diff --git a/.circleci/config.yml b/.circleci/config.yml index c5b0d3dc6f10..c3611c57351a 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -82,7 +82,6 @@ jobs: - ~/.bundle - ~/.go_workspace - ~/.gradle - - ~/.pub-cache - ~/.cache/bower - ".git" - ~/.stack diff --git a/.github/actions/run-samples/action.yaml b/.github/actions/run-samples/action.yaml new file mode 100644 index 000000000000..64bc77458620 --- /dev/null +++ b/.github/actions/run-samples/action.yaml @@ -0,0 +1,19 @@ +name: 'Run samples' +description: 'Runs sample integration test profile with Maven' +inputs: + name: + description: 'The Maven profile name' + required: true + goal: + description: 'Maven goal' + required: false + default: 'verify' + args: + description: 'Additional maven arguments' + required: false + default: '' +runs: + using: "composite" + steps: + - run: mvn --no-snapshot-updates --batch-mode --quiet ${{ inputs.goal }} -P${{ inputs.name }} -Dintegration-test -Dmaven.javadoc.skip=true ${{ inputs.args }} + shell: bash \ No newline at end of file diff --git a/.github/workflows/check-supported-versions.yaml b/.github/workflows/check-supported-versions.yaml index 35c95b5b2aa5..56992b9811e0 100644 --- a/.github/workflows/check-supported-versions.yaml +++ b/.github/workflows/check-supported-versions.yaml @@ -24,18 +24,19 @@ jobs: uses: actions/checkout@v2 - name: Set up JDK ${{ matrix.java }} - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: + distribution: 'adopt' java-version: ${{ matrix.java }} - - uses: actions/cache@v2.1.4 + - uses: actions/cache@v2.1.5 with: path: ~/.m2/repository key: ${{ runner.os }}-maven-${{ hashFiles('pom.xml', 'modules/**/pom.xml') }} restore-keys: | ${{ runner.os }}-maven- - - uses: actions/cache@v2.1.4 + - uses: actions/cache@v2.1.5 with: path: | ~/.gradle/caches @@ -49,7 +50,7 @@ jobs: run: mvn -nsu -B --quiet -Djacoco.skip=true -Dorg.slf4j.simpleLogger.defaultLogLevel=error --no-transfer-progress clean install --file pom.xml ${{ matrix.flags }} - name: Upload Maven build artifact - uses: actions/upload-artifact@v2.2.2 + uses: actions/upload-artifact@v2.2.3 if: matrix.java == '8' && matrix.os == 'ubuntu-latest' with: name: artifact diff --git a/.github/workflows/openapi-generator-test-results.yaml b/.github/workflows/openapi-generator-test-results.yaml new file mode 100644 index 000000000000..f246b16c36b1 --- /dev/null +++ b/.github/workflows/openapi-generator-test-results.yaml @@ -0,0 +1,19 @@ +name: OpenAPI Generator Test Report + +on: + workflow_run: + workflows: ['OpenAPI Generator'] + types: + - completed + +# separate workflow required due to https://github.com/dorny/test-reporter#recommended-setup-for-public-repositories +jobs: + report: + runs-on: ubuntu-latest + steps: + - uses: dorny/test-reporter@v1 + with: + artifact: surefire-test-results + name: JUnit Test results + path: '**/surefire-reports/TEST-*.xml' + reporter: java-junit diff --git a/.github/workflows/openapi-generator.yaml b/.github/workflows/openapi-generator.yaml new file mode 100644 index 000000000000..5bb78a6f3b02 --- /dev/null +++ b/.github/workflows/openapi-generator.yaml @@ -0,0 +1,214 @@ +name: OpenAPI Generator + +on: + push: + branches: + - master + - '[5-9]+.[0-9]+.x' + pull_request: + branches: + - master + - '[5-9]+.[0-9]+.x' + +jobs: + build: + name: Build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 8 + uses: actions/setup-java@v1 + with: + java-version: 8 + - name: Cache maven dependencies + uses: actions/cache@v2 + env: + cache-name: cache-maven-repository + with: + path: | + ~/.m2/repository + ~/.gradle + !~/.gradle/caches/*/plugin-resolution/ + !~/.m2/repository/org/openapitools/ + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + - name: Run maven + run: mvn --no-snapshot-updates --batch-mode --quiet install -DskipTests -Dorg.slf4j.simpleLogger.defaultLogLevel=error + - run: ls -la modules/openapi-generator-cli/target + - name: Upload openapi-generator-cli.jar artifact + uses: actions/upload-artifact@v2 + with: + name: openapi-generator-cli.jar + path: modules/openapi-generator-cli/target/openapi-generator-cli.jar + retention-days: 1 + + test: + name: Unit tests + runs-on: ubuntu-latest + needs: + - build + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 8 + uses: actions/setup-java@v1 + with: + java-version: 8 + - name: Cache maven dependencies + uses: actions/cache@v2 + env: + cache-name: cache-maven-repository + with: + path: | + ~/.m2/repository + ~/.gradle + !~/.gradle/caches/*/plugin-resolution/ + !~/.m2/repository/org/openapitools/ + key: ${{ runner.os }}-test-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + - name: Run unit tests + run: mvn --no-snapshot-updates --batch-mode --quiet --fail-at-end test -Dorg.slf4j.simpleLogger.defaultLogLevel=error + - name: Publish unit test reports + if: ${{ always() }} + uses: actions/upload-artifact@v2 + with: + name: surefire-test-results + path: '**/surefire-reports/TEST-*.xml' + + documentation: + name: Docs up-to-date + runs-on: ubuntu-latest + needs: + - build + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 8 + uses: actions/setup-java@v1 + with: + java-version: 8 + - name: Download openapi-generator-cli.jar artifact + uses: actions/download-artifact@v2 + with: + name: openapi-generator-cli.jar + path: modules/openapi-generator-cli/target + - name: Generate docs + run: | + bash bin/meta-codegen.sh + bash bin/utils/export_docs_generators.sh + bash bin/utils/copy-to-website.sh + bash bin/utils/export_generators_readme.sh + - name: Verify git status + run: | + if [[ "$(git status --porcelain)" != "" ]]; then + echo "UNCOMMITTED CHANGES ERROR" + echo "There are uncommitted changes in working tree after execution of 'bin/ensure-up-to-date'" + echo "Perform git diff" + git --no-pager diff + echo "Perform git status" + git status + echo -e "\nThis script runs in pull requests against the anticipated merge commit (as if the PR was merged now)." + echo "When you see unexpected files here, it likely means that there are newer commits in master that you need to " + echo -e "rebase or merge into your branch.\n" + echo "Please run 'bin/utils/ensure-up-to-date' locally and commit changes (UNCOMMITTED CHANGES ERROR)" + exit 1 + fi + + samples: + name: Samples up-to-date + needs: + - build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 8 + uses: actions/setup-java@v1 + with: + java-version: 8 + - name: Download openapi-generator-cli.jar artifact + uses: actions/download-artifact@v2 + with: + name: openapi-generator-cli.jar + path: modules/openapi-generator-cli/target + - name: Generate samples + run: bash bin/generate-samples.sh + - name: Verify git status + run: | + if [[ "$(git status --porcelain)" != "" ]]; then + echo "UNCOMMITTED CHANGES ERROR" + echo "There are uncommitted changes in working tree after execution of 'bin/generate-samples.sh'" + echo "Perform git diff" + git --no-pager diff + echo "Perform git status" + git status + echo -e "\nThis script runs in pull requests against the anticipated merge commit (as if the PR was merged now)." + echo "When you see unexpected files here, it likely means that there are newer commits in master that you need to " + echo -e "rebase or merge into your branch.\n" + echo "Please run 'bin/generate-samples.sh' locally and commit changes (UNCOMMITTED CHANGES ERROR)" + exit 1 + fi + + test-maven-plugin: + name: Maven plugin tests + runs-on: ubuntu-latest + needs: + - build + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 11 + uses: actions/setup-java@v1 + with: + java-version: 11 + - name: Cache maven dependencies + uses: actions/cache@v2 + env: + cache-name: cache-maven-repository + with: + path: | + ~/.m2/repository + ~/.gradle + !~/.gradle/caches/*/plugin-resolution/ + !~/.m2/repository/org/openapitools/ + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-test-maven-plugin-${{ env.cache-name }}- + ${{ runner.os }}-test-maven-plugin- + - name: Run tests + run: | + mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/java-client.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error + mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/multi-module/pom.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error + mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/kotlin.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error + mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/spring.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error + + test-gradle-plugin: + name: Gradle plugin tests + runs-on: ubuntu-latest + needs: + - build + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 11 + uses: actions/setup-java@v1 + with: + java-version: 11 + - name: Cache maven dependencies + uses: actions/cache@v2 + env: + cache-name: cache-maven-repository + with: + path: | + ~/.m2/repository + ~/.gradle + !~/.gradle/caches/modules-2/modules-2.lock + !~/.gradle/caches/*/plugin-resolution/ + !~/.m2/repository/org/openapitools/ + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-test-gradle-plugin-${{ env.cache-name }}- + ${{ runner.os }}-test-gradle-plugin- + - name: Run tests + run: | + (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew buildGoSdk) + (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew openApiGenerate) diff --git a/.github/workflows/samples-dart.yaml b/.github/workflows/samples-dart.yaml new file mode 100644 index 000000000000..a1392d65e7c8 --- /dev/null +++ b/.github/workflows/samples-dart.yaml @@ -0,0 +1,78 @@ +name: Samples Dart + +on: + push: + branches: + - master + - '[5-9]+.[0-9]+.x' + pull_request: + branches: + - master + - '[5-9]+.[0-9]+.x' + +jobs: + tests-dart-2-10: + name: Tests Dart 2.10 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-java@v2 + with: + distribution: 'adopt' + java-version: 8 + - name: Cache maven dependencies + uses: actions/cache@v2 + env: + cache-name: maven-repository + with: + path: | + ~/.m2/repository + ~/.gradle + key: ${{ runner.os }}-${{ github.job }}-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} + - name: Cache test dependencies + uses: actions/cache@v2 + env: + cache-name: pub-cache + with: + path: $PUB_CACHE + key: ${{ runner.os }}-${{ github.job }}-${{ env.cache-name }}-${{ hashFiles('samples/**/pubspec.yaml') }} + - uses: dart-lang/setup-dart@v1 + with: + sdk: 2.10.5 + - name: Run tests + uses: ./.github/actions/run-samples + with: + name: samples.dart-2.10 + + tests-dart-2-13: + name: Tests Dart 2.13 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-java@v2 + with: + distribution: 'adopt' + java-version: 8 + - name: Cache maven dependencies + uses: actions/cache@v2 + env: + cache-name: maven-repository + with: + path: | + ~/.m2/repository + ~/.gradle + key: ${{ runner.os }}-${{ github.job }}-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} + - name: Cache test dependencies + uses: actions/cache@v2 + env: + cache-name: pub-cache + with: + path: $PUB_CACHE + key: ${{ runner.os }}-${{ github.job }}-${{ env.cache-name }}-${{ hashFiles('samples/**/pubspec.yaml') }} + - uses: dart-lang/setup-dart@v1 + with: + sdk: 2.13.0 + - name: Run tests + uses: ./.github/actions/run-samples + with: + name: samples.dart-2.13 diff --git a/.github/workflows/samples-kotlin.yaml b/.github/workflows/samples-kotlin.yaml new file mode 100644 index 000000000000..faa5062c5530 --- /dev/null +++ b/.github/workflows/samples-kotlin.yaml @@ -0,0 +1,64 @@ +name: Samples Kotlin + +on: + push: + branches: + - master + - '[5-9]+.[0-9]+.x' + pull_request: + branches: + - master + - '[5-9]+.[0-9]+.x' + +env: + GRADLE_VERSION: 6.9 + +jobs: + build: + name: Build Kotlin + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + sample: + - samples/client/petstore/kotlin + - samples/client/petstore/kotlin-gson + - samples/client/petstore/kotlin-jackson + # needs Android configured + #- samples/client/petstore/kotlin-json-request-string + - samples/client/petstore/kotlin-jvm-okhttp4-coroutines + - samples/client/petstore/kotlin-moshi-codegen + # need some special setup + #- samples/client/petstore/kotlin-multiplatform + - samples/client/petstore/kotlin-nonpublic + - samples/client/petstore/kotlin-nullable + - samples/client/petstore/kotlin-okhttp3 + - samples/client/petstore/kotlin-retrofit2 + - samples/client/petstore/kotlin-retrofit2-kotlinx_serialization + - samples/client/petstore/kotlin-retrofit2-rx3 + - samples/client/petstore/kotlin-string + - samples/client/petstore/kotlin-threetenbp + - samples/client/petstore/kotlin-uppercase-enum + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-java@v2 + with: + distribution: 'adopt' + java-version: 8 + - name: Cache maven dependencies + uses: actions/cache@v2 + env: + cache-name: maven-repository + with: + path: | + ~/.gradle + key: ${{ runner.os }}-${{ github.job }}-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} + - name: Install Gradle wrapper + uses: eskatos/gradle-command-action@v1 + with: + gradle-version: ${{ env.GRADLE_VERSION }} + build-root-directory: ${{ matrix.sample }} + arguments: wrapper + - name: Build + working-directory: ${{ matrix.sample }} + run: ./gradlew build -x test diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index bc4992833b73..d991e052a7d6 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -14,8 +14,9 @@ jobs: steps: - uses: actions/checkout@v1 - name: Set up JDK 11 - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: + distribution: 'adopt' java-version: 11 - name: Compile with Maven run: mvn -B -q clean install jacoco:report diff --git a/.gitignore b/.gitignore index b56824e26e3c..3a964a0bc5e3 100644 --- a/.gitignore +++ b/.gitignore @@ -177,7 +177,6 @@ samples/client/petstore/python-tornado/.venv/ # PHP samples/client/petstore/php/OpenAPIClient-php/composer.lock samples/openapi3/server/petstore/php-symfony/SymfonyBundle-php/composer.lock -samples/openapi3/server/petstore/php-mezzio-ph/composer.lock samples/server/petstore/php-laravel/lib/composer.lock samples/server/petstore/php-lumen/lib/composer.lock samples/server/petstore/php-slim4/composer.lock diff --git a/.travis.yml b/.travis.yml index 9ba0b842f02c..7deb298f0fa1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -62,17 +62,25 @@ addons: - petstore.swagger.io before_install: + - sudo rm -rf /var/lib/apt/lists/* + - curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - + - sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) edge" + - sudo apt-get update + - sudo apt-get -y -o Dpkg::Options::="--force-confnew" install docker-ce + - mkdir -vp ~/.docker/cli-plugins/ + - curl --silent -L "https://github.com/docker/buildx/releases/download/v0.3.0/buildx-v0.3.0.linux-amd64" > ~/.docker/cli-plugins/docker-buildx + - chmod a+x ~/.docker/cli-plugins/docker-buildx # to run petstore server locally via docker - echo "$DOCKER_HUB_PASSWORD" | docker login --username=$DOCKER_HUB_USERNAME --password-stdin || true - docker pull swaggerapi/petstore - docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore - docker ps -a # install crystal - - curl -sSL https://dist.crystal-lang.org/apt/setup.sh | sudo bash - - curl -sL "https://keybase.io/crystal/pgp_keys.asc" | sudo apt-key add - - - echo "deb https://dist.crystal-lang.org/apt crystal main" | sudo tee /etc/apt/sources.list.d/crystal.list - - sudo apt-get update + - echo 'deb http://download.opensuse.org/repositories/devel:/languages:/crystal/xUbuntu_16.04/ /' | sudo tee /etc/apt/sources.list.d/devel:languages:crystal.list + - curl -fsSL https://download.opensuse.org/repositories/devel:languages:crystal/xUbuntu_16.04/Release.key | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/devel_languages_crystal.gpg > /dev/null + - sudo apt update - sudo apt install crystal + - crystal --version - curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version 1.22.0 - export PATH="$HOME/.yarn/bin:$PATH" # install rust @@ -149,6 +157,8 @@ install: script: # fail fast - set -e + # show docker buildx version + - docker buildx version # fail if the template files contains tabs - /bin/bash ./bin/utils/detect_tab_in_templates.sh # fail if the test files have changes @@ -199,12 +209,14 @@ after_success: echo "$DOCKER_HUB_PASSWORD" | docker login --username=$DOCKER_HUB_USERNAME --password-stdin; export cli_version=$(\mvn -o org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate -Dexpression=project.version | grep -v '\['); export build_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ"); - docker build --label=org.opencontainers.image.created=$build_date --label=org.opencontainers.image.title=openapi-generator-online --label=org.opencontainers.image.revision=$TRAVIS_COMMIT --label=org.opencontainers.image.version=$cli_version -t $DOCKER_GENERATOR_IMAGE_NAME ./modules/openapi-generator-online; + docker buildx create --use; if [ ! -z "$TRAVIS_TAG" ]; then - docker tag $DOCKER_GENERATOR_IMAGE_NAME:latest $DOCKER_GENERATOR_IMAGE_NAME:$TRAVIS_TAG; + docker buildx build --platform linux/amd64,linux/arm64 --label=org.opencontainers.image.created=$build_date --label=org.opencontainers.image.title=openapi-generator-online --label=org.opencontainers.image.revision=$TRAVIS_COMMIT --label=org.opencontainers.image.version=$cli_version -t $DOCKER_GENERATOR_IMAGE_NAME:latest -t $DOCKER_GENERATOR_IMAGE_NAME:$TRAVIS_TAG -t $DOCKER_GENERATOR_IMAGE_NAME ./modules/openapi-generator-online; + echo "Built and tagged $DOCKER_GENERATOR_IMAGE_NAME"; fi; - if [ ! -z "$TRAVIS_TAG" ] || [ "$TRAVIS_BRANCH" = "master" ]; then - docker push $DOCKER_GENERATOR_IMAGE_NAME && echo "Pushed to $DOCKER_GENERATOR_IMAGE_NAME"; + if [ -z "$TRAVIS_TAG" ] && [ "$TRAVIS_BRANCH" = "master" ] && [ "$TRAVIS_PULL_REQUEST" = "false" ]; then + docker buildx build --push --platform linux/amd64,linux/arm64 --label=org.opencontainers.image.created=$build_date --label=org.opencontainers.image.title=openapi-generator-online --label=org.opencontainers.image.revision=$TRAVIS_COMMIT --label=org.opencontainers.image.version=$cli_version -t $DOCKER_GENERATOR_IMAGE_NAME ./modules/openapi-generator-online; + echo "Pushed to $DOCKER_GENERATOR_IMAGE_NAME for master"; fi; fi; ## docker: build cli image and push to Docker Hub @@ -213,12 +225,14 @@ after_success: cp docker-entrypoint.sh ./modules/openapi-generator-cli; export cli_version=$(\mvn -o org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate -Dexpression=project.version | grep -v '\['); export build_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ"); - docker build --label=org.opencontainers.image.created=$build_date --label=org.opencontainers.image.title=openapi-generator-cli --label=org.opencontainers.image.revision=$TRAVIS_COMMIT --label=org.opencontainers.image.version=$cli_version -t $DOCKER_CODEGEN_CLI_IMAGE_NAME ./modules/openapi-generator-cli; + docker buildx create --use; + docker buildx build --platform linux/amd64,linux/arm64 --label=org.opencontainers.image.created=$build_date --label=org.opencontainers.image.title=openapi-generator-cli --label=org.opencontainers.image.revision=$TRAVIS_COMMIT --label=org.opencontainers.image.version=$cli_version -t $DOCKER_CODEGEN_CLI_IMAGE_NAME ./modules/openapi-generator-cli; if [ ! -z "$TRAVIS_TAG" ]; then - docker tag $DOCKER_CODEGEN_CLI_IMAGE_NAME:latest $DOCKER_CODEGEN_CLI_IMAGE_NAME:$TRAVIS_TAG; + docker buildx build --platform linux/amd64,linux/arm64 --label=org.opencontainers.image.created=$build_date --label=org.opencontainers.image.title=openapi-generator-cli --label=org.opencontainers.image.revision=$TRAVIS_COMMIT --label=org.opencontainers.image.version=$cli_version -t $DOCKER_CODEGEN_CLI_IMAGE_NAME:latest -t $DOCKER_CODEGEN_CLI_IMAGE_NAME:$TRAVIS_TAG -t $DOCKER_CODEGEN_CLI_IMAGE_NAME ./modules/openapi-generator-cli; + echo "Built and tagged $DOCKER_GENERATOR_IMAGE_NAME"; fi; - if [ ! -z "$TRAVIS_TAG" ] || [ "$TRAVIS_BRANCH" = "master" ]; then - docker push $DOCKER_CODEGEN_CLI_IMAGE_NAME; + if [ -z "$TRAVIS_TAG" ] && [ "$TRAVIS_BRANCH" = "master" ] && [ "$TRAVIS_PULL_REQUEST" = "false" ]; then + docker buildx build --push --platform linux/amd64,linux/arm64 --label=org.opencontainers.image.created=$build_date --label=org.opencontainers.image.title=openapi-generator-cli --label=org.opencontainers.image.revision=$TRAVIS_COMMIT --label=org.opencontainers.image.version=$cli_version -t $DOCKER_CODEGEN_CLI_IMAGE_NAME ./modules/openapi-generator-cli; echo "Pushed to $DOCKER_CODEGEN_CLI_IMAGE_NAME"; fi; fi; diff --git a/CI/.drone.yml b/CI/.drone.yml index 49495e430941..073d7332a433 100644 --- a/CI/.drone.yml +++ b/CI/.drone.yml @@ -1,7 +1,20 @@ kind: pipeline name: default - steps: +# test Java 11 HTTP client +- name: java11-test + image: openjdk:11.0 + commands: + - ./mvnw --quiet clean install -Dorg.slf4j.simpleLogger.defaultLogLevel=error + - ./mvnw --quiet verify -Psamples.droneio -Dorg.slf4j.simpleLogger.defaultLogLevel=error + # test java native client + - ./mvnw clean test -f samples/client/petstore/java/native/pom.xml + - ./mvnw clean test -f samples/client/petstore/java/native-async/pom.xml + - ./mvnw clean test -f samples/openapi3/client/petstore/java/native/pom.xml + # test all generators with fake petstore spec (2.0, 3.0) + - /bin/bash bin/utils/test-fake-petstore-for-all.sh + # generate test scripts + - /bin/bash bin/tests/run-all-test # test nim client - name: nim-client-test image: nimlang/nim @@ -37,22 +50,12 @@ steps: - name: haskell-client-test image: haskell:8.6.5 commands: - - (cd samples/client/petstore/haskell-http-client/ && stack --install-ghc --no-haddock-deps haddock --fast && stack test --fast) -# test Java 11 HTTP client -- name: java11-test - image: openjdk:11.0 + - (cd samples/client/petstore/haskell-http-client/ && stack --allow-different-user --install-ghc --no-haddock-deps haddock --fast && stack --allow-different-user test --fast) +# test erlang client and server +- name: erlang + image: erlang:alpine commands: - - ./mvnw --quiet clean install -Dorg.slf4j.simpleLogger.defaultLogLevel=error - - ./mvnw --quiet verify -Psamples.droneio -Dorg.slf4j.simpleLogger.defaultLogLevel=error - # test java native client - - ./mvnw clean test -f samples/client/petstore/java/native/pom.xml - - ./mvnw clean test -f samples/client/petstore/java/native-async/pom.xml - - ./mvnw clean test -f samples/openapi3/client/petstore/java/native/pom.xml - # test all generators with fake petstore spec (2.0, 3.0) - - /bin/bash bin/utils/test-fake-petstore-for-all.sh - # generate test scripts - - /bin/bash bin/tests/run-all-test - # generate all petstore samples (client, servers, doc) - - /bin/bash bin/generate-samples.sh - # generate all petstore samples (openapi3) - - /bin/bash bin/generate-samples.sh bin/configs/other/*.yaml + - (cd samples/client/petstore/erlang-client && rebar3 compile) + - (cd samples/client/petstore/erlang-proper && rebar3 compile) + # comment out as the tests pass locally but not in the CI + #- (cd samples/server/petstore/erlang-server && rebar3 compile) diff --git a/CI/circle_parallel.sh b/CI/circle_parallel.sh index e66f55242567..f1a5a529a791 100755 --- a/CI/circle_parallel.sh +++ b/CI/circle_parallel.sh @@ -14,17 +14,6 @@ function cleanup { trap cleanup EXIT -function installDart { - # install dart2 - sudo apt-get update - sudo apt-get install apt-transport-https - sudo sh -c 'wget -qO- https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -' - sudo sh -c 'wget -qO- https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_stable.list > /etc/apt/sources.list.d/dart_stable.list' - sudo apt-get update - sudo apt-get install dart - export PATH="$PATH:/usr/lib/dart/bin" -} - if [ "$NODE_INDEX" = "1" ]; then echo "Running node $NODE_INDEX to test 'samples.circleci' defined in pom.xml ..." java -version @@ -35,20 +24,6 @@ if [ "$NODE_INDEX" = "1" ]; then ls -l /home/circleci/.ivy2/cache elif [ "$NODE_INDEX" = "2" ]; then - installDart - - # run ensure-up-to-date sample script on SNAPSHOT version only - project_version=`mvn org.apache.maven.plugins:maven-help-plugin:3.1.0:evaluate -Dexpression=project.version -q -DforceStdout` - if [[ $project_version == *"-SNAPSHOT" ]]; then - echo "Running node $NODE_INDEX to test ensure-up-to-date" - java -version - - # clear any changes to the samples - git checkout -- . - - # look for outdated samples - ./bin/utils/ensure-up-to-date - fi echo "Running node $NODE_INDEX to test haskell" # install haskell curl -sSL https://get.haskellstack.org/ | sh diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 30258ec9fd6c..0fe833163afa 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -48,6 +48,7 @@ Code change should conform to the programming style guide of the respective lang - C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx - C++: https://google.github.io/styleguide/cppguide.html - C++ (Tizen): https://wiki.tizen.org/Native_Platform_Coding_Idiom_and_Style_Guide#C.2B.2B_Coding_Style +- C++ (Unreal Engine 4): https://docs.unrealengine.com/en-US/ProductionPipelines/DevelopmentSetup/CodingStandard/index.html - Clojure: https://github.com/bbatsov/clojure-style-guide - Crystal: https://crystal-lang.org/reference/conventions/coding_style.html - Dart: https://www.dartlang.org/guides/language/effective-dart/style diff --git a/README.md b/README.md index 84a876cf0b80..f02a8ada352e 100644 --- a/README.md +++ b/README.md @@ -9,27 +9,17 @@
-[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`5.1.1`): +[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`5.2.0`): [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator) [![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator) -[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=master)](https://app.shippable.com/github/OpenAPITools/openapi-generator) [![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=master&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu) [![JDK11 Build](https://cloud.drone.io/api/badges/OpenAPITools/openapi-generator/status.svg?ref=refs/heads/master)](https://cloud.drone.io/OpenAPITools/openapi-generator) [![Bitrise](https://img.shields.io/bitrise/4a2b10a819d12b67/master?label=bitrise%3A%20Swift+4,5&token=859FMDR8QHwabCzwvZK6vQ)](https://app.bitrise.io/app/4a2b10a819d12b67) [![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/openapitools/openapi-generator/Check%20Supported%20Java%20Versions/master?label=Check%20Supported%20Java%20Versions&logo=github&logoColor=green)](https://github.com/OpenAPITools/openapi-generator/actions?query=workflow%3A%22Check+Supported+Java+Versions%22) -[5.2.x](https://github.com/OpenAPITools/openapi-generator/tree/5.2.x) (`5.2.x`): -[![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/5.2.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator) -[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/5.2.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator) -[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=5.2.x)](https://app.shippable.com/github/OpenAPITools/openapi-generator) -[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=5.2.x&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu) -[![JDK11 Build](https://cloud.drone.io/api/badges/OpenAPITools/openapi-generator/status.svg?ref=refs/heads/5.2.x)](https://cloud.drone.io/OpenAPITools/openapi-generator) -[![Bitrise](https://img.shields.io/bitrise/4a2b10a819d12b67/5.2.x?label=bitrise%3A%20Swift+4,5&token=859FMDR8QHwabCzwvZK6vQ)](https://app.bitrise.io/app/4a2b10a819d12b67) - [6.0.x](https://github.com/OpenAPITools/openapi-generator/tree/6.0.x) (`6.0.x`): [![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/6.0.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator) [![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/6.0.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator) -[![Run Status](https://api.shippable.com/projects/5af6bf74e790f4070084a115/badge?branch=6.0.x)](https://app.shippable.com/github/OpenAPITools/openapi-generator) [![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=6.0.x&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu) [![JDK11 Build](https://cloud.drone.io/api/badges/OpenAPITools/openapi-generator/status.svg?ref=refs/heads/6.0.x)](https://cloud.drone.io/OpenAPITools/openapi-generator) [![Bitrise](https://img.shields.io/bitrise/4a2b10a819d12b67/6.0.x?label=bitrise%3A%20Swift+4,5&token=859FMDR8QHwabCzwvZK6vQ)](https://app.bitrise.io/app/4a2b10a819d12b67) @@ -77,11 +67,11 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se | | Languages/Frameworks | | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0, .NET 5.0. Libraries: RestSharp, HttpClient), **C++** (cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client), **k6**, **Kotlin**, **Lua**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (hyper, reqwest, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (2.x - 11.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, redux-query, Rxjs) | -| **Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin), **Haskell** (Servant), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra) | +| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0, .NET 5.0. Libraries: RestSharp, HttpClient), **C++** (Arduino, cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client), **k6**, **Kotlin**, **Lua**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (hyper, reqwest, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (2.x - 11.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, redux-query, Rxjs) | +| **Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (FastAPI, Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra) | | **API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc**, **Markdown**, **PlantUML** | | **Configuration files** | [**Apache2**](https://httpd.apache.org/) | -| **Others** | **GraphQL**, **JMeter**, **Ktorm**, **MySQL Schema**, **Protocol Buffer** | +| **Others** | **GraphQL**, **JMeter**, **Ktorm**, **MySQL Schema**, **Protocol Buffer**, **WSDL** | ## Table of contents @@ -120,9 +110,8 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20 | OpenAPI Generator Version | Release Date | Notes | | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------- | | 6.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/6.0.0-SNAPSHOT/) | Nov/Dec 2021 | Minor release with breaking changes (no fallback) | -| 5.2.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.2.0-SNAPSHOT/) | May/Jun 2021 | Minor release with breaking changes (with fallback) | -| 5.1.1 (upcoming patch release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.1.1-SNAPSHOT/) | Apr/May 2021 | Patch release (enhancements, bug fixes, etc) | -| [5.1.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.1.0) (latest stable release) | 20.03.2021 | Minor release with breaking changes (with fallback) | +| 5.2.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.2.0-SNAPSHOT/) | Jun/Jul 2021 | Minor release with breaking changes (with fallback) | +| [5.1.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.1.1) (latest stable release) | 07.05.2021 | Patch release (enhancements, bug fixes, etc) | | [4.3.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v4.3.1) | 06.05.2020 | Patch release (enhancements, bug fixes, etc) | OpenAPI Spec compatibility: 1.0, 1.1, 1.2, 2.0, 3.0 @@ -179,16 +168,16 @@ See the different versions of the [openapi-generator-cli](https://mvnrepository. If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 8 runtime at a minimum): -JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.0/openapi-generator-cli-5.1.0.jar` +JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.1/openapi-generator-cli-5.1.1.jar` For **Mac/Linux** users: ```sh -wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.0/openapi-generator-cli-5.1.0.jar -O openapi-generator-cli.jar +wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.1/openapi-generator-cli-5.1.1.jar -O openapi-generator-cli.jar ``` For **Windows** users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g. ``` -Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.0/openapi-generator-cli-5.1.0.jar +Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.1/openapi-generator-cli-5.1.1.jar ``` After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage. @@ -413,7 +402,7 @@ openapi-generator-cli version To use a specific version of "openapi-generator-cli" ```sh -openapi-generator-cli version-manager set 5.1.0 +openapi-generator-cli version-manager set 5.1.1 ``` Or install it as dev-dependency: @@ -437,7 +426,7 @@ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generat (if you're on Windows, replace the last command with `java -jar modules\openapi-generator-cli\target\openapi-generator-cli.jar generate -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g php -o c:\temp\php_api_client`) -You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.0/openapi-generator-cli-5.1.0.jar) +You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.1/openapi-generator-cli-5.1.1.jar) To get a list of **general** options available, please run `java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar help generate` @@ -562,7 +551,7 @@ When code is generated from this project, it shall be considered **AS IS** and o ### [3.5 - IDE Integration](#table-of-contents) -Here is a list of community-conitributed IDE plug-ins that integrate with OpenAPI Generator: +Here is a list of community-contributed IDE plug-ins that integrate with OpenAPI Generator: - Eclipse: [Codewind OpenAPI Tools for Eclipse](https://www.eclipse.org/codewind/open-api-tools-for-eclipse.html) by [IBM](https://www.ibm.com) - IntelliJ IDEA: [OpenAPI Generator](https://plugins.jetbrains.com/plugin/8433-openapi-generator) by [Jim Schubert](https://jimschubert.us/#/) @@ -575,6 +564,7 @@ Here is a list of community-conitributed IDE plug-ins that integrate with OpenAP ## [4 - Companies/Projects using OpenAPI Generator](#table-of-contents) Here are some companies/projects (alphabetical order) using OpenAPI Generator in production. To add your company/project to the list, please visit [README.md](README.md) and click on the icon to edit the page. +- [Aalborg University](https://www.aau.dk) - [Adaptant Solutions AG](https://www.adaptant.io/) - [adesso SE](https://www.adesso.de/) - [Agoda](https://www.agoda.com/) @@ -659,12 +649,14 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in - [Stingray](http://www.stingray.com) - [Suva](https://www.suva.ch/) - [Telstra](https://dev.telstra.com) +- [The University of Aizu](https://www.u-aizu.ac.jp/en/) - [TravelTime platform](https://www.traveltimeplatform.com/) - [TribalScale](https://www.tribalscale.com) - [TUI InfoTec GmbH](http://www.tui-infotec.com/) - [Twitter](https://twitter.com) - [unblu inc.](https://www.unblu.com/) - [Veamly](https://www.veamly.com/) +- [VMWare](https://www.vmware.com/) - [wbt-solutions](https://www.wbt-solutions.de/) - [Woleet](https://www.woleet.io/) - [WSO2](https://wso2.com/) @@ -820,6 +812,9 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in - 2021-03-28 - [Trying out NestJS part 4: Generate Typescript clients from OpenAPI documents](https://dev.to/arnaudcortisse/trying-out-nestjs-part-4-generate-typescript-clients-from-openapi-documents-28mk) by [Arnaud Cortisse](https://dev.to/arnaudcortisse) - 2021-03-31 - [Open API Server Implementation Using OpenAPI Generator](https://www.baeldung.com/java-openapi-generator-server) at [Baeldung](https://www.baeldung.com/) - 2021-03-31 - [使用OpenAPI Generator實現Open API Server](https://www.1ju.org/article/java-openapi-generator-server) at [億聚網](https://www.1ju.org/) +- 2021-04-19 - [Introducing Twilio’s OpenAPI Specification Beta](https://www.twilio.com/blog/introducing-twilio-open-api-specification-beta) by [GARETH PAUL JONES](https://www.twilio.com/blog/author/gpj) at [Twilio Blog](https://www.twilio.com/blog) +- 2021-04-22 - [Leveraging OpenApi strengths in a Micro-Service environment](https://medium.com/unibuddy-technology-blog/leveraging-openapi-strengths-in-a-micro-service-environment-3d7f9e7c26ff) by Nicolas Jellab at [Unibuddy Technology Blog](https://medium.com/unibuddy-technology-blog) +- 2021-04-27 - [From zero to publishing PowerShell API clients in PowerShell Gallery within minutes](https://speakerdeck.com/wing328/from-zero-to-publishing-powershell-api-clients-in-powershell-gallery-within-minutes) by [William Cheng](https://github.com/wing328) at [PowerShell + DevOps Global Summit 2021](https://events.devopscollective.org/event/powershell-devops-global-summit-2021/) ## [6 - About Us](#table-of-contents) @@ -849,6 +844,7 @@ Here is a list of template creators: * Bash: @bkryza * C: @PowerOfCreation @zhemant [:heart:](https://www.patreon.com/zhemant) * C++ REST: @Danielku15 + * C++ Tiny: @AndersSpringborg * C++ UE4: @Kahncode * C# (.NET 2.0): @who * C# (.NET Standard 1.3 ): @Gronsak @@ -932,6 +928,7 @@ Here is a list of template creators: * Erlang Server: @galaxie * F# (Giraffe) Server: @nmfisher * Go Server: @guohuang + * Go (Echo) Server: @ph4r5h4d * Go (Gin) Server: @kemokemo * GraphQL Express Server: @renepardon * Haskell Servant: @algas @@ -954,6 +951,7 @@ Here is a list of template creators: * PHP Slim: @jfastnacht * PHP Symfony: @ksm2 * PHP Zend Expressive (with Path Handler): @Articus + * Python FastAPI: @krjakbrjak * Python AIOHTTP: @Jyhess * Ruby on Rails 5: @zlx * Rust (rust-server): @metaswitch @@ -975,6 +973,7 @@ Here is a list of template creators: * Ktorm: @Luiz-Monad * MySQL: @ybelenko * Protocol Buffer: @wing328 + * WSDL @adessoDpd :heart: = Link to support the contributor directly @@ -1016,7 +1015,7 @@ If you want to join the committee, please kindly apply by sending an email to te | Bash | @frol (2017/07) @bkryza (2017/08) @kenjones-cisco (2017/09) | | C | @zhemant (2018/11) @ityuhui (2019/12) @michelealbano (2020/03) | | C++ | @ravinikam (2017/07) @stkrwork (2017/07) @etherealjoy (2018/02) @martindelille (2018/03) @muttleyxd (2019/08) | -| C# | @mandrean (2017/08) @frankyjuang (2019/09) @shibayan (2020/02) @Blackclaws (2021/03) | +| C# | @mandrean (2017/08) @frankyjuang (2019/09) @shibayan (2020/02) @Blackclaws (2021/03) @lucamazzanti (2021/05) | | Clojure | | | Dart | @swipesight (2018/09) @jaumard (2018/09) @josh-burton (2019/12) @amondnet (2019/12) @sbu-WBT (2020/12) @kuhnroyal (2020/12) @agilob (2020/12) | | Eiffel | @jvelilla (2017/09) | @@ -1024,7 +1023,7 @@ If you want to join the committee, please kindly apply by sending an email to te | Elm | @eriktim (2018/09) | | Erlang | @tsloughter (2017/11) @jfacorro (2018/10) @robertoaloi (2018/10) | | F# | @nmfisher (2019/05) | -| Go | @antihax (2017/11) @grokify (2018/07) @kemokemo (2018/09) @jirikuncar (2021/01) | +| Go | @antihax (2017/11) @grokify (2018/07) @kemokemo (2018/09) @jirikuncar (2021/01) @ph4r5h4d (2021/04) | | GraphQL | @renepardon (2018/12) | | Groovy | | | Haskell | | diff --git a/bin/configs/other/bash.yaml b/bin/configs/bash.yaml similarity index 100% rename from bin/configs/other/bash.yaml rename to bin/configs/bash.yaml diff --git a/bin/configs/other/cpp-pistache-server-cpp-pistache.yaml b/bin/configs/cpp-pistache-server-cpp-pistache.yaml similarity index 100% rename from bin/configs/other/cpp-pistache-server-cpp-pistache.yaml rename to bin/configs/cpp-pistache-server-cpp-pistache.yaml diff --git a/bin/configs/cpp-qt5-client.yaml b/bin/configs/cpp-qt-client.yaml similarity index 72% rename from bin/configs/cpp-qt5-client.yaml rename to bin/configs/cpp-qt-client.yaml index dc36141b436b..14f4a2745003 100644 --- a/bin/configs/cpp-qt5-client.yaml +++ b/bin/configs/cpp-qt-client.yaml @@ -1,7 +1,7 @@ -generatorName: cpp-qt5-client -outputDir: samples/client/petstore/cpp-qt5 +generatorName: cpp-qt-client +outputDir: samples/client/petstore/cpp-qt inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml -templateDir: modules/openapi-generator/src/main/resources/cpp-qt5-client +templateDir: modules/openapi-generator/src/main/resources/cpp-qt-client additionalProperties: cppNamespace: test_namespace modelNamePrefix: PFX diff --git a/bin/configs/cpp-qt5-qhttpengine-server.yaml b/bin/configs/cpp-qt-qhttpengine-server.yaml similarity index 52% rename from bin/configs/cpp-qt5-qhttpengine-server.yaml rename to bin/configs/cpp-qt-qhttpengine-server.yaml index 8ead0fe398de..9a03bcbc9511 100644 --- a/bin/configs/cpp-qt5-qhttpengine-server.yaml +++ b/bin/configs/cpp-qt-qhttpengine-server.yaml @@ -1,4 +1,4 @@ -generatorName: cpp-qt5-qhttpengine-server -outputDir: samples/server/petstore/cpp-qt5-qhttpengine-server +generatorName: cpp-qt-qhttpengine-server +outputDir: samples/server/petstore/cpp-qt-qhttpengine-server inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml -templateDir: modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server +templateDir: modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server diff --git a/bin/configs/cpp-tiny.yaml b/bin/configs/cpp-tiny.yaml new file mode 100644 index 000000000000..237ae1403f46 --- /dev/null +++ b/bin/configs/cpp-tiny.yaml @@ -0,0 +1,7 @@ +generatorName: cpp-tiny +outputDir: samples/client/petstore/cpp-tiny +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/cpp-tiny +additionalProperties: + hideGenerationTimestamp: "true" + controller: "esp32" diff --git a/bin/configs/go-echo-server-petstore-new.yaml b/bin/configs/go-echo-server-petstore-new.yaml new file mode 100644 index 000000000000..bfc2e946c586 --- /dev/null +++ b/bin/configs/go-echo-server-petstore-new.yaml @@ -0,0 +1,6 @@ +generatorName: go-echo-server +outputDir: samples/server/petstore/go-echo-server +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/go-echo-server +additionalProperties: + hideGenerationTimestamp: "true" diff --git a/bin/configs/kotlin-json-request-string.yaml b/bin/configs/kotlin-json-request-string.yaml index 8f1dade28c90..bbe5ddd4283b 100644 --- a/bin/configs/kotlin-json-request-string.yaml +++ b/bin/configs/kotlin-json-request-string.yaml @@ -5,3 +5,5 @@ templateDir: modules/openapi-generator/src/main/resources/kotlin-client additionalProperties: requestDateConverter: toString artifactId: kotlin-petstore-json-request-string + parcelizeModels: true + supportAndroidApiLevel25AndBelow: true diff --git a/bin/configs/ktorm-schema.yaml b/bin/configs/ktorm-schema.yaml index aff895cb279b..d3c5beb9a33b 100644 --- a/bin/configs/ktorm-schema.yaml +++ b/bin/configs/ktorm-schema.yaml @@ -1,7 +1,7 @@ generatorName: ktorm-schema outputDir: samples/schema/petstore/ktorm -inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/ktorm-schema additionalProperties: hideGenerationTimestamp: true - importModelPackageName: org.openapitools.client.models \ No newline at end of file + importModelPackageName: org.openapitools.client.models diff --git a/bin/configs/nim.yaml b/bin/configs/nim.yaml index 136a92764c3c..13a27a6b764c 100644 --- a/bin/configs/nim.yaml +++ b/bin/configs/nim.yaml @@ -1,6 +1,6 @@ generatorName: nim outputDir: samples/client/petstore/nim -inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/nim-client additionalProperties: packageName: petstore diff --git a/bin/configs/php-mezzio-ph-modern.yaml b/bin/configs/php-mezzio-ph-modern.yaml new file mode 100644 index 000000000000..accaa2dfe30d --- /dev/null +++ b/bin/configs/php-mezzio-ph-modern.yaml @@ -0,0 +1,6 @@ +generatorName: php-mezzio-ph +outputDir: samples/server/petstore/php-mezzio-ph-modern +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/php-mezzio-ph-modern +additionalProperties: + modern: "true" diff --git a/bin/configs/php-symfony-SymfonyBundle-php.yaml b/bin/configs/php-symfony-SymfonyBundle-php.yaml index c77a71f14b7d..f7c6218a50fe 100644 --- a/bin/configs/php-symfony-SymfonyBundle-php.yaml +++ b/bin/configs/php-symfony-SymfonyBundle-php.yaml @@ -1,4 +1,4 @@ generatorName: php-symfony outputDir: samples/server/petstore/php-symfony/SymfonyBundle-php -inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/php-symfony diff --git a/bin/configs/python-fastapi.yaml b/bin/configs/python-fastapi.yaml new file mode 100644 index 000000000000..7bf7405c527e --- /dev/null +++ b/bin/configs/python-fastapi.yaml @@ -0,0 +1,6 @@ +generatorName: python-fastapi +outputDir: samples/server/petstore/python-fastapi +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/python-fastapi +additionalProperties: + hideGenerationTimestamp: "true" diff --git a/bin/configs/python-oas2.yaml b/bin/configs/python-oas2.yaml index 4555376bd167..7c548fb39269 100644 --- a/bin/configs/python-oas2.yaml +++ b/bin/configs/python-oas2.yaml @@ -1,7 +1,10 @@ +# this file exists because in this file we omit setting disallowAdditionalPropertiesIfNotPresent +# which makes it default to false +# that false setting is needed for composed schemas to work +# Composed schemas are schemas that contain the allOf/oneOf/anyOf keywords. v2 specs only support the allOf keyword. generatorName: python outputDir: samples/client/petstore/python inputSpec: modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml templateDir: modules/openapi-generator/src/main/resources/python additionalProperties: - disallowAdditionalPropertiesIfNotPresent: "true" packageName: petstore_api diff --git a/bin/configs/python-oas2_disallowAdditionalPropertiesIfNotPresent.yaml b/bin/configs/python-oas2_disallowAdditionalPropertiesIfNotPresent.yaml new file mode 100644 index 000000000000..841cf77854eb --- /dev/null +++ b/bin/configs/python-oas2_disallowAdditionalPropertiesIfNotPresent.yaml @@ -0,0 +1,7 @@ +generatorName: python +outputDir: samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent +inputSpec: modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml +templateDir: modules/openapi-generator/src/main/resources/python +additionalProperties: + disallowAdditionalPropertiesIfNotPresent: "true" + packageName: petstore_api diff --git a/bin/configs/swift5-default.yaml b/bin/configs/swift5-default.yaml index ede36e7331cf..fffd318be1ad 100644 --- a/bin/configs/swift5-default.yaml +++ b/bin/configs/swift5-default.yaml @@ -1,6 +1,6 @@ generatorName: swift5 outputDir: samples/client/petstore/swift5/default -inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml +inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml templateDir: modules/openapi-generator/src/main/resources/swift5 generateAliasAsModel: true additionalProperties: diff --git a/bin/configs/swift5-oneOf.yaml b/bin/configs/swift5-oneOf.yaml new file mode 100644 index 000000000000..975892b340ce --- /dev/null +++ b/bin/configs/swift5-oneOf.yaml @@ -0,0 +1,10 @@ +generatorName: swift5 +outputDir: samples/client/petstore/swift5/oneOf +inputSpec: modules/openapi-generator/src/test/resources/3_0/oneOf.yaml +templateDir: modules/openapi-generator/src/main/resources/swift5 +generateAliasAsModel: true +additionalProperties: + podAuthors: "" + podSummary: PetstoreClient + projectName: PetstoreClient + podHomepage: https://github.com/openapitools/openapi-generator diff --git a/bin/configs/swift5-rxswiftLibrary.yaml b/bin/configs/swift5-rxswiftLibrary.yaml index f564ac3340cf..8751d3479121 100644 --- a/bin/configs/swift5-rxswiftLibrary.yaml +++ b/bin/configs/swift5-rxswiftLibrary.yaml @@ -9,3 +9,5 @@ additionalProperties: podSummary: PetstoreClient projectName: PetstoreClient podHomepage: https://github.com/openapitools/openapi-generator + useBacktickEscapes: true + generateModelAdditionalProperties: false diff --git a/bin/configs/swift5-urlsessionLibrary.yaml b/bin/configs/swift5-urlsessionLibrary.yaml index 2fe5ecca0c7b..1520a7c1ea98 100644 --- a/bin/configs/swift5-urlsessionLibrary.yaml +++ b/bin/configs/swift5-urlsessionLibrary.yaml @@ -9,3 +9,6 @@ additionalProperties: podSummary: PetstoreClient projectName: PetstoreClient podHomepage: https://github.com/openapitools/openapi-generator + useSPMFileStructure: true + useClasses: true + swiftUseApiNamespace: true diff --git a/bin/configs/swift5-x-swift-hashable.yaml b/bin/configs/swift5-x-swift-hashable.yaml new file mode 100644 index 000000000000..c07937d53366 --- /dev/null +++ b/bin/configs/swift5-x-swift-hashable.yaml @@ -0,0 +1,11 @@ +generatorName: swift5 +outputDir: samples/client/petstore/swift5/x-swift-hashable +inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml +templateDir: modules/openapi-generator/src/main/resources/swift5 +generateAliasAsModel: true +additionalProperties: + podAuthors: "" + podSummary: PetstoreClient + projectName: PetstoreClient + podHomepage: https://github.com/openapitools/openapi-generator + hashableModels: false diff --git a/bin/configs/wsdl-schema.yaml b/bin/configs/wsdl-schema.yaml new file mode 100644 index 000000000000..29484b39dfe4 --- /dev/null +++ b/bin/configs/wsdl-schema.yaml @@ -0,0 +1,6 @@ +generatorName: wsdl-schema +outputDir: samples/schema/petstore/wsdl-schema +inputSpec: modules/openapi-generator/src/test/resources/3_0/wsdl/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/wsdl-schema +additionalProperties: + hideGenerationTimestamp: "true" diff --git a/bin/meta-codegen.sh b/bin/meta-codegen.sh index d2a05a0fe6a7..5b90f6abc8cb 100755 --- a/bin/meta-codegen.sh +++ b/bin/meta-codegen.sh @@ -1,5 +1,7 @@ #!/usr/bin/env bash +set -e + SCRIPT="$0" echo "# START SCRIPT: $SCRIPT" @@ -18,8 +20,8 @@ ags="meta -n myClientCodegen -t DOCUMENTATION -p com.my.company.codegen -o sampl java $JAVA_OPTS -jar $executable $ags -(cd "$root"/samples/meta-codegen/ && mvn -B package -Djacoco.skip=true -DskipTests=true -f pom.xml) +(./mvnw -B package -Djacoco.skip=true -DskipTests=true -f "$root"/samples/meta-codegen/pom.xml) -ags2="generate -g myClientCodegen -i modules/openapi-generator/src/test/resources/2_0/petstore.json -o samples/meta-codegen/usage $@" +ags2="generate -g myClientCodegen -i modules/openapi-generator/src/test/resources/3_0/petstore.json -o samples/meta-codegen/usage $@" -java $JAVA_OPTS -cp ${root}/samples/meta-codegen/lib/target/myClientCodegen-openapi-generator-1.0.0.jar:$executable org.openapitools.codegen.OpenAPIGenerator $ags2 \ No newline at end of file +java $JAVA_OPTS -cp ${root}/samples/meta-codegen/lib/target/myClientCodegen-openapi-generator-1.0.0.jar:$executable org.openapitools.codegen.OpenAPIGenerator $ags2 diff --git a/bin/utils/test-fake-petstore-for-all.sh b/bin/utils/test-fake-petstore-for-all.sh index 6be320d6b999..1ec62890c3bb 100755 --- a/bin/utils/test-fake-petstore-for-all.sh +++ b/bin/utils/test-fake-petstore-for-all.sh @@ -11,15 +11,16 @@ logfile="/tmp/generator-fake-petstore-output.log" for GENERATOR in $(java -jar ${executable} list --short | sed -e 's/,/\'$'\n''/g') do - if eval java -jar ${executable} generate -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g ${GENERATOR} -o /tmp/openapi-generator-test-fake-petstore/2.0/${GENERATOR} > ${logfile} 2>&1; then - echo "[OAS 2.0] Executed ${GENERATOR} successfully!" - else - echo "ERROR: Failed to run '${GENERATOR}' generator. The command was:" - echo "java -jar ${executable} generate -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g ${GENERATOR} -o /tmp/openapi-generator-test-fake-petstore/2.0/${GENERATOR}" - echo "ERROR: The output of the command was:" - cat ${logfile} - exit 1 - fi + # no longer test 2.0 spec as we migrated to 3.0 spec + #if eval java -jar ${executable} generate -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g ${GENERATOR} -o /tmp/openapi-generator-test-fake-petstore/2.0/${GENERATOR} > ${logfile} 2>&1; then + # echo "[OAS 2.0] Executed ${GENERATOR} successfully!" + #else + # echo "ERROR: Failed to run '${GENERATOR}' generator. The command was:" + # echo "java -jar ${executable} generate -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g ${GENERATOR} -o /tmp/openapi-generator-test-fake-petstore/2.0/${GENERATOR}" + # echo "ERROR: The output of the command was:" + # cat ${logfile} + # exit 1 + #fi if eval java -jar ${executable} generate -i modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml -g ${GENERATOR} -o /tmp/openapi-generator-test-fake-petstore/3.0/${GENERATOR} > ${logfile} 2>&1; then echo "[OAS 3.0] Executed ${GENERATOR} successfully!" diff --git a/docs/contributing.md b/docs/contributing.md index a791b0d6f1ba..fe325ae17e16 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -52,6 +52,7 @@ Code change should conform to the programming style guide of the respective lang - C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx - C++: https://google.github.io/styleguide/cppguide.html - C++ (Tizen): https://wiki.tizen.org/Native_Platform_Coding_Idiom_and_Style_Guide#C.2B.2B_Coding_Style +- C++ (Unreal Engine 4): https://docs.unrealengine.com/en-US/ProductionPipelines/DevelopmentSetup/CodingStandard/index.html - Clojure: https://github.com/bbatsov/clojure-style-guide - Crystal: https://crystal-lang.org/reference/conventions/coding_style.html - Dart: https://www.dartlang.org/guides/language/effective-dart/style diff --git a/docs/generators.md b/docs/generators.md index e581cc54fb1a..2531acc9e670 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -12,8 +12,9 @@ The following generators are available: * [bash](generators/bash.md) * [c](generators/c.md) * [clojure](generators/clojure.md) -* [cpp-qt5-client](generators/cpp-qt5-client.md) +* [cpp-qt-client](generators/cpp-qt-client.md) * [cpp-restsdk](generators/cpp-restsdk.md) +* [cpp-tiny (beta)](generators/cpp-tiny.md) * [cpp-tizen](generators/cpp-tizen.md) * [cpp-ue4 (beta)](generators/cpp-ue4.md) * [crystal (beta)](generators/crystal.md) @@ -80,12 +81,13 @@ The following generators are available: * [ada-server](generators/ada-server.md) * [aspnetcore](generators/aspnetcore.md) * [cpp-pistache-server](generators/cpp-pistache-server.md) -* [cpp-qt5-qhttpengine-server](generators/cpp-qt5-qhttpengine-server.md) +* [cpp-qt-qhttpengine-server](generators/cpp-qt-qhttpengine-server.md) * [cpp-restbed-server](generators/cpp-restbed-server.md) * [csharp-nancyfx](generators/csharp-nancyfx.md) * [erlang-server](generators/erlang-server.md) * [fsharp-functions (beta)](generators/fsharp-functions.md) * [fsharp-giraffe-server (beta)](generators/fsharp-giraffe-server.md) +* [go-echo-server (beta)](generators/go-echo-server.md) * [go-gin-server](generators/go-gin-server.md) * [go-server](generators/go-server.md) * [graphql-nodejs-express-server](generators/graphql-nodejs-express-server.md) @@ -105,6 +107,7 @@ The following generators are available: * [jaxrs-resteasy-eap](generators/jaxrs-resteasy-eap.md) * [jaxrs-spec](generators/jaxrs-spec.md) * [kotlin-server](generators/kotlin-server.md) +* [kotlin-server-deprecated (deprecated)](generators/kotlin-server-deprecated.md) * [kotlin-spring](generators/kotlin-spring.md) * [kotlin-vertx (beta)](generators/kotlin-vertx.md) * [nodejs-express-server (beta)](generators/nodejs-express-server.md) @@ -117,6 +120,7 @@ The following generators are available: * [php-symfony](generators/php-symfony.md) * [python-aiohttp](generators/python-aiohttp.md) * [python-blueplanet](generators/python-blueplanet.md) +* [python-fastapi (beta)](generators/python-fastapi.md) * [python-flask](generators/python-flask.md) * [ruby-on-rails](generators/ruby-on-rails.md) * [ruby-sinatra](generators/ruby-sinatra.md) @@ -147,6 +151,7 @@ The following generators are available: * [ktorm-schema (beta)](generators/ktorm-schema.md) * [mysql-schema](generators/mysql-schema.md) * [protobuf-schema (beta)](generators/protobuf-schema.md) +* [wsdl-schema (beta)](generators/wsdl-schema.md) ## CONFIG generators diff --git a/docs/generators/README.md b/docs/generators/README.md index 6510770e47a9..a8ac9c9310c3 100644 --- a/docs/generators/README.md +++ b/docs/generators/README.md @@ -91,6 +91,7 @@ The following generators are available: * [jaxrs-resteasy-eap](jaxrs-resteasy-eap.md) * [jaxrs-spec](jaxrs-spec.md) * [kotlin-server](kotlin-server.md) +* [kotlin-server-deprecated](kotlin-server-deprecated.md) * [kotlin-spring](kotlin-spring.md) * [kotlin-vertx (beta)](kotlin-vertx.md) * [nodejs-express-server (beta)](nodejs-express-server.md) diff --git a/docs/generators/aspnetcore.md b/docs/generators/aspnetcore.md index 0a30830099f5..14d54f778d4c 100644 --- a/docs/generators/aspnetcore.md +++ b/docs/generators/aspnetcore.md @@ -7,8 +7,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | -|aspnetCoreVersion|ASP.NET Core version: 5.0, 3.1, 3.0, 2.2, 2.1, 2.0 (deprecated)| |3.1| -|buildTarget|Target to build an application or library| |program| +|aspnetCoreVersion|ASP.NET Core version: 5.0, 3.1, 3.0, 2.2, 2.1, 2.0 (deprecated)|
**2.0**
ASP.NET Core 2.0
**2.1**
ASP.NET Core 2.1
**2.2**
ASP.NET Core 2.2
**3.0**
ASP.NET Core 3.0
**3.1**
ASP.NET Core 3.1
**5.0**
ASP.NET Core 5.0
|3.1| +|buildTarget|Target to build an application or library|
**program**
Generate code for a standalone server
**library**
Generate code for a server abstract class library
|program| |classModifier|Class Modifier for controller classes: Empty string or abstract.| || |compatibilityVersion|ASP.Net Core CompatibilityVersion| |Version_2_2| |enumNameSuffix|Suffix that will be appended to all enum names.| |Enum| @@ -19,8 +19,9 @@ These options may be applied as additional-properties (cli) or configOptions (pl |licenseUrl|The URL of the license| |http://localhost| |modelClassModifier|Model Class Modifier can be nothing or partial| |partial| |newtonsoftVersion|Version for Microsoft.AspNetCore.Mvc.NewtonsoftJson for ASP.NET Core 3.0+| |3.0.0| +|nullableReferenceTypes|Annotate Project with <Nullable>annotations</Nullable> and use ? annotation on all nullable attributes. Only supported on C# 8 / ASP.NET Core 3.0 or newer.| |false| |operationIsAsync|Set methods to async or sync (default).| |false| -|operationModifier|Operation Modifier can be virtual or abstract| |virtual| +|operationModifier|Operation Modifier can be virtual or abstract|
**virtual**
Keep method virtual
**abstract**
Make method abstract
|virtual| |operationResultTask|Set methods result to Task<>.| |false| |packageAuthors|Specifies Authors property in the .NET Core project file.| |OpenAPI| |packageCopyright|Specifies an AssemblyCopyright for the .NET Framework global assembly attributes stored in the AssemblyInfo file.| |No Copyright| @@ -32,7 +33,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |returnICollection|Return ICollection<T> instead of the concrete type.| |false| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|source folder for generated code| |src| -|swashbuckleVersion|Swashbuckle version: 3.0.0, 4.0.0, 5.0.0| |3.0.0| +|swashbuckleVersion|Swashbuckle version: 3.0.0, 4.0.0, 5.0.0|
**3.0.0**
Swashbuckle 3.0.0
**4.0.0**
Swashbuckle 4.0.0
**5.0.0**
Swashbuckle 5.0.0
|3.0.0| |useCollection|Deserialize array types to Collection<T> instead of List<T>.| |false| |useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false| |useDefaultRouting|Use default routing for the ASP.NET Core version.| |true| diff --git a/docs/generators/cpp-qt5-client.md b/docs/generators/cpp-qt-client.md similarity index 99% rename from docs/generators/cpp-qt5-client.md rename to docs/generators/cpp-qt-client.md index ce9e00428f88..0dcbd968233d 100644 --- a/docs/generators/cpp-qt5-client.md +++ b/docs/generators/cpp-qt-client.md @@ -1,6 +1,6 @@ --- -title: Config Options for cpp-qt5-client -sidebar_label: cpp-qt5-client +title: Config Options for cpp-qt-client +sidebar_label: cpp-qt-client --- These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. diff --git a/docs/generators/cpp-qt5-qhttpengine-server.md b/docs/generators/cpp-qt-qhttpengine-server.md similarity index 98% rename from docs/generators/cpp-qt5-qhttpengine-server.md rename to docs/generators/cpp-qt-qhttpengine-server.md index 3467f16775b9..efd57d28d7ad 100644 --- a/docs/generators/cpp-qt5-qhttpengine-server.md +++ b/docs/generators/cpp-qt-qhttpengine-server.md @@ -1,6 +1,6 @@ --- -title: Config Options for cpp-qt5-qhttpengine-server -sidebar_label: cpp-qt5-qhttpengine-server +title: Config Options for cpp-qt-qhttpengine-server +sidebar_label: cpp-qt-qhttpengine-server --- These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. diff --git a/docs/generators/cpp-tiny.md b/docs/generators/cpp-tiny.md new file mode 100644 index 000000000000..1c90b5cbe8e0 --- /dev/null +++ b/docs/generators/cpp-tiny.md @@ -0,0 +1,243 @@ +--- +title: Config Options for cpp-tiny +sidebar_label: cpp-tiny +--- + +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|controller|name of microcontroller (e.g esp32 or esp8266)| |esp32| +|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true| +|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| +|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|reservedWordPrefix|Prefix to prepend to reserved words in order to avoid conflicts| |r_| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|variableNameFirstCharacterUppercase|Make first character of variable name uppercase (eg. value -> Value)| |true| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | + + +## LANGUAGE PRIMITIVES + + + +## RESERVED WORDS + + + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✗|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Array|✓|OAS2,OAS3 +|Maps|✗|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✗|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✗|ToolingExtension +|MapOfModel|✗|ToolingExtension +|MapOfCollectionOfPrimitives|✗|ToolingExtension +|MapOfCollectionOfModel|✗|ToolingExtension +|MapOfCollectionOfEnum|✗|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✗|OAS2,OAS3 +|Header|✗|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✗|OAS2 +|FormMultipart|✗|OAS2 +|Cookie|✗|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 +|Union|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✓|OAS2,OAS3 +|ApiKey|✓|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✓|OAS3 +|OAuth2_Implicit|✓|OAS2,OAS3 +|OAuth2_Password|✓|OAS2,OAS3 +|OAuth2_ClientCredentials|✓|OAS2,OAS3 +|OAuth2_AuthorizationCode|✓|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✗|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/csharp-netcore.md b/docs/generators/csharp-netcore.md index c7935752d018..0887dcbfeca0 100644 --- a/docs/generators/csharp-netcore.md +++ b/docs/generators/csharp-netcore.md @@ -29,7 +29,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |returnICollection|Return ICollection<T> instead of the concrete type.| |false| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|source folder for generated code| |src| -|targetFramework|The target .NET framework version.|
**netstandard1.3**
.NET Standard 1.3 compatible
**netstandard1.4**
.NET Standard 1.4 compatible
**netstandard1.5**
.NET Standard 1.5 compatible
**netstandard1.6**
.NET Standard 1.6 compatible
**netstandard2.0**
.NET Standard 2.0 compatible
**netstandard2.1**
.NET Standard 2.1 compatible
**netcoreapp2.0**
.NET Core 2.0 compatible
**netcoreapp2.1**
.NET Core 2.1 compatible
**netcoreapp3.0**
.NET Core 3.0 compatible
**netcoreapp3.1**
.NET Core 3.1 compatible
**net47**
.NET Framework 4.7 compatible
**net5.0**
.NET 5.0 compatible
|netstandard2.0| +|targetFramework|The target .NET framework version. To target multiple frameworks, use `;` as the separator, e.g. `netstandard2.1;netcoreapp3.0`|
**netstandard1.3**
.NET Standard 1.3 compatible
**netstandard1.4**
.NET Standard 1.4 compatible
**netstandard1.5**
.NET Standard 1.5 compatible
**netstandard1.6**
.NET Standard 1.6 compatible
**netstandard2.0**
.NET Standard 2.0 compatible
**netstandard2.1**
.NET Standard 2.1 compatible
**netcoreapp2.0**
.NET Core 2.0 compatible
**netcoreapp2.1**
.NET Core 2.1 compatible
**netcoreapp3.0**
.NET Core 3.0 compatible
**netcoreapp3.1**
.NET Core 3.1 compatible
**net47**
.NET Framework 4.7 compatible
**net5.0**
.NET 5.0 compatible
|netstandard2.0| |useCollection|Deserialize array types to Collection<T> instead of List<T>.| |false| |useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false| |useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.| |false| diff --git a/docs/generators/csharp.md b/docs/generators/csharp.md index ec9c4454ff8e..0b3185606ec1 100644 --- a/docs/generators/csharp.md +++ b/docs/generators/csharp.md @@ -25,7 +25,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |returnICollection|Return ICollection<T> instead of the concrete type.| |false| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|source folder for generated code| |src| -|targetFramework|The target .NET framework version.|
**v3.5**
.NET Framework 3.5 compatible
**v4.0**
.NET Framework 4.0 compatible
**v4.5**
.NET Framework 4.5 compatible
**v4.5.2**
.NET Framework 4.5.2+ compatible
**netstandard1.3**
.NET Standard 1.3 compatible (DEPRECATED. Please use `csharp-netcore` generator instead)
**uwp**
Universal Windows Platform (DEPRECATED. Please use `csharp-netcore` generator instead)
|v4.5| +|targetFramework|The target .NET framework version. To target multiple frameworks, use `;` as the separator, e.g. `netstandard2.1;netcoreapp3.0`|
**v3.5**
.NET Framework 3.5 compatible
**v4.0**
.NET Framework 4.0 compatible
**v4.5**
.NET Framework 4.5 compatible
**v4.5.2**
.NET Framework 4.5.2+ compatible
**netstandard1.3**
.NET Standard 1.3 compatible (DEPRECATED. Please use `csharp-netcore` generator instead)
**uwp**
Universal Windows Platform (DEPRECATED. Please use `csharp-netcore` generator instead)
|v4.5| |useCollection|Deserialize array types to Collection<T> instead of List<T>.| |false| |useCompareNetObjects|Use KellermanSoftware.CompareNetObjects for deep recursive object comparison. WARNING: this option incurs potential performance impact.| |false| |useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false| diff --git a/docs/generators/go-echo-server.md b/docs/generators/go-echo-server.md new file mode 100644 index 000000000000..53c726fb85e8 --- /dev/null +++ b/docs/generators/go-echo-server.md @@ -0,0 +1,206 @@ +--- +title: Config Options for go-echo-server +sidebar_label: go-echo-server +--- + +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| +|packageName|Go package name (convention: lowercase).| |openapi| +|packageVersion|Go package version.| |1.0.0| +|serverPort|The network port the generated server binds to| |8080| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | + + +## LANGUAGE PRIMITIVES + + + +## RESERVED WORDS + + + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✗|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Array|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✗|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 +|Union|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✗|OAS2,OAS3 +|ApiKey|✗|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✗|OAS3 +|OAuth2_Implicit|✗|OAS2,OAS3 +|OAuth2_Password|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_AuthorizationCode|✗|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/kotlin-server-deprecated.md b/docs/generators/kotlin-server-deprecated.md new file mode 100644 index 000000000000..5499354747c5 --- /dev/null +++ b/docs/generators/kotlin-server-deprecated.md @@ -0,0 +1,214 @@ +--- +title: Config Options for kotlin-server-deprecated +sidebar_label: kotlin-server-deprecated +--- + +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|apiSuffix|suffix for api classes| |Api| +|artifactId|Generated artifact id (name of jar).| |kotlin-server-deprecated| +|artifactVersion|Generated artifact's package version.| |1.0.0| +|enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |camelCase| +|featureAutoHead|Automatically provide responses to HEAD requests for existing routes that have the GET verb defined.| |true| +|featureCORS|Ktor by default provides an interceptor for implementing proper support for Cross-Origin Resource Sharing (CORS). See enable-cors.org.| |false| +|featureCompression|Adds ability to compress outgoing content using gzip, deflate or custom encoder and thus reduce size of the response.| |true| +|featureConditionalHeaders|Avoid sending content if client already has same content, by checking ETag or LastModified properties.| |false| +|featureHSTS|Avoid sending content if client already has same content, by checking ETag or LastModified properties.| |true| +|groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapitools| +|library|library template (sub-template)|
**ktor**
ktor framework
|ktor| +|modelMutable|Create mutable models| |false| +|packageName|Generated artifact package name.| |org.openapitools.server| +|parcelizeModels|toggle "@Parcelize" for generated models| |null| +|serializableModel|boolean - toggle "implements Serializable" for generated models| |null| +|serializationLibrary|What serialization library to use: 'moshi' (default), or 'gson' or 'jackson'| |moshi| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |null| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |null| +|sourceFolder|source folder for generated code| |src/main/kotlin| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | +|BigDecimal|java.math.BigDecimal| +|Date|java.time.LocalDate| +|DateTime|java.time.OffsetDateTime| +|File|java.io.File| +|LocalDate|java.time.LocalDate| +|LocalDateTime|java.time.LocalDateTime| +|LocalTime|java.time.LocalTime| +|Timestamp|java.sql.Timestamp| +|URI|java.net.URI| +|UUID|java.util.UUID| + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | +|array|kotlin.collections.ArrayList| +|list|kotlin.collections.ArrayList| +|map|kotlin.collections.HashMap| + + +## LANGUAGE PRIMITIVES + + + +## RESERVED WORDS + + + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✗|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Array|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✗|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 +|Union|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✓|OAS2,OAS3 +|ApiKey|✓|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✗|OAS3 +|OAuth2_Implicit|✓|OAS2,OAS3 +|OAuth2_Password|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_AuthorizationCode|✗|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/kotlin-server.md b/docs/generators/kotlin-server.md index ecaf99a294f2..b45dc3ffb4d2 100644 --- a/docs/generators/kotlin-server.md +++ b/docs/generators/kotlin-server.md @@ -16,6 +16,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |featureCompression|Adds ability to compress outgoing content using gzip, deflate or custom encoder and thus reduce size of the response.| |true| |featureConditionalHeaders|Avoid sending content if client already has same content, by checking ETag or LastModified properties.| |false| |featureHSTS|Avoid sending content if client already has same content, by checking ETag or LastModified properties.| |true| +|featureLocations|Generates routes in a typed way, for both: constructing URLs and reading the parameters.| |true| |groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapitools| |library|library template (sub-template)|
**ktor**
ktor framework
|ktor| |modelMutable|Create mutable models| |false| diff --git a/docs/generators/kotlin.md b/docs/generators/kotlin.md index ef76c9af691b..6432fc5be67a 100644 --- a/docs/generators/kotlin.md +++ b/docs/generators/kotlin.md @@ -16,6 +16,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapitools| |library|Library template (sub-template) to use|
**jvm-okhttp4**
[DEFAULT] Platform: Java Virtual Machine. HTTP client: OkHttp 4.2.0 (Android 5.0+ and Java 8+). JSON processing: Moshi 1.8.0.
**jvm-okhttp3**
Platform: Java Virtual Machine. HTTP client: OkHttp 3.12.4 (Android 2.3+ and Java 7+). JSON processing: Moshi 1.8.0.
**jvm-retrofit2**
Platform: Java Virtual Machine. HTTP client: Retrofit 2.6.2.
**multiplatform**
Platform: Kotlin multiplatform. HTTP client: Ktor 1.2.4. JSON processing: Kotlinx Serialization: 0.12.0.
|jvm-okhttp4| |modelMutable|Create mutable models| |false| +|moshiCodeGen|Whether to enable codegen with the Moshi library. Refer to the [official Moshi doc](https://github.com/square/moshi#codegen) for more info.| |false| |packageName|Generated artifact package name.| |org.openapitools.client| |parcelizeModels|toggle "@Parcelize" for generated models| |null| |requestDateConverter|JVM-Option. Defines in how to handle date-time objects that are used for a request (as query or parameter)|
**toJson**
[DEFAULT] Date formater option using a json converter.
**toString**
Use the 'toString'-method of the date-time object to retrieve the related string representation.
|toJson| @@ -24,6 +25,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |null| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |null| |sourceFolder|source folder for generated code| |src/main/kotlin| +|supportAndroidApiLevel25AndBelow|[WARNING] This flag will generate code that has a known security vulnerability. It uses `kotlin.io.createTempFile` instead of `java.nio.file.Files.createTempFile` in oder to support Android API level 25 and bellow. For more info, please check the following links https://github.com/OpenAPITools/openapi-generator/security/advisories/GHSA-23x4-m842-fmwf, https://github.com/OpenAPITools/openapi-generator/pull/9284| |false| |useCoroutines|Whether to use the Coroutines adapter with the retrofit2 library.| |false| |useRxJava|Whether to use the RxJava adapter with the retrofit2 library.| |false| |useRxJava2|Whether to use the RxJava2 adapter with the retrofit2 library.| |false| diff --git a/docs/generators/php-mezzio-ph.md b/docs/generators/php-mezzio-ph.md index f691e8f57fb2..93f31d7fbca2 100644 --- a/docs/generators/php-mezzio-ph.md +++ b/docs/generators/php-mezzio-ph.md @@ -15,6 +15,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |invokerPackage|The main namespace to use for all classes. e.g. Yay\Pets| |null| |legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |modelPackage|package for generated models| |null| +|modern|use modern language features (generated code will require PHP 8.0)| |false| |packageName|The main package name for classes. e.g. GeneratedPetstore| |null| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/python-aiohttp.md b/docs/generators/python-aiohttp.md index 7c46da0b5b44..9adef96ba51f 100644 --- a/docs/generators/python-aiohttp.md +++ b/docs/generators/python-aiohttp.md @@ -23,6 +23,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |supportPython2|support python2. This option has been deprecated and will be removed in the 5.x release.| |false| |useNose|use the nose test framework| |false| +|usePythonSrcRootInImports|include pythonSrcRoot in import namespaces.| |false| ## IMPORT MAPPING diff --git a/docs/generators/python-blueplanet.md b/docs/generators/python-blueplanet.md index 81c9b89cbf3d..ba461d1822fe 100644 --- a/docs/generators/python-blueplanet.md +++ b/docs/generators/python-blueplanet.md @@ -23,6 +23,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |supportPython2|support python2. This option has been deprecated and will be removed in the 5.x release.| |false| |useNose|use the nose test framework| |false| +|usePythonSrcRootInImports|include pythonSrcRoot in import namespaces.| |false| ## IMPORT MAPPING diff --git a/docs/generators/python-fastapi.md b/docs/generators/python-fastapi.md new file mode 100644 index 000000000000..2143321f2d7d --- /dev/null +++ b/docs/generators/python-fastapi.md @@ -0,0 +1,211 @@ +--- +title: Config Options for python-fastapi +sidebar_label: python-fastapi +--- + +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true| +|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| +|packageName|python package name (convention: snake_case).| |openapi_server| +|packageVersion|python package version.| |1.0.0| +|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|serverPort|TCP port to listen to in app.run| |8080| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | + + +## LANGUAGE PRIMITIVES + + + +## RESERVED WORDS + + + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✗|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Array|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✗|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✓|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✓|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✓|OAS2,OAS3 +|Union|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✓|OAS2,OAS3 +|ApiKey|✓|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✓|OAS3 +|OAuth2_Implicit|✓|OAS2,OAS3 +|OAuth2_Password|✓|OAS2,OAS3 +|OAuth2_ClientCredentials|✓|OAS2,OAS3 +|OAuth2_AuthorizationCode|✓|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/python-flask.md b/docs/generators/python-flask.md index 92bf4fdb97fa..9e69fa443023 100644 --- a/docs/generators/python-flask.md +++ b/docs/generators/python-flask.md @@ -23,6 +23,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |supportPython2|support python2. This option has been deprecated and will be removed in the 5.x release.| |false| |useNose|use the nose test framework| |false| +|usePythonSrcRootInImports|include pythonSrcRoot in import namespaces.| |false| ## IMPORT MAPPING diff --git a/docs/generators/python.md b/docs/generators/python.md index 4cf503ff2786..fe60f0e511c7 100644 --- a/docs/generators/python.md +++ b/docs/generators/python.md @@ -7,6 +7,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | +|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default. NOTE: this option breaks composition and will be removed in 6.0.0
|false| |generateSourceCodeOnly|Specifies that only a library source code is to be generated.| |false| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| |library|library template (sub-template) to use: asyncio, tornado, urllib3| |urllib3| @@ -28,7 +29,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl | Type/Alias | Instantiated By | | ---------- | --------------- | -|map|dict| ## LANGUAGE PRIMITIVES diff --git a/docs/generators/scala-sttp.md b/docs/generators/scala-sttp.md index 5f0c9f7e6adc..77891a59141a 100644 --- a/docs/generators/scala-sttp.md +++ b/docs/generators/scala-sttp.md @@ -13,8 +13,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl |dateLibrary|Option. Date library to use|
**joda**
Joda (for legacy app)
**java8**
Java 8 native JSR310 (prefered for JDK 1.8+)
|java8| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| -|jodaTimeVersion|The version of joda-time library| |2.10.6| -|json4sVersion|The version of json4s library| |3.6.8| +|jodaTimeVersion|The version of joda-time library| |2.10.10| +|json4sVersion|The version of json4s library| |3.6.11| |jsonLibrary|Json library to use. Possible values are: json4s and circe.| |json4s| |legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |mainPackage|Top-level package name, which defines 'apiPackage', 'modelPackage', 'invokerPackage'| |org.openapitools.client| @@ -25,7 +25,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|source folder for generated code| |null| -|sttpClientVersion|The version of sttp client| |2.2.0| +|sttpClientVersion|The version of sttp client| |2.2.9| ## IMPORT MAPPING diff --git a/docs/generators/swift5.md b/docs/generators/swift5.md index ebf6f2b0e86a..51dc7529358f 100644 --- a/docs/generators/swift5.md +++ b/docs/generators/swift5.md @@ -11,10 +11,13 @@ These options may be applied as additional-properties (cli) or configOptions (pl |apiNamePrefix|Prefix that will be appended to all API names ('tags'). Default: empty string. e.g. Pet => Pet.| |null| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|generateModelAdditionalProperties|Generate model additional properties (default: true)| |true| +|hashableModels|Make hashable models (default: true)| |true| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| |legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| |lenientTypeCast|Accept and cast values for simple types (string->bool, string->int, int->string)| |false| |library|Library template (sub-template) to use|
**urlsession**
[DEFAULT] HTTP client: URLSession
**alamofire**
HTTP client: Alamofire
|urlsession| +|mapFileBinaryToData|[WARNING] This option will be removed and enabled by default in the future once we've enhanced the code to work with `Data` in all the different situations. Map File and Binary to Data (default: false)| |false| |nonPublicApi|Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers.(default: false)| |null| |objcCompatible|Add additional properties and methods for Objective-C compatibility (default: false)| |null| |podAuthors|Authors used for Podspec| |null| @@ -33,7 +36,11 @@ These options may be applied as additional-properties (cli) or configOptions (pl |responseAs|Optionally use libraries to manage response. Currently PromiseKit, RxSwift, Result, Combine are available.| |null| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|swiftPackagePath|Set a custom source path instead of OpenAPIClient/Classes/OpenAPIs.| |null| |swiftUseApiNamespace|Flag to make all the API classes inner-class of {{projectName}}API| |null| +|useBacktickEscapes|Escape reserved words using backticks (default: false)| |false| +|useClasses|Use final classes for models instead of structs (default: false)| |false| +|useSPMFileStructure|Use SPM file structure and set the source path to Sources/{{projectName}} (default: false).| |null| ## IMPORT MAPPING diff --git a/docs/generators/tiny-cpp.md b/docs/generators/tiny-cpp.md new file mode 100644 index 000000000000..f7f6a0385cac --- /dev/null +++ b/docs/generators/tiny-cpp.md @@ -0,0 +1,243 @@ +--- +title: Config Options for tiny-cpp +sidebar_label: tiny-cpp +--- + +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|controller|name of microcontroller (e.g esp32 or esp8266)| |esp32| +|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true| +|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| +|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|reservedWordPrefix|Prefix to prepend to reserved words in order to avoid conflicts| |r_| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|variableNameFirstCharacterUppercase|Make first character of variable name uppercase (eg. value -> Value)| |true| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | + + +## LANGUAGE PRIMITIVES + + + +## RESERVED WORDS + + + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✗|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Array|✓|OAS2,OAS3 +|Maps|✗|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✗|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✗|ToolingExtension +|MapOfModel|✗|ToolingExtension +|MapOfCollectionOfPrimitives|✗|ToolingExtension +|MapOfCollectionOfModel|✗|ToolingExtension +|MapOfCollectionOfEnum|✗|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✗|OAS2,OAS3 +|Header|✗|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✗|OAS2 +|FormMultipart|✗|OAS2 +|Cookie|✗|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 +|Union|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✓|OAS2,OAS3 +|ApiKey|✓|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✓|OAS3 +|OAuth2_Implicit|✓|OAS2,OAS3 +|OAuth2_Password|✓|OAS2,OAS3 +|OAuth2_ClientCredentials|✓|OAS2,OAS3 +|OAuth2_AuthorizationCode|✓|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✗|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/wsdl-schema.md b/docs/generators/wsdl-schema.md new file mode 100644 index 000000000000..7842f8567492 --- /dev/null +++ b/docs/generators/wsdl-schema.md @@ -0,0 +1,150 @@ +--- +title: Config Options for wsdl-schema +sidebar_label: wsdl-schema +--- + +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true| +|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|hostname|the hostname of the service| |null| +|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| +|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|serviceName|service name for the wsdl| |null| +|soapPath|basepath of the soap services| |null| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | + + +## LANGUAGE PRIMITIVES + + + +## RESERVED WORDS + + + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✗|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Array|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✗|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✓|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✓|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✓|OAS2,OAS3 +|Union|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✓|OAS2,OAS3 +|ApiKey|✓|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✓|OAS3 +|OAuth2_Implicit|✓|OAS2,OAS3 +|OAuth2_Password|✓|OAS2,OAS3 +|OAuth2_ClientCredentials|✓|OAS2,OAS3 +|OAuth2_AuthorizationCode|✓|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/plugins.md b/docs/plugins.md index 224a0d5fa580..c9fbbe5b5484 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -15,7 +15,9 @@ Add to your `build->plugins` section (default phase is `generate-sources` phase) org.openapitools openapi-generator-maven-plugin - 5.0.0 + + 5.1.0 + @@ -43,7 +45,7 @@ For full details of all options, see the [plugin README](https://github.com/Open ### Dependencies -The generated models use commonly use Swagger v2 annotations like `@ApiModelProperty`. A user may add Swagger v3 annotations: +The generated models use commonly used Swagger v2 annotations like `@ApiModelProperty`. A user may add Swagger v3 annotations: ```xml diff --git a/modules/openapi-generator-cli/Dockerfile b/modules/openapi-generator-cli/Dockerfile index e9c64a546197..00fad3e7cdd8 100644 --- a/modules/openapi-generator-cli/Dockerfile +++ b/modules/openapi-generator-cli/Dockerfile @@ -1,6 +1,4 @@ -FROM java:8-jre-alpine - -RUN apk add --no-cache bash +FROM openjdk:11.0-jre-buster ADD target/openapi-generator-cli.jar /opt/openapi-generator/modules/openapi-generator-cli/target/openapi-generator-cli.jar diff --git a/modules/openapi-generator-cli/pom.xml b/modules/openapi-generator-cli/pom.xml index 3d97efb83457..fb3c5139b0e3 100644 --- a/modules/openapi-generator-cli/pom.xml +++ b/modules/openapi-generator-cli/pom.xml @@ -4,7 +4,7 @@ org.openapitools openapi-generator-project - 5.1.1-SNAPSHOT + 5.2.0-SNAPSHOT ../.. diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java index f935b14e6d76..27447fad78ab 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java @@ -134,7 +134,8 @@ public class Generate extends OpenApiGeneratorCommand { title = "type mappings", description = "sets mappings between OpenAPI spec types and generated code types " + "in the format of OpenAPIType=generatedType,OpenAPIType=generatedType. For example: array=List,map=Map,string=String." - + " You can also have multiple occurrences of this option.") + + " You can also have multiple occurrences of this option." + + " To map a specified format, use type+format, e.g. string+password=EncryptedString will map `type: string, format: password` to `EncryptedString`.") private List typeMappings = new ArrayList<>(); @Option( diff --git a/modules/openapi-generator-core/pom.xml b/modules/openapi-generator-core/pom.xml index 7995a10523e5..dc964764aa68 100644 --- a/modules/openapi-generator-core/pom.xml +++ b/modules/openapi-generator-core/pom.xml @@ -6,7 +6,7 @@ openapi-generator-project org.openapitools - 5.1.1-SNAPSHOT + 5.2.0-SNAPSHOT ../.. diff --git a/modules/openapi-generator-gradle-plugin/README.adoc b/modules/openapi-generator-gradle-plugin/README.adoc index ae55fb161369..08b093049004 100644 --- a/modules/openapi-generator-gradle-plugin/README.adoc +++ b/modules/openapi-generator-gradle-plugin/README.adoc @@ -212,7 +212,7 @@ apply plugin: 'org.openapi.generator' |typeMappings |Map(String,String) |None -|Sets mappings between OpenAPI spec types and generated code types. +|Sets mappings between OpenAPI spec types and generated code types in the format of OpenAPIType=generatedType,OpenAPIType=generatedType. For example: `array=List,map=Map,string=String`. You can also have multiple occurrences of this option. To map a specified format, use type+format, e.g. string+password=EncryptedString will map `type: string, format: password` to `EncryptedString`. |additionalProperties |Map(String,Any) diff --git a/modules/openapi-generator-gradle-plugin/gradle.properties b/modules/openapi-generator-gradle-plugin/gradle.properties index c82f792a787a..01c9f563508e 100644 --- a/modules/openapi-generator-gradle-plugin/gradle.properties +++ b/modules/openapi-generator-gradle-plugin/gradle.properties @@ -1,5 +1,5 @@ # RELEASE_VERSION -openApiGeneratorVersion=5.1.1-SNAPSHOT +openApiGeneratorVersion=5.2.0-SNAPSHOT # /RELEASE_VERSION # BEGIN placeholders diff --git a/modules/openapi-generator-gradle-plugin/pom.xml b/modules/openapi-generator-gradle-plugin/pom.xml index bcf9abfe79e1..fc856601f671 100644 --- a/modules/openapi-generator-gradle-plugin/pom.xml +++ b/modules/openapi-generator-gradle-plugin/pom.xml @@ -4,7 +4,7 @@ org.openapitools openapi-generator-project - 5.1.1-SNAPSHOT + 5.2.0-SNAPSHOT ../.. diff --git a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties index 589e91215782..8b65b3b4572d 100644 --- a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties +++ b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties @@ -1,3 +1,3 @@ # RELEASE_VERSION -openApiGeneratorVersion=5.1.1-SNAPSHOT +openApiGeneratorVersion=5.2.0-SNAPSHOT # /RELEASE_VERSION diff --git a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt index b1dcd474ae84..c3e1efcee94e 100644 --- a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt +++ b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt @@ -81,9 +81,8 @@ open class GenerateTask : DefaultTask() { val outputDir = project.objects.property() @Suppress("unused") - @get:Internal @set:Option(option = "input", description = "The input specification.") - @Input + @Internal var input: String? = null set(value) { inputSpec.set(value) diff --git a/modules/openapi-generator-maven-plugin/README.md b/modules/openapi-generator-maven-plugin/README.md index 627fa155e634..64151ad1418c 100644 --- a/modules/openapi-generator-maven-plugin/README.md +++ b/modules/openapi-generator-maven-plugin/README.md @@ -79,7 +79,7 @@ mvn clean compile | `configOptions` | N/A | a **map** of language-specific parameters. To show a full list of generator-specified parameters (options), please use `configHelp` (explained below) | `instantiationTypes` | `openapi.generator.maven.plugin.instantiationTypes` | sets instantiation type mappings in the format of type=instantiatedType,type=instantiatedType. For example (in Java): `array=ArrayList,map=HashMap`. In other words array types will get instantiated as ArrayList in generated code. You can also have multiple occurrences of this option | `importMappings` | `openapi.generator.maven.plugin.importMappings` | specifies mappings between a given class and the import that should be used for that class in the format of type=import,type=import. You can also have multiple occurrences of this option -| `typeMappings` | `openapi.generator.maven.plugin.typeMappings` | sets mappings between OpenAPI spec types and generated code types in the format of OpenAPIType=generatedType,OpenAPIType=generatedType. For example: `array=List,map=Map,string=String`. You can also have multiple occurrences of this option +| `typeMappings` | `openapi.generator.maven.plugin.typeMappings` | sets mappings between OpenAPI spec types and generated code types in the format of OpenAPIType=generatedType,OpenAPIType=generatedType. For example: `array=List,map=Map,string=String`. You can also have multiple occurrences of this option. To map a specified format, use type+format, e.g. string+password=EncryptedString will map `type: string, format: password` to `EncryptedString`. | `languageSpecificPrimitives` | `openapi.generator.maven.plugin.languageSpecificPrimitives` | specifies additional language specific primitive types in the format of type1,type2,type3,type3. For example: `String,boolean,Boolean,Double`. You can also have multiple occurrences of this option | `additionalProperties` | `openapi.generator.maven.plugin.additionalProperties` | 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 | `serverVariableOverrides` | `openapi.generator.maven.plugin.serverVariableOverrides` | A map of server variable overrides for specs that support server URL templating diff --git a/modules/openapi-generator-maven-plugin/examples/java-client.xml b/modules/openapi-generator-maven-plugin/examples/java-client.xml index bd5f9cbc6c96..fb7e9a810c3d 100644 --- a/modules/openapi-generator-maven-plugin/examples/java-client.xml +++ b/modules/openapi-generator-maven-plugin/examples/java-client.xml @@ -13,7 +13,7 @@ org.openapitools openapi-generator-maven-plugin - 5.1.1-SNAPSHOT + 5.2.0-SNAPSHOT diff --git a/modules/openapi-generator-maven-plugin/examples/kotlin.xml b/modules/openapi-generator-maven-plugin/examples/kotlin.xml index f501797cec62..d6ddeeb890db 100644 --- a/modules/openapi-generator-maven-plugin/examples/kotlin.xml +++ b/modules/openapi-generator-maven-plugin/examples/kotlin.xml @@ -15,7 +15,7 @@ org.openapitools openapi-generator-maven-plugin - 5.1.1-SNAPSHOT + 5.2.0-SNAPSHOT diff --git a/modules/openapi-generator-maven-plugin/examples/multi-module/java-client/pom.xml b/modules/openapi-generator-maven-plugin/examples/multi-module/java-client/pom.xml index 04e2e1dd6127..b2a3696e1c08 100644 --- a/modules/openapi-generator-maven-plugin/examples/multi-module/java-client/pom.xml +++ b/modules/openapi-generator-maven-plugin/examples/multi-module/java-client/pom.xml @@ -19,7 +19,7 @@ org.openapitools openapi-generator-maven-plugin - 5.1.1-SNAPSHOT + 5.2.0-SNAPSHOT diff --git a/modules/openapi-generator-maven-plugin/examples/non-java-invalid-spec.xml b/modules/openapi-generator-maven-plugin/examples/non-java-invalid-spec.xml index 2fdca946a92f..f3ef4ff8d49c 100644 --- a/modules/openapi-generator-maven-plugin/examples/non-java-invalid-spec.xml +++ b/modules/openapi-generator-maven-plugin/examples/non-java-invalid-spec.xml @@ -13,7 +13,7 @@ org.openapitools openapi-generator-maven-plugin - 5.1.1-SNAPSHOT + 5.2.0-SNAPSHOT diff --git a/modules/openapi-generator-maven-plugin/examples/non-java.xml b/modules/openapi-generator-maven-plugin/examples/non-java.xml index 808f52ddc066..1f18f87d7553 100644 --- a/modules/openapi-generator-maven-plugin/examples/non-java.xml +++ b/modules/openapi-generator-maven-plugin/examples/non-java.xml @@ -13,7 +13,7 @@ org.openapitools openapi-generator-maven-plugin - 5.1.1-SNAPSHOT + 5.2.0-SNAPSHOT diff --git a/modules/openapi-generator-maven-plugin/examples/spring.xml b/modules/openapi-generator-maven-plugin/examples/spring.xml index 538b3a1f3d03..c0932d04dd09 100644 --- a/modules/openapi-generator-maven-plugin/examples/spring.xml +++ b/modules/openapi-generator-maven-plugin/examples/spring.xml @@ -20,7 +20,7 @@ org.openapitools openapi-generator-maven-plugin - 5.1.1-SNAPSHOT + 5.2.0-SNAPSHOT diff --git a/modules/openapi-generator-maven-plugin/pom.xml b/modules/openapi-generator-maven-plugin/pom.xml index 4de0f38b2b5a..f58c7f17bcd1 100644 --- a/modules/openapi-generator-maven-plugin/pom.xml +++ b/modules/openapi-generator-maven-plugin/pom.xml @@ -5,7 +5,7 @@ org.openapitools openapi-generator-project - 5.1.1-SNAPSHOT + 5.2.0-SNAPSHOT ../.. diff --git a/modules/openapi-generator-online/pom.xml b/modules/openapi-generator-online/pom.xml index 16e5b8b6f3fa..eff136ed4a37 100644 --- a/modules/openapi-generator-online/pom.xml +++ b/modules/openapi-generator-online/pom.xml @@ -4,7 +4,7 @@ org.openapitools openapi-generator-project - 5.1.1-SNAPSHOT + 5.2.0-SNAPSHOT ../.. diff --git a/modules/openapi-generator/pom.xml b/modules/openapi-generator/pom.xml index 8c5211e0637a..2347fc4090ea 100644 --- a/modules/openapi-generator/pom.xml +++ b/modules/openapi-generator/pom.xml @@ -4,7 +4,7 @@ org.openapitools openapi-generator-project - 5.1.1-SNAPSHOT + 5.2.0-SNAPSHOT ../.. diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java index 2e7151dc94e2..631ff47eedbc 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java @@ -206,7 +206,7 @@ public class CodegenConstants { public static final String MODEL_PROPERTY_NAMING_DESC = "Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name"; public static final String DOTNET_FRAMEWORK = "targetFramework"; - public static final String DOTNET_FRAMEWORK_DESC = "The target .NET framework version."; + public static final String DOTNET_FRAMEWORK_DESC = "The target .NET framework version. To target multiple frameworks, use `;` as the separator, e.g. `netstandard2.1;netcoreapp3.0`"; public static final String TEMPLATING_ENGINE = "templatingEngine"; public static final String TEMPLATING_ENGINE_DESC = "The templating engine plugin to use: \"mustache\" (default) or \"handlebars\" (beta)"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java index e7a3adce6a39..7669f8379193 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java @@ -64,7 +64,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties { public String defaultValue; public String arrayModelType; public boolean isAlias; // Is this effectively an alias of another simple type - public boolean isString, isInteger, isLong, isNumber, isNumeric, isFloat, isDouble, isDate, isDateTime; + public boolean isString, isInteger, isLong, isNumber, isNumeric, isFloat, isDouble, isDate, isDateTime, isShort, isUnboundedInteger; private boolean additionalPropertiesIsAnyType; public List vars = new ArrayList(); // all properties (without parent's properties) public List allVars = new ArrayList(); // all properties (with parent's properties) @@ -606,6 +606,22 @@ public void setIsArray(boolean isArray) { this.isArray = isArray; } + @Override + public boolean getIsShort() { return isShort; } + + @Override + public void setIsShort(boolean isShort) { + this.isShort = isShort; + } + + @Override + public boolean getIsUnboundedInteger() { return isUnboundedInteger; } + + @Override + public void setIsUnboundedInteger(boolean isUnboundedInteger) { + this.isUnboundedInteger = isUnboundedInteger; + } + @Override public CodegenProperty getAdditionalProperties() { return additionalProperties; } @@ -752,7 +768,9 @@ public boolean equals(Object o) { return isAlias == that.isAlias && isString == that.isString && isInteger == that.isInteger && + isShort == that.isShort && isLong == that.isLong && + isUnboundedInteger == that.isUnboundedInteger && isNumber == that.isNumber && isNumeric == that.isNumeric && isFloat == that.isFloat && @@ -839,7 +857,7 @@ public int hashCode() { getDescription(), getClassVarName(), getModelJson(), getDataType(), getXmlPrefix(), getXmlNamespace(), getXmlName(), getClassFilename(), getUnescapedDescription(), getDiscriminator(), getDefaultValue(), getArrayModelType(), isAlias, isString, isInteger, isLong, isNumber, isNumeric, isFloat, isDouble, - isDate, isDateTime, isNull, hasValidation, + isDate, isDateTime, isNull, hasValidation, isShort, isUnboundedInteger, getVars(), getAllVars(), getRequiredVars(), getOptionalVars(), getReadOnlyVars(), getReadWriteVars(), getParentVars(), getAllowableValues(), getMandatory(), getAllMandatory(), getImports(), hasVars, isEmptyVars(), hasMoreModels, hasEnums, isEnum, isNullable, hasRequired, hasOptional, isArray, @@ -881,7 +899,9 @@ public String toString() { sb.append(", isAlias=").append(isAlias); sb.append(", isString=").append(isString); sb.append(", isInteger=").append(isInteger); + sb.append(", isShort=").append(isShort); sb.append(", isLong=").append(isLong); + sb.append(", isUnboundedInteger=").append(isUnboundedInteger); sb.append(", isNumber=").append(isNumber); sb.append(", isNumeric=").append(isNumeric); sb.append(", isFloat=").append(isFloat); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java index b41adac44871..0a8e7b31991c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java @@ -29,7 +29,7 @@ public class CodegenOperation { isArray, isMultipart, isResponseBinary = false, isResponseFile = false, hasReference = false, isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy, - isRestful, isDeprecated, isCallbackRequest, uniqueItems; + isRestful, isDeprecated, isCallbackRequest, uniqueItems, hasDefaultResponse = false; public String path, operationId, returnType, returnFormat, httpMethod, returnBaseType, returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse; public CodegenDiscriminator discriminator; @@ -168,6 +168,15 @@ public boolean getHasExamples() { return nonempty(examples); } + /** + * Check if there's a default response + * + * @return true if responses contain a default response, false otherwise + */ + public boolean getHasDefaultResponse() { + return responses.stream().filter(response -> response.isDefault).findFirst().isPresent(); + } + /** * Check if act as Restful index method * @@ -270,6 +279,7 @@ public String toString() { sb.append(", isResponseBinary=").append(isResponseBinary); sb.append(", isResponseFile=").append(isResponseFile); sb.append(", hasReference=").append(hasReference); + sb.append(", hasDefaultResponse=").append(hasDefaultResponse); sb.append(", isRestfulIndex=").append(isRestfulIndex); sb.append(", isRestfulShow=").append(isRestfulShow); sb.append(", isRestfulCreate=").append(isRestfulCreate); @@ -343,6 +353,7 @@ public boolean equals(Object o) { isResponseBinary == that.isResponseBinary && isResponseFile == that.isResponseFile && hasReference == that.hasReference && + hasDefaultResponse == that.hasDefaultResponse && isRestfulIndex == that.isRestfulIndex && isRestfulShow == that.isRestfulShow && isRestfulCreate == that.isRestfulCreate && @@ -400,7 +411,7 @@ public int hashCode() { return Objects.hash(responseHeaders, hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams, hasRequiredParams, returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMap, - isArray, isMultipart, isResponseBinary, isResponseFile, hasReference, isRestfulIndex, + isArray, isMultipart, isResponseBinary, isResponseFile, hasReference, hasDefaultResponse, isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy, isRestful, isDeprecated, isCallbackRequest, uniqueItems, path, operationId, returnType, httpMethod, returnBaseType, returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse, discriminator, consumes, diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java index 326785046d9a..d2dc9fa98089 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java @@ -35,7 +35,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { public String example; // example value (x-example) public String jsonSchema; public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, - isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType; + isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType, isShort, isUnboundedInteger; public boolean isArray, isMap; public boolean isFile; public boolean isEnum; @@ -184,7 +184,9 @@ public CodegenParameter copy() { output.isString = this.isString; output.isNumeric = this.isNumeric; output.isInteger = this.isInteger; + output.isShort = this.isShort; output.isLong = this.isLong; + output.isUnboundedInteger = this.isUnboundedInteger; output.isDouble = this.isDouble; output.isDecimal = this.isDecimal; output.isFloat = this.isFloat; @@ -209,7 +211,7 @@ public CodegenParameter copy() { @Override public int hashCode() { - return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, isContainer, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style, isDeepObject, example, jsonSchema, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType, isArray, isMap, isFile, isEnum, _enum, allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, getMaxProperties(), getMinProperties(), isNullable, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull, additionalPropertiesIsAnyType, hasVars, hasRequired); + return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, isContainer, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style, isDeepObject, example, jsonSchema, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType, isArray, isMap, isFile, isEnum, _enum, allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, getMaxProperties(), getMinProperties(), isNullable, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull, additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger); } @Override @@ -231,7 +233,9 @@ public boolean equals(Object o) { isString == that.isString && isNumeric == that.isNumeric && isInteger == that.isInteger && + isShort == that.isShort && isLong == that.isLong && + isUnboundedInteger == that.isUnboundedInteger && isNumber == that.isNumber && isFloat == that.isFloat && isDouble == that.isDouble && @@ -328,7 +332,9 @@ public String toString() { sb.append(", isString=").append(isString); sb.append(", isNumeric=").append(isNumeric); sb.append(", isInteger=").append(isInteger); + sb.append(", isShort=").append(isShort); sb.append(", isLong=").append(isLong); + sb.append(", isUnboundedInteger=").append(isUnboundedInteger); sb.append(", isNumber=").append(isNumber); sb.append(", isFloat=").append(isFloat); sb.append(", isDouble=").append(isDouble); @@ -560,6 +566,22 @@ public void setIsArray(boolean isArray) { this.isArray = isArray; } + @Override + public boolean getIsShort() { return isShort; } + + @Override + public void setIsShort(boolean isShort) { + this.isShort = isShort; + } + + @Override + public boolean getIsUnboundedInteger() { return isUnboundedInteger; } + + @Override + public void setIsUnboundedInteger(boolean isUnboundedInteger) { + this.isUnboundedInteger = isUnboundedInteger; + } + @Override public CodegenProperty getAdditionalProperties() { return additionalProperties; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java index b20e55f61b42..47e69fe89d4a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java @@ -118,7 +118,9 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti public boolean isString; public boolean isNumeric; public boolean isInteger; + public boolean isShort; public boolean isLong; + public boolean isUnboundedInteger; public boolean isNumber; public boolean isFloat; public boolean isDouble; @@ -507,6 +509,22 @@ public void setIsArray(boolean isArray) { this.isArray = isArray; } + @Override + public boolean getIsShort() { return isShort; } + + @Override + public void setIsShort(boolean isShort) { + this.isShort = isShort; + } + + @Override + public boolean getIsUnboundedInteger() { return isUnboundedInteger; } + + @Override + public void setIsUnboundedInteger(boolean isUnboundedInteger) { + this.isUnboundedInteger = isUnboundedInteger; + } + public Map getVendorExtensions() { return vendorExtensions; } @@ -765,7 +783,9 @@ public String toString() { sb.append(", isString=").append(isString); sb.append(", isNumeric=").append(isNumeric); sb.append(", isInteger=").append(isInteger); + sb.append(", isShort=").append(isShort); sb.append(", isLong=").append(isLong); + sb.append(", isUnboundedInteger=").append(isUnboundedInteger); sb.append(", isNumber=").append(isNumber); sb.append(", isFloat=").append(isFloat); sb.append(", isDouble=").append(isDouble); @@ -838,7 +858,9 @@ public boolean equals(Object o) { isString == that.isString && isNumeric == that.isNumeric && isInteger == that.isInteger && + isShort == that.isShort && isLong == that.isLong && + isUnboundedInteger == that.isUnboundedInteger && isNumber == that.isNumber && isFloat == that.isFloat && isDouble == that.isDouble && @@ -926,7 +948,7 @@ public int hashCode() { hasMoreNonReadOnly, isPrimitiveType, isModel, isContainer, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isFile, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, - isArray, isMap, isEnum, isReadOnly, isWriteOnly, isNullable, + isArray, isMap, isEnum, isReadOnly, isWriteOnly, isNullable, isShort, isUnboundedInteger, isSelfReference, isCircularReference, isDiscriminator, _enum, allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, isInherited, discriminatorValue, nameInCamelCase, diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java index bb062c1304fc..d8c1756f4462 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java @@ -36,7 +36,9 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { public boolean isString; public boolean isNumeric; public boolean isInteger; + public boolean isShort; public boolean isLong; + public boolean isUnboundedInteger; public boolean isNumber; public boolean isFloat; public boolean isDouble; @@ -89,7 +91,7 @@ public int hashCode() { isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBoolean, isDate, isDateTime, isUuid, isEmail, isModel, isFreeFormObject, isAnyType, isDefault, simpleType, primitiveType, isMap, isArray, isBinary, isFile, schema, jsonSchema, vendorExtensions, items, additionalProperties, - vars, requiredVars, isNull, hasValidation, + vars, requiredVars, isNull, hasValidation, isShort, isUnboundedInteger, getMaxProperties(), getMinProperties(), uniqueItems, getMaxItems(), getMinItems(), getMaxLength(), getMinLength(), exclusiveMinimum, exclusiveMaximum, getMinimum(), getMaximum(), getPattern(), is1xx, is2xx, is3xx, is4xx, is5xx, additionalPropertiesIsAnyType, hasVars, hasRequired); @@ -104,7 +106,9 @@ public boolean equals(Object o) { isString == that.isString && isNumeric == that.isNumeric && isInteger == that.isInteger && + isShort == that.isShort && isLong == that.isLong && + isUnboundedInteger == that.isUnboundedInteger && isNumber == that.isNumber && isFloat == that.isFloat && isDouble == that.isDouble && @@ -316,6 +320,22 @@ public void setIsArray(boolean isArray) { this.isArray = isArray; } + @Override + public boolean getIsShort() { return isShort; } + + @Override + public void setIsShort(boolean isShort) { + this.isShort = isShort; + } + + @Override + public boolean getIsUnboundedInteger() { return isUnboundedInteger; } + + @Override + public void setIsUnboundedInteger(boolean isUnboundedInteger) { + this.isUnboundedInteger = isUnboundedInteger; + } + @Override public void setIsModel(boolean isModel) { this.isModel = isModel; @@ -402,7 +422,9 @@ public String toString() { sb.append(", isString=").append(isString); sb.append(", isNumeric=").append(isNumeric); sb.append(", isInteger=").append(isInteger); + sb.append(", isShort=").append(isShort); sb.append(", isLong=").append(isLong); + sb.append(", isUnboundedInteger=").append(isUnboundedInteger); sb.append(", isNumber=").append(isNumber); sb.append(", isFloat=").append(isFloat); sb.append(", isDouble=").append(isDouble); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenSecurity.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenSecurity.java index ca659105b7fb..a5d5bd4ce857 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenSecurity.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenSecurity.java @@ -39,7 +39,7 @@ public class CodegenSecurity { public String keyParamName; public Boolean isKeyInQuery, isKeyInHeader, isKeyInCookie; // Oauth specific - public String flow, authorizationUrl, tokenUrl; + public String flow, authorizationUrl, tokenUrl, refreshUrl; public List> scopes; public Boolean isCode, isPassword, isApplication, isImplicit; @@ -66,6 +66,7 @@ public CodegenSecurity filterByScopeNames(List filterScopes) { filteredSecurity.flow = flow; filteredSecurity.tokenUrl = tokenUrl; filteredSecurity.authorizationUrl = authorizationUrl; + filteredSecurity.refreshUrl = refreshUrl; // It is not possible to deep copy the extensions, as we have no idea what types they are. // So the filtered method *will* refer to the original extensions, if any. filteredSecurity.vendorExtensions = new HashMap(vendorExtensions); @@ -109,6 +110,7 @@ public boolean equals(Object o) { Objects.equals(flow, that.flow) && Objects.equals(authorizationUrl, that.authorizationUrl) && Objects.equals(tokenUrl, that.tokenUrl) && + Objects.equals(refreshUrl, that.refreshUrl) && Objects.equals(scopes, that.scopes) && Objects.equals(isCode, that.isCode) && Objects.equals(isPassword, that.isPassword) && @@ -122,7 +124,7 @@ public int hashCode() { return Objects.hash(name, type, scheme, isBasic, isOAuth, isApiKey, isBasicBasic, isHttpSignature, isBasicBearer, bearerFormat, vendorExtensions, keyParamName, isKeyInQuery, isKeyInHeader, isKeyInCookie, flow, - authorizationUrl, tokenUrl, scopes, isCode, isPassword, isApplication, isImplicit); + authorizationUrl, tokenUrl, refreshUrl, scopes, isCode, isPassword, isApplication, isImplicit); } @Override @@ -146,6 +148,7 @@ public String toString() { sb.append(", flow='").append(flow).append('\''); sb.append(", authorizationUrl='").append(authorizationUrl).append('\''); sb.append(", tokenUrl='").append(tokenUrl).append('\''); + sb.append(", refreshUrl='").append(refreshUrl).append('\''); sb.append(", scopes=").append(scopes); sb.append(", isCode=").append(isCode); sb.append(", isPassword=").append(isPassword); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index 590e925a1422..c26a4df1362e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -2043,6 +2043,10 @@ protected String getSingleSchemaType(Schema schema) { private String getPrimitiveType(Schema schema) { if (schema == null) { throw new RuntimeException("schema cannot be null in getPrimitiveType"); + } else if (typeMapping.containsKey(schema.getType() + "+" + schema.getFormat())) { + // allows custom type_format mapping. + // use {type}+{format} + return typeMapping.get(schema.getType() + "+" + schema.getFormat()); } else if (ModelUtils.isNullType(schema)) { // The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x, // though this tooling supports it. @@ -2528,8 +2532,13 @@ public CodegenModel fromModel(String name, Schema schema) { m.isNumeric = Boolean.TRUE; if (ModelUtils.isLongSchema(schema)) { // int64/long format m.isLong = Boolean.TRUE; - } else { // int32 format - m.isInteger = Boolean.TRUE; + } else { + m.isInteger = Boolean.TRUE; // older use case, int32 and unbounded int + if (ModelUtils.isShortSchema(schema)) { // int32 + m.setIsShort(Boolean.TRUE); + } else { // unbounded integer + m.setIsUnboundedInteger(Boolean.TRUE); + } } } else if (ModelUtils.isDateTimeSchema(schema)) { // NOTE: DateTime schemas as CodegenModel is a rare use case and may be removed at a later date. @@ -2702,14 +2711,14 @@ private CodegenProperty discriminatorFound(String composedSchemaName, Schema sc, String modelName = ModelUtils.getSimpleRef(oneOf.get$ref()); CodegenProperty thisCp = discriminatorFound(composedSchemaName, oneOf, discPropName, openAPI); if (thisCp == null) { - throw new RuntimeException("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the referenced OneOf schema '" + modelName + "' is missing " + discPropName); + LOGGER.warn("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the referenced OneOf schema '" + modelName + "' is missing " + discPropName); } if (cp.dataType == null) { cp = thisCp; continue; } if (cp != thisCp) { - throw new RuntimeException("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the OneOf schema '" + modelName + "' has a different " + discPropName + " definition than the prior OneOf schema's. Make sure the " + discPropName + " type and required values are the same"); + LOGGER.warn("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the OneOf schema '" + modelName + "' has a different " + discPropName + " definition than the prior OneOf schema's. Make sure the " + discPropName + " type and required values are the same"); } } return cp; @@ -2721,14 +2730,14 @@ private CodegenProperty discriminatorFound(String composedSchemaName, Schema sc, String modelName = ModelUtils.getSimpleRef(anyOf.get$ref()); CodegenProperty thisCp = discriminatorFound(composedSchemaName, anyOf, discPropName, openAPI); if (thisCp == null) { - throw new RuntimeException("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the referenced AnyOf schema '" + modelName + "' is missing " + discPropName); + LOGGER.warn("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the referenced AnyOf schema '" + modelName + "' is missing " + discPropName); } if (cp.dataType == null) { cp = thisCp; continue; } if (cp != thisCp) { - throw new RuntimeException("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the AnyOf schema '" + modelName + "' has a different " + discPropName + " definition than the prior AnyOf schema's. Make sure the " + discPropName + " type and required values are the same"); + LOGGER.warn("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the AnyOf schema '" + modelName + "' has a different " + discPropName + " definition than the prior AnyOf schema's. Make sure the " + discPropName + " type and required values are the same"); } } return cp; @@ -2787,7 +2796,7 @@ private Discriminator recursiveGetDiscriminator(Schema sc, OpenAPI openAPI) { } } if (discriminatorsPropNames.size() > 1) { - throw new RuntimeException("The oneOf schemas have conflicting discriminator property names. " + + LOGGER.warn("The oneOf schemas have conflicting discriminator property names. " + "oneOf schemas must have the same property name, but found " + String.join(", ", discriminatorsPropNames)); } if (foundDisc != null && (hasDiscriminatorCnt + hasNullTypeCnt) == composedSchema.getOneOf().size() && discriminatorsPropNames.size() == 1) { @@ -2816,7 +2825,7 @@ private Discriminator recursiveGetDiscriminator(Schema sc, OpenAPI openAPI) { } } if (discriminatorsPropNames.size() > 1) { - throw new RuntimeException("The anyOf schemas have conflicting discriminator property names. " + + LOGGER.warn("The anyOf schemas have conflicting discriminator property names. " + "anyOf schemas must have the same property name, but found " + String.join(", ", discriminatorsPropNames)); } if (foundDisc != null && (hasDiscriminatorCnt + hasNullTypeCnt) == composedSchema.getAnyOf().size() && discriminatorsPropNames.size() == 1) { @@ -2866,7 +2875,7 @@ protected List getOneOfAnyOfDescendants(String composedSchemaName, // schemas also has inline composed schemas // Note: if it is only inline one level, then the inline model resolver will move it into its own // schema and make it a $ref schema in the oneOf/anyOf location - throw new RuntimeException("Invalid inline schema defined in oneOf/anyOf in '" + composedSchemaName + "'. Per the OpenApi spec, for this case when a composed schema defines a discriminator, the oneOf/anyOf schemas must use $ref. Change this inline definition to a $ref definition"); + LOGGER.warn("Invalid inline schema defined in oneOf/anyOf in '" + composedSchemaName + "'. Per the OpenApi spec, for this case when a composed schema defines a discriminator, the oneOf/anyOf schemas must use $ref. Change this inline definition to a $ref definition"); } CodegenProperty df = discriminatorFound(composedSchemaName, sc, discPropName, openAPI); String modelName = ModelUtils.getSimpleRef(ref); @@ -2886,7 +2895,7 @@ protected List getOneOfAnyOfDescendants(String composedSchemaName, msgSuffix += spacer + "invalid optional definition of " + discPropName + ", include it in required"; } } - throw new RuntimeException("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the referenced schema '" + modelName + "' is incorrect. " + msgSuffix); + LOGGER.warn("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the referenced schema '" + modelName + "' is incorrect. " + msgSuffix); } MappedModel mm = new MappedModel(modelName, toModelName(modelName)); descendentSchemas.add(mm); @@ -3188,10 +3197,14 @@ public CodegenProperty fromProperty(String name, Schema p) { property.isNumeric = Boolean.TRUE; if (ModelUtils.isLongSchema(p)) { // int64/long format property.isLong = Boolean.TRUE; - } else { // int32 format - property.isInteger = Boolean.TRUE; + } else { + property.isInteger = Boolean.TRUE; // older use case, int32 and unbounded int + if (ModelUtils.isShortSchema(p)) { // int32 + property.setIsShort(Boolean.TRUE); + } else { // unbounded integer + property.setIsUnboundedInteger(Boolean.TRUE); + } } - } else if (ModelUtils.isBooleanSchema(p)) { // boolean type property.isBoolean = true; property.getter = toBooleanGetter(name); @@ -4063,6 +4076,11 @@ public CodegenResponse fromResponse(String responseCode, ApiResponse response) { } else if (Boolean.TRUE.equals(cp.isInteger)) { r.isInteger = true; r.isNumeric = true; + if (Boolean.TRUE.equals(cp.isShort)) { + r.isShort = true; + } else if (Boolean.TRUE.equals(cp.isUnboundedInteger)) { + r.isUnboundedInteger = true; + } } else if (Boolean.TRUE.equals(cp.isNumber)) { r.isNumber = true; r.isNumeric = true; @@ -5379,6 +5397,11 @@ public void setParameterBooleanFlagWithCodegenProperty(CodegenParameter paramete } else if (Boolean.TRUE.equals(property.isInteger)) { parameter.isInteger = true; parameter.isPrimitiveType = true; + if (Boolean.TRUE.equals(property.isShort)) { + parameter.isShort = true; + } else if (Boolean.TRUE.equals(property.isUnboundedInteger)) { + parameter.isUnboundedInteger = true; + } } else if (Boolean.TRUE.equals(property.isDouble)) { parameter.isDouble = true; parameter.isPrimitiveType = true; @@ -5599,6 +5622,7 @@ protected String getContentType(RequestBody requestBody) { private void setOauth2Info(CodegenSecurity codegenSecurity, OAuthFlow flow) { codegenSecurity.authorizationUrl = flow.getAuthorizationUrl(); codegenSecurity.tokenUrl = flow.getTokenUrl(); + codegenSecurity.refreshUrl = flow.getRefreshUrl(); if (flow.getScopes() != null && !flow.getScopes().isEmpty()) { List> scopes = new ArrayList<>(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java index 9fde6eaa0478..d2e1bb4500d3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java @@ -938,7 +938,7 @@ private void processUserDefinedTemplates() { // TODO: initial behavior is "merge" user defined with built-in templates. consider offering user a "replace" option. if (userDefinedTemplates != null && !userDefinedTemplates.isEmpty()) { Map supportingFilesMap = config.supportingFiles().stream() - .collect(Collectors.toMap(TemplateDefinition::getTemplateFile, Function.identity())); + .collect(Collectors.toMap(TemplateDefinition::getTemplateFile, Function.identity(), (oldValue, newValue) -> oldValue)); // TemplateFileType.SupportingFiles userDefinedTemplates.stream() diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java index 4eb567b6cdc3..ea677853335f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java @@ -77,7 +77,15 @@ public interface IJsonSchemaValidationProperties { boolean getIsArray(); - void setIsArray(boolean isArray); + void setIsArray(boolean isShort); + + boolean getIsShort(); + + void setIsShort(boolean isShort); + + boolean getIsUnboundedInteger(); + + void setIsUnboundedInteger(boolean isUnboundedInteger); CodegenProperty getAdditionalProperties(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java index 6cd5d2926e83..c5d8f65516d2 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java @@ -1,7 +1,6 @@ package org.openapitools.codegen.languages; import com.google.common.collect.Lists; -import com.google.common.collect.Maps; import com.google.common.collect.Sets; import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.media.ArraySchema; @@ -29,6 +28,9 @@ public abstract class AbstractDartCodegen extends DefaultCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractDartCodegen.class); + protected static final List DEFAULT_SUPPORTED_CONTENT_TYPES = Arrays.asList( + "application/json", "application/x-www-form-urlencoded", "multipart/form-data"); + public static final String PUB_LIBRARY = "pubLibrary"; public static final String PUB_NAME = "pubName"; public static final String PUB_VERSION = "pubVersion"; @@ -556,6 +558,68 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation return op; } + @Override + public Map postProcessOperationsWithModels(Map objs, List allModels) { + super.postProcessOperationsWithModels(objs, allModels); + Map operations = (Map) objs.get("operations"); + if (operations != null) { + List ops = (List) operations.get("operation"); + for (CodegenOperation op : ops) { + if (op.hasConsumes) { + if (!op.formParams.isEmpty() || op.isMultipart) { + // DefaultCodegen only sets this if the first consumes mediaType + // is application/x-www-form-urlencoded or multipart. + // Can just use the original + op.prioritizedContentTypes = op.consumes; + } else { + // Prioritize content types by moving application/json to the front + // similar to JavaCodegen + op.prioritizedContentTypes = prioritizeContentTypes(op.consumes); + String mediaType = op.prioritizedContentTypes.get(0).get("mediaType"); + if (!DEFAULT_SUPPORTED_CONTENT_TYPES.contains(mediaType)) { + LOGGER.warn("The media-type '{}' for operation '{}' is not support in the Dart generators by default.", mediaType, op.path); + } + } + } + } + } + return objs; + } + + private List> prioritizeContentTypes(List> consumes) { + if (consumes.size() <= 1) { + // no need to change any order + return consumes; + } + + List> prioritizedContentTypes = new ArrayList<>(consumes.size()); + + List> jsonVendorMimeTypes = new ArrayList<>(consumes.size()); + List> jsonMimeTypes = new ArrayList<>(consumes.size()); + + for (Map consume : consumes) { + String mediaType = consume.get("mediaType"); + if (isJsonVendorMimeType(mediaType)) { + jsonVendorMimeTypes.add(consume); + } else if (isJsonMimeType(mediaType)) { + jsonMimeTypes.add(consume); + } else { + prioritizedContentTypes.add(consume); + } + } + + prioritizedContentTypes.addAll(0, jsonMimeTypes); + prioritizedContentTypes.addAll(0, jsonVendorMimeTypes); + return prioritizedContentTypes; + } + + private static boolean isMultipartType(String mediaType) { + if (mediaType != null) { + return "multipart/form-data".equals(mediaType); + } + return false; + } + @Override protected void updateEnumVarsWithExtensions(List> enumVars, Map vendorExtensions, String dataType) { if (vendorExtensions != null && useEnumExtension && vendorExtensions.containsKey("x-enum-values")) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java index 2765920fab4f..eced1ac0e782 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java @@ -600,6 +600,7 @@ public String patternCorrection(String pattern) { public void setPackageName(String packageName) { this.packageName = packageName; + additionalProperties.put(CodegenConstants.PACKAGE_NAME, this.packageName); } public void setProjectName(String projectName) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonConnexionServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonConnexionServerCodegen.java index 3898b7c09daf..df60913e61e4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonConnexionServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonConnexionServerCodegen.java @@ -52,6 +52,7 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho // nose is a python testing framework, we use pytest if USE_NOSE is unset public static final String USE_NOSE = "useNose"; public static final String PYTHON_SRC_ROOT = "pythonSrcRoot"; + public static final String USE_PYTHON_SRC_ROOT_IN_IMPORTS = "usePythonSrcRootInImports"; static final String MEDIA_TYPE = "mediaType"; protected int serverPort = 8080; @@ -62,6 +63,7 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho protected boolean featureCORS = Boolean.FALSE; protected boolean useNose = Boolean.FALSE; protected String pythonSrcRoot; + protected boolean usePythonSrcRootInImports = Boolean.FALSE; public AbstractPythonConnexionServerCodegen(String templateDirectory, boolean fixBodyNameValue) { super(); @@ -79,7 +81,7 @@ public AbstractPythonConnexionServerCodegen(String templateDirectory, boolean fi typeMapping.put("map", "Dict"); // set the output folder here - outputFolder = "generated-code/connexion"; + outputFolder = "generated-code" + File.separatorChar + "connexion"; apiTemplateFiles.put("controller.mustache", ".py"); modelTemplateFiles.put("model.mustache", ".py"); @@ -132,6 +134,8 @@ public AbstractPythonConnexionServerCodegen(String templateDirectory, boolean fi defaultValue(Boolean.FALSE.toString())); cliOptions.add(new CliOption(PYTHON_SRC_ROOT, "put python sources in this subdirectory of output folder (defaults to \"\" for). Use this for src/ layout."). defaultValue("")); + cliOptions.add(new CliOption(USE_PYTHON_SRC_ROOT_IN_IMPORTS, "include pythonSrcRoot in import namespaces."). + defaultValue("false")); } protected void addSupportingFiles() { @@ -147,7 +151,6 @@ public void processOpts() { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); } else { setPackageName("openapi_server"); - additionalProperties.put(CodegenConstants.PACKAGE_NAME, this.packageName); } if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); @@ -177,9 +180,19 @@ public void processOpts() { if (additionalProperties.containsKey(USE_NOSE)) { setUseNose((String) additionalProperties.get(USE_NOSE)); } + if (additionalProperties.containsKey(USE_PYTHON_SRC_ROOT_IN_IMPORTS)) { + setUsePythonSrcRootInImports((String) additionalProperties.get(USE_PYTHON_SRC_ROOT_IN_IMPORTS)); + } if (additionalProperties.containsKey(PYTHON_SRC_ROOT)) { - setPythonSrcRoot((String) additionalProperties.get(PYTHON_SRC_ROOT)); - additionalProperties.put(PYTHON_SRC_ROOT, pythonSrcRoot); + String pythonSrcRoot = (String) additionalProperties.get(PYTHON_SRC_ROOT); + if (usePythonSrcRootInImports) { + // if we prepend the package name if the pythonSrcRoot we get the desired effect. + // but we also need to set pythonSrcRoot itself to "" to ensure all the paths are + // what we expect. + setPackageName(pythonSrcRoot + "." + packageName); + pythonSrcRoot = ""; + } + setPythonSrcRoot(pythonSrcRoot); } else { setPythonSrcRoot(""); } @@ -218,6 +231,11 @@ public void setPythonSrcRoot(String val) { } else { this.pythonSrcRoot = pySrcRoot + File.separator; } + additionalProperties.put(PYTHON_SRC_ROOT, StringUtils.defaultIfBlank(this.pythonSrcRoot, null)); + } + + public void setUsePythonSrcRootInImports(String val) { + this.usePythonSrcRootInImports = Boolean.parseBoolean(val); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java index a52fa88609a5..141cd952bdec 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java @@ -60,6 +60,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { public static final String USE_NEWTONSOFT = "useNewtonsoft"; public static final String USE_DEFAULT_ROUTING = "useDefaultRouting"; public static final String NEWTONSOFT_VERSION = "newtonsoftVersion"; + public static final String NULLABLE_REFERENCE_TYPES = "nullableReferenceTypes"; private String packageGuid = "{" + randomUUID().toString().toUpperCase(Locale.ROOT) + "}"; private String userSecretsGuid = randomUUID().toString(); @@ -84,6 +85,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { private boolean useFrameworkReference = false; private boolean useNewtonsoft = true; private boolean useDefaultRouting = true; + private boolean nullableReferenceTypes = false; private String newtonsoftVersion = "3.0.0"; public AspNetCoreServerCodegen() { @@ -199,14 +201,14 @@ public AspNetCoreServerCodegen() { aspnetCoreVersion.addEnum("5.0", "ASP.NET Core 5.0"); aspnetCoreVersion.setDefault("3.1"); aspnetCoreVersion.setOptValue(aspnetCoreVersion.getDefault()); - addOption(aspnetCoreVersion.getOpt(), aspnetCoreVersion.getDescription(), aspnetCoreVersion.getOptValue()); + cliOptions.add(aspnetCoreVersion); swashbuckleVersion.addEnum("3.0.0", "Swashbuckle 3.0.0"); swashbuckleVersion.addEnum("4.0.0", "Swashbuckle 4.0.0"); swashbuckleVersion.addEnum("5.0.0", "Swashbuckle 5.0.0"); swashbuckleVersion.setDefault("3.0.0"); swashbuckleVersion.setOptValue(swashbuckleVersion.getDefault()); - addOption(swashbuckleVersion.getOpt(), swashbuckleVersion.getDescription(), swashbuckleVersion.getOptValue()); + cliOptions.add(swashbuckleVersion); // CLI Switches addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, @@ -249,6 +251,11 @@ public AspNetCoreServerCodegen() { "Use default routing for the ASP.NET Core version.", useDefaultRouting); + addSwitch(NULLABLE_REFERENCE_TYPES, + "Annotate Project with annotations and use ? annotation on all nullable attributes. " + + "Only supported on C# 8 / ASP.NET Core 3.0 or newer.", + nullableReferenceTypes); + addOption(CodegenConstants.ENUM_NAME_SUFFIX, CodegenConstants.ENUM_NAME_SUFFIX_DESC, enumNameSuffix); @@ -267,13 +274,13 @@ public AspNetCoreServerCodegen() { operationModifier.addEnum("abstract", "Make method abstract"); operationModifier.setDefault("virtual"); operationModifier.setOptValue(operationModifier.getDefault()); - addOption(operationModifier.getOpt(), operationModifier.getDescription(), operationModifier.getOptValue()); + cliOptions.add(operationModifier); buildTarget.addEnum("program", "Generate code for a standalone server"); buildTarget.addEnum("library", "Generate code for a server abstract class library"); buildTarget.setDefault("program"); buildTarget.setOptValue(buildTarget.getDefault()); - addOption(buildTarget.getOpt(), buildTarget.getDescription(), buildTarget.getOptValue()); + cliOptions.add(buildTarget); addSwitch(GENERATE_BODY, "Generates method body.", @@ -366,6 +373,7 @@ public void processOpts() { setIsFramework(); setUseNewtonsoft(); setUseEndpointRouting(); + setNullableReferenceTypes(); supportingFiles.add(new SupportingFile("build.sh.mustache", "", "build.sh")); supportingFiles.add(new SupportingFile("build.bat.mustache", "", "build.bat")); @@ -520,7 +528,7 @@ public String toRegularExpression(String pattern) { @Override public String getNullableType(Schema p, String type) { if (languageSpecificPrimitives.contains(type)) { - if (isSupportNullable() && ModelUtils.isNullable(p) && nullableType.contains(type)) { + if (isSupportNullable() && ModelUtils.isNullable(p) && (nullableType.contains(type) || nullableReferenceTypes)) { return type + "?"; } else { return type; @@ -592,6 +600,7 @@ private void setModelClassModifier() { private void setBuildTarget() { setCliOption(buildTarget); if ("library".equals(buildTarget.getOptValue())) { + LOGGER.warn("buildTarget is {} so changing default isLibrary to true", buildTarget.getOptValue()); isLibrary = true; projectSdk = SDK_LIB; additionalProperties.put(CLASS_MODIFIER, "abstract"); @@ -636,7 +645,7 @@ private String determineTemplateVersion(String frameworkVersion) { private void setUseSwashbuckle() { if (isLibrary) { - LOGGER.warn("buildTarget is " + buildTarget.getOptValue() + " so changing default isLibrary to false "); + LOGGER.warn("isLibrary is true so changing default useSwashbuckle to false"); useSwashbuckle = false; } else { useSwashbuckle = true; @@ -648,6 +657,19 @@ private void setUseSwashbuckle() { } } + private void setNullableReferenceTypes() { + if (additionalProperties.containsKey(NULLABLE_REFERENCE_TYPES)) { + if (aspnetCoreVersion.getOptValue().startsWith("2.")) { + LOGGER.warn("Nullable annotation are not supported in ASP.NET core version 2. Setting " + NULLABLE_REFERENCE_TYPES + " to false"); + additionalProperties.put(NULLABLE_REFERENCE_TYPES, false); + } else { + nullableReferenceTypes = convertPropertyToBooleanAndWriteBack(NULLABLE_REFERENCE_TYPES); + } + } else { + additionalProperties.put(NULLABLE_REFERENCE_TYPES, nullableReferenceTypes); + } + } + private void setOperationIsAsync() { if (isLibrary) { operationIsAsync = false; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java index ff90d1e30e26..356c6a895b05 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java @@ -681,6 +681,11 @@ public void processOpts() { binRelativePath += "vendor"; additionalProperties.put("binRelativePath", binRelativePath); + if(HTTPCLIENT.equals(getLibrary())) { + supportingFiles.add(new SupportingFile("FileParameter.mustache", clientPackageDir, "FileParameter.cs")); + typeMapping.put("file", "FileParameter"); + } + supportingFiles.add(new SupportingFile("IApiAccessor.mustache", clientPackageDir, "IApiAccessor.cs")); supportingFiles.add(new SupportingFile("Configuration.mustache", clientPackageDir, "Configuration.cs")); supportingFiles.add(new SupportingFile("ApiClient.mustache", clientPackageDir, "ApiClient.cs")); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java index bf49fd425e05..cb21ea5a6de7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java @@ -128,6 +128,7 @@ public CppPistacheServerCodegen() { typeMapping.put("boolean", "bool"); typeMapping.put("array", "std::vector"); typeMapping.put("map", "std::map"); + typeMapping.put("set", "std::vector"); typeMapping.put("file", "std::string"); typeMapping.put("object", "Object"); typeMapping.put("binary", "std::string"); @@ -400,7 +401,11 @@ public String toDefaultValue(Schema p) { } else if (!StringUtils.isEmpty(p.get$ref())) { // model return toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "()"; } else if (ModelUtils.isStringSchema(p)) { - return "\"\""; + if (p.getDefault() == null) { + return "\"\""; + } else { + return "\"" + p.getDefault().toString() + "\""; + } } return ""; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5AbstractCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtAbstractCodegen.java similarity index 98% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5AbstractCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtAbstractCodegen.java index af8323258da5..2dff94f15c36 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5AbstractCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtAbstractCodegen.java @@ -13,8 +13,8 @@ import java.io.File; import java.util.*; -public class CppQt5AbstractCodegen extends AbstractCppCodegen implements CodegenConfig { - private final Logger LOGGER = LoggerFactory.getLogger(CppQt5AbstractCodegen.class); +public class CppQtAbstractCodegen extends AbstractCppCodegen implements CodegenConfig { + private final Logger LOGGER = LoggerFactory.getLogger(CppQtAbstractCodegen.class); protected final String PREFIX = "OAI"; protected String apiVersion = "1.0.0"; protected static final String CPP_NAMESPACE = "cppNamespace"; @@ -29,7 +29,7 @@ public class CppQt5AbstractCodegen extends AbstractCppCodegen implements Codegen protected Set nonFrameworkPrimitives = new HashSet(); - public CppQt5AbstractCodegen() { + public CppQtAbstractCodegen() { super(); modifyFeatureSet(features -> features diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtClientCodegen.java similarity index 89% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5ClientCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtClientCodegen.java index 00e489ee6ee7..e93ae32541a8 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5ClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtClientCodegen.java @@ -29,28 +29,28 @@ import static org.openapitools.codegen.utils.StringUtils.*; -public class CppQt5ClientCodegen extends CppQt5AbstractCodegen implements CodegenConfig { +public class CppQtClientCodegen extends CppQtAbstractCodegen implements CodegenConfig { public static final String OPTIONAL_PROJECT_FILE_DESC = "Generate client.pri."; // source folder where to write the files protected String sourceFolder = "client"; protected boolean optionalProjectFileFlag = true; - public CppQt5ClientCodegen() { + public CppQtClientCodegen() { super(); modifyFeatureSet(features -> features - .includeDocumentationFeatures(DocumentationFeature.Readme) - .includeGlobalFeatures(GlobalFeature.ParameterizedServer) - .includeGlobalFeatures(GlobalFeature.MultiServer) - .includeSecurityFeatures(SecurityFeature.BasicAuth) - .includeSecurityFeatures(SecurityFeature.ApiKey) - .includeSecurityFeatures(SecurityFeature.BearerToken) - .includeGlobalFeatures(GlobalFeature.ParameterStyling) + .includeDocumentationFeatures(DocumentationFeature.Readme) + .includeGlobalFeatures(GlobalFeature.ParameterizedServer) + .includeGlobalFeatures(GlobalFeature.MultiServer) + .includeSecurityFeatures(SecurityFeature.BasicAuth) + .includeSecurityFeatures(SecurityFeature.ApiKey) + .includeSecurityFeatures(SecurityFeature.BearerToken) + .includeGlobalFeatures(GlobalFeature.ParameterStyling) ); // set the output folder here - outputFolder = "generated-code/qt5cpp"; + outputFolder = "generated-code/cpp-qt-client"; /* * Models. You can write model files using the modelTemplateFiles map. @@ -83,7 +83,7 @@ public CppQt5ClientCodegen() { * Template Location. This is the location which templates will be read from. The generator * will use the resource stream to attempt to read the templates. */ - embeddedTemplateDir = templateDir = "cpp-qt5-client"; + embeddedTemplateDir = templateDir = "cpp-qt-client"; addSwitch(CodegenConstants.OPTIONAL_PROJECT_FILE, OPTIONAL_PROJECT_FILE_DESC, this.optionalProjectFileFlag); supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h")); @@ -94,9 +94,9 @@ public CppQt5ClientCodegen() { supportingFiles.add(new SupportingFile("HttpFileElement.cpp.mustache", sourceFolder, PREFIX + "HttpFileElement.cpp")); supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h")); supportingFiles.add(new SupportingFile("enum.mustache", sourceFolder, PREFIX + "Enum.h")); - supportingFiles.add(new SupportingFile("ServerConfiguration.mustache", sourceFolder, PREFIX +"ServerConfiguration.h")); - supportingFiles.add(new SupportingFile("ServerVariable.mustache", sourceFolder, PREFIX +"ServerVariable.h")); - supportingFiles.add(new SupportingFile("README.mustache", "","README.md")); + supportingFiles.add(new SupportingFile("ServerConfiguration.mustache", sourceFolder, PREFIX + "ServerConfiguration.h")); + supportingFiles.add(new SupportingFile("ServerVariable.mustache", sourceFolder, PREFIX + "ServerVariable.h")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("CMakeLists.txt.mustache", sourceFolder, "CMakeLists.txt")); if (optionalProjectFileFlag) { supportingFiles.add(new SupportingFile("Project.mustache", sourceFolder, "client.pri")); @@ -127,7 +127,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("enum.mustache", sourceFolder, modelNamePrefix + "Enum.h")); supportingFiles.add(new SupportingFile("ServerConfiguration.mustache", sourceFolder, modelNamePrefix + "ServerConfiguration.h")); supportingFiles.add(new SupportingFile("ServerVariable.mustache", sourceFolder, modelNamePrefix + "ServerVariable.h")); - supportingFiles.add(new SupportingFile("README.mustache", "","README.md")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("CMakeLists.txt.mustache", sourceFolder, "CMakeLists.txt")); @@ -158,7 +158,7 @@ public CodegenType getTag() { */ @Override public String getName() { - return "cpp-qt5-client"; + return "cpp-qt-client"; } /** @@ -169,7 +169,7 @@ public String getName() { */ @Override public String getHelp() { - return "Generates a Qt5 C++ client library."; + return "Generates a Qt C++ client library."; } /** diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5QHttpEngineServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtQHttpEngineServerCodegen.java similarity index 95% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5QHttpEngineServerCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtQHttpEngineServerCodegen.java index 7c35de11720f..938211f67870 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5QHttpEngineServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtQHttpEngineServerCodegen.java @@ -26,7 +26,7 @@ import static org.openapitools.codegen.utils.StringUtils.camelize; -public class CppQt5QHttpEngineServerCodegen extends CppQt5AbstractCodegen implements CodegenConfig { +public class CppQtQHttpEngineServerCodegen extends CppQtAbstractCodegen implements CodegenConfig { protected final String SRC_DIR = "/src"; protected final String MODEL_DIR = "/src/models"; @@ -36,13 +36,13 @@ public class CppQt5QHttpEngineServerCodegen extends CppQt5AbstractCodegen implem // source folder where to write the files protected String sourceFolder = "server"; - public CppQt5QHttpEngineServerCodegen() { + public CppQtQHttpEngineServerCodegen() { super(); modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); // set the output folder here - outputFolder = "generated-code/cpp-qt5-qhttpengine-server"; + outputFolder = "generated-code/cpp-qt-qhttpengine-server"; /* * Models. You can write model files using the modelTemplateFiles map. @@ -83,7 +83,7 @@ public CppQt5QHttpEngineServerCodegen() { * Template Location. This is the location which templates will be read from. The generator * will use the resource stream to attempt to read the templates. */ - embeddedTemplateDir = templateDir = "cpp-qt5-qhttpengine-server"; + embeddedTemplateDir = templateDir = "cpp-qt-qhttpengine-server"; supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder + MODEL_DIR, PREFIX + "Helpers.h")); supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder + MODEL_DIR, PREFIX + "Helpers.cpp")); @@ -154,7 +154,7 @@ public CodegenType getTag() { */ @Override public String getName() { - return "cpp-qt5-qhttpengine-server"; + return "cpp-qt-qhttpengine-server"; } /** @@ -165,7 +165,7 @@ public String getName() { */ @Override public String getHelp() { - return "Generates a Qt5 C++ Server using the QHTTPEngine HTTP Library."; + return "Generates a Qt C++ Server using the QHTTPEngine HTTP Library."; } /** diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTinyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTinyClientCodegen.java new file mode 100644 index 000000000000..d339555a86ef --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTinyClientCodegen.java @@ -0,0 +1,343 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.languages; + +import org.openapitools.codegen.*; +import io.swagger.v3.oas.models.media.Schema; + +import io.swagger.v3.parser.util.SchemaTypeUtil; +import org.openapitools.codegen.meta.features.*; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; +import org.openapitools.codegen.utils.ModelUtils; + +import java.io.File; +import java.util.*; + +import org.apache.commons.lang3.StringUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CppTinyClientCodegen extends AbstractCppCodegen implements CodegenConfig { + public static final String PROJECT_NAME = "TinyClient"; + + static final Logger LOGGER = LoggerFactory.getLogger(CppTinyClientCodegen.class); + + public static final String MICROCONTROLLER = "controller"; + public static final String rootFolder = ""; + protected String controller = "esp32"; + + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + /** + * Configures a friendly name for the generator. This will be used by the + * generator to select the library with the -g flag. + * + * @return the friendly name for the generator + */ + public String getName() { + return "cpp-tiny"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with + * help tips, parameters here + * + * @return A string value for the help message + */ + public String getHelp() { + return "Generates a C++ Arduino REST API client."; + } + + public void addControllerToAdditionalProperties() { + Map supportedControllers = new HashMap() {{ + put("esp32", "isESP32"); + put("esp8266", "isESP8266"); + }}; + if (supportedControllers.containsKey(controller)) { + additionalProperties.put(supportedControllers.get(controller), true); + } else { + //String msg = String.format("The specified controller: %s is not supported.\nSupported controllers are: %s", + // controller, + // supportedControllers.keySet()); + throw new UnsupportedOperationException("Supported controllers are: ESP32, ESP8266"); + } + } + + public CppTinyClientCodegen() { + super(); + + modifyFeatureSet(feature -> feature + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling, + GlobalFeature.MultiServer) + .excludeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) + .excludeParameterFeatures( + ParameterFeature.Cookie, + ParameterFeature.Header, + ParameterFeature.FormUnencoded, + ParameterFeature.FormMultipart, + ParameterFeature.Query + ) + .excludeDataTypeFeatures( + DataTypeFeature.Enum, + DataTypeFeature.Maps, + DataTypeFeature.MapOfCollectionOfEnum, + DataTypeFeature.MapOfCollectionOfModel, + DataTypeFeature.MapOfCollectionOfPrimitives, + DataTypeFeature.MapOfEnum, + DataTypeFeature.MapOfModel + + ) + .excludeWireFormatFeatures( + WireFormatFeature.XML, + WireFormatFeature.PROTOBUF, + WireFormatFeature.Custom + ) + .includeDocumentationFeatures( + DocumentationFeature.Readme + )); + + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.BETA) + .build(); + + outputFolder = "generated-code" + File.separator + "cpp-tiny"; + embeddedTemplateDir = templateDir = "cpp-tiny"; + + String libFolder = "lib"; + // MODELS + modelPackage = libFolder + File.separator + "Models"; + modelTemplateFiles.put("model-header.mustache", ".h"); + modelTemplateFiles.put("model-body.mustache", ".cpp"); + + // MODELS: Helpers + supportingFiles.add(new SupportingFile("helpers-header.mustache", modelPackage, "Helpers.h")); + supportingFiles.add(new SupportingFile("helpers-body.mustache", modelPackage, "Helpers.cpp")); + + // MODELS: TESTS + testPackage = libFolder + File.separator + "TestFiles"; + modelTestTemplateFiles.put("unit-test-model.mustache", ".cpp"); + supportingFiles.add(new SupportingFile("run-tests.mustache", "test", "RunTests.cpp")); + + // SERVICES + apiPackage = CppTinyClientCodegen.libFolder + File.separator + "service"; + apiTemplateFiles.put("service/api-header.mustache".replace('/', File.separatorChar), ".h"); + apiTemplateFiles.put("service/api-body.mustache".replace('/', File.separatorChar), ".cpp"); + + // SERVICES: Helpers + supportingFiles.add(new SupportingFile("service/Response.h.mustache", serviceFolder, "Response.h")); + supportingFiles.add(new SupportingFile("service/AbstractService.h.mustache", serviceFolder, "AbstractService.h")); + supportingFiles.add(new SupportingFile("service/AbstractService.cpp.mustache", serviceFolder, "AbstractService.cpp")); + + // Main + supportingFiles.add(new SupportingFile("main.mustache", CppTinyClientCodegen.sourceFolder, "main.cpp")); + + // Config files + supportingFiles.add(new SupportingFile("README.mustache", rootFolder, "README.md")); + supportingFiles.add(new SupportingFile("platformio.ini.mustache", rootFolder, "platformio.ini")); + supportingFiles.add(new SupportingFile("root.cert.mustache", rootFolder, "root.cert")); + supportingFiles.add(new SupportingFile("README.mustache", rootFolder, "README.md")); + supportingFiles.add(new SupportingFile("pre_compiling_bourne.py.mustache", rootFolder, "pre_compiling_bourne.py")); + + defaultIncludes = new HashSet( + Arrays.asList( + "bool", + "int", + "long", + "double", + "float") + ); + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "bool", + "int", + "long", + "double", + "float", + "std::string") + ); + + super.typeMapping = new HashMap(); + typeMapping.put("string", "std::string"); + typeMapping.put("integer", "int"); + typeMapping.put("boolean", "bool"); + typeMapping.put("array", "std::list"); + typeMapping.put("DateTime", "std::string"); + + cliOptions.add(new CliOption(MICROCONTROLLER, "name of microcontroller (e.g esp32 or esp8266)"). + defaultValue("esp32")); + + makeTypeMappings(); + + } + + // FilePaths + private static final String sourceFolder = "src"; + private static final String libFolder = "lib"; + private static final String serviceFolder = libFolder + File.separator + "service"; + + @Override + public String getTypeDeclaration(String str) { + return str; + } + + private void makeTypeMappings() { + // Types + String cpp_array_type = "std::list"; + typeMapping = new HashMap<>(); + + typeMapping.put("string", "std::string"); + typeMapping.put("integer", "int"); + typeMapping.put("float", "float"); + typeMapping.put("long", "long"); + typeMapping.put("boolean", "bool"); + typeMapping.put("double", "double"); + typeMapping.put("array", cpp_array_type); + typeMapping.put("number", "long"); + typeMapping.put("binary", "std::string"); + typeMapping.put("password", "std::string"); + typeMapping.put("file", "std::string"); + typeMapping.put("DateTime", "std::string"); + typeMapping.put("Date", "std::string"); + typeMapping.put("UUID", "std::string"); + typeMapping.put("URI", "std::string"); + } + + @Override + public void processOpts() { + super.processOpts(); + // Throw exception if http and esp8266 + + // -- --additional-properties=controller= + if (additionalProperties.containsKey(MICROCONTROLLER)) { + controller = additionalProperties.get(MICROCONTROLLER).toString(); + } + + addControllerToAdditionalProperties(); + + LOGGER.info("Generator targeting the following microcontroller: {}", controller); + } + + @Override + public String toInstantiationType(Schema p) { + if (ModelUtils.isArraySchema(p)) { + return instantiationTypes.get("array"); + } else { + return null; + } + } + + @Override + public String getTypeDeclaration(Schema p) { + String openAPIType = getSchemaType(p); + if (languageSpecificPrimitives.contains(openAPIType)) { + return toModelName(openAPIType); + } else { + return openAPIType + ""; + } + } + + @Override + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); + String type = null; + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); + if (languageSpecificPrimitives.contains(type)) { + return toModelName(type); + } + } else { + type = openAPIType; + } + return toModelName(type); + } + + @Override + public String toModelName(String type) { + if (typeMapping.keySet().contains(type) || + typeMapping.values().contains(type) || + defaultIncludes.contains(type) || + languageSpecificPrimitives.contains(type)) { + return type; + } else { + return Character.toUpperCase(type.charAt(0)) + type.substring(1); + } + } + + @Override + public String toModelImport(String name) { + if (name.equals("std::string")) { + return "#include "; + } else if (name.equals("std::list")) { + return "#include "; + } else if (name.equals("Map")) { + return "#include "; + } + return "#include \"" + name + ".h\""; + } + + @Override + public String toApiImport(String name) { + return super.toApiImport(name); + } + + @Override + public String toVarName(String name) { + String paramName = name.replaceAll("[^a-zA-Z0-9_]", ""); + if (name.length() > 0) { + paramName = Character.toLowerCase(paramName.charAt(0)) + paramName.substring(1); + } + if (isReservedWord(paramName)) { + return escapeReservedWord(paramName); + } + return "" + paramName; + } + + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { + return "bool(false)"; + } else if (ModelUtils.isNumberSchema(p)) { + return "float(0)"; + } else if (ModelUtils.isIntegerSchema(p)) { + if (SchemaTypeUtil.INTEGER64_FORMAT.equals(p.getFormat())) { + return "long(0)"; + } + return "int(0)"; + } else if (ModelUtils.isArraySchema(p)) { + return "std::list"; + } else if (!StringUtils.isEmpty(p.get$ref())) { + return toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "()"; + } else if (ModelUtils.isDateSchema(p) || ModelUtils.isDateTimeSchema(p)) { + return "std::string()"; + } else if (ModelUtils.isStringSchema(p)) { + return "std::string()"; + } + return "null"; + } + + +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java index 23b50b2f7566..517d1023b980 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java @@ -264,7 +264,7 @@ private void appendCollection(StringBuilder sb, CodegenProperty property) { @Override public Map postProcessOperationsWithModels(Map objs, List allModels) { - objs = super.postProcessOperationsWithModels(objs, allModels); + super.postProcessOperationsWithModels(objs, allModels); Map operations = (Map) objs.get("operations"); List operationList = (List) operations.get("operation"); @@ -272,24 +272,8 @@ public Map postProcessOperationsWithModels(Map o Set resultImports = new HashSet<>(); for (CodegenOperation op : operationList) { - op.httpMethod = op.httpMethod.toLowerCase(Locale.ROOT); - boolean isJson = true; //default to JSON - boolean isForm = false; - boolean isMultipart = false; - if (op.consumes != null) { - for (Map consume : op.consumes) { - if (consume.containsKey("mediaType")) { - String type = consume.get("mediaType"); - isJson = type.equalsIgnoreCase("application/json"); - isForm = type.equalsIgnoreCase("application/x-www-form-urlencoded"); - isMultipart = type.equalsIgnoreCase("multipart/form-data"); - break; - } - } - } - for (CodegenParameter param : op.bodyParams) { - if (param.baseType != null && param.baseType.equalsIgnoreCase("Uint8List") && isMultipart) { + if (param.baseType != null && param.baseType.equalsIgnoreCase("Uint8List") && op.isMultipart) { param.baseType = "MultipartFile"; param.dataType = "MultipartFile"; } @@ -303,10 +287,6 @@ public Map postProcessOperationsWithModels(Map o } } - op.vendorExtensions.put("x-is-json", isJson); - op.vendorExtensions.put("x-is-form", isForm); - op.vendorExtensions.put("x-is-multipart", isMultipart); - resultImports.addAll(rewriteImports(op.imports)); if (op.getHasFormParams()) { resultImports.add("package:" + pubName + "/api_util.dart"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java index ee1fbb9d261f..6b7beaeaea2e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java @@ -46,6 +46,7 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { public static final String SERIALIZATION_LIBRARY_BUILT_VALUE = "built_value"; public static final String SERIALIZATION_LIBRARY_DEFAULT = SERIALIZATION_LIBRARY_BUILT_VALUE; + private static final String DIO_IMPORT = "package:dio/dio.dart"; private static final String CLIENT_NAME = "clientName"; private String dateLibrary; @@ -192,6 +193,7 @@ private void configureSerializationLibraryBuiltValue(String srcFolder) { imports.put("BuiltMap", "package:built_collection/built_collection.dart"); imports.put("JsonObject", "package:built_value/json_object.dart"); imports.put("Uint8List", "dart:typed_data"); + imports.put("MultipartFile", DIO_IMPORT); } private void configureDateLibrary(String srcFolder) { @@ -205,13 +207,19 @@ private void configureDateLibrary(String srcFolder) { imports.put("OffsetDate", "package:time_machine/time_machine.dart"); imports.put("OffsetDateTime", "package:time_machine/time_machine.dart"); if (SERIALIZATION_LIBRARY_BUILT_VALUE.equals(library)) { - supportingFiles.add(new SupportingFile("serialization/built_value/local_date_serializer.mustache", srcFolder, "local_date_serializer.dart")); + supportingFiles.add(new SupportingFile("serialization/built_value/offset_date_serializer.mustache", srcFolder, "local_date_serializer.dart")); } break; default: case DATE_LIBRARY_CORE: - // this option uses the dart core classes additionalProperties.put("useDateLibCore", "true"); + if (SERIALIZATION_LIBRARY_BUILT_VALUE.equals(library)) { + typeMapping.put("date", "Date"); + typeMapping.put("Date", "Date"); + importMapping.put("Date", "package:" + pubName + "/src/model/date.dart"); + supportingFiles.add(new SupportingFile("serialization/built_value/date.mustache", srcFolder + File.separator + "model", "date.dart")); + supportingFiles.add(new SupportingFile("serialization/built_value/date_serializer.mustache", srcFolder, "date_serializer.dart")); + } break; } } @@ -251,7 +259,7 @@ public Map postProcessModels(Map objs) { for (Object _mo : models) { Map mo = (Map) _mo; CodegenModel cm = (CodegenModel) mo.get("model"); - cm.imports = rewriteImports(cm.imports); + cm.imports = rewriteImports(cm.imports, true); cm.vendorExtensions.put("x-has-vars", !cm.vars.isEmpty()); } return objs; @@ -296,10 +304,9 @@ private void appendBuiltValueCollection(StringBuilder sb, CodegenProperty proper sb.append(")]"); } - @Override public Map postProcessOperationsWithModels(Map objs, List allModels) { - objs = super.postProcessOperationsWithModels(objs, allModels); + super.postProcessOperationsWithModels(objs, allModels); Map operations = (Map) objs.get("operations"); List operationList = (List) operations.get("operation"); @@ -307,27 +314,15 @@ public Map postProcessOperationsWithModels(Map o Set resultImports = new HashSet<>(); for (CodegenOperation op : operationList) { - op.httpMethod = op.httpMethod.toLowerCase(Locale.ROOT); - boolean isJson = true; //default to JSON - boolean isForm = false; - boolean isMultipart = false; - if (op.consumes != null) { - for (Map consume : op.consumes) { - if (consume.containsKey("mediaType")) { - String type = consume.get("mediaType"); - isJson = type.equalsIgnoreCase("application/json"); - isForm = type.equalsIgnoreCase("application/x-www-form-urlencoded"); - isMultipart = type.equalsIgnoreCase("multipart/form-data"); - break; - } + for (CodegenParameter param : op.allParams) { + if (((op.isMultipart && param.isFormParam) || param.isBodyParam) && (param.isBinary || param.isFile)) { + param.baseType = "MultipartFile"; + param.dataType = "MultipartFile"; + op.imports.add("MultipartFile"); } } for (CodegenParameter param : op.bodyParams) { - if (param.baseType != null && param.baseType.equalsIgnoreCase("Uint8List") && isMultipart) { - param.baseType = "MultipartFile"; - param.dataType = "MultipartFile"; - } if (param.isContainer) { final Map serializer = new HashMap<>(); serializer.put("isArray", param.isArray); @@ -338,11 +333,12 @@ public Map postProcessOperationsWithModels(Map o } } - op.vendorExtensions.put("x-is-json", isJson); - op.vendorExtensions.put("x-is-form", isForm); - op.vendorExtensions.put("x-is-multipart", isMultipart); + if (op.allParams.stream().noneMatch(param -> param.dataType.equals("Uint8List"))) { + // Remove unused imports after processing + op.imports.remove("Uint8List"); + } - resultImports.addAll(rewriteImports(op.imports)); + resultImports.addAll(rewriteImports(op.imports, false)); if (op.getHasFormParams()) { resultImports.add("package:" + pubName + "/src/api_util.dart"); } @@ -363,11 +359,16 @@ public Map postProcessOperationsWithModels(Map o return objs; } - private Set rewriteImports(Set originalImports) { + private Set rewriteImports(Set originalImports, boolean isModel) { Set resultImports = Sets.newHashSet(); for (String modelImport : originalImports) { if (imports.containsKey(modelImport)) { - resultImports.add(imports.get(modelImport)); + String i = imports.get(modelImport); + if (Objects.equals(i, DIO_IMPORT) && !isModel) { + // Don't add imports to operations that are already imported + continue; + } + resultImports.add(i); } else { resultImports.add("package:" + pubName + "/src/model/" + underscore(modelImport) + ".dart"); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpGiraffeServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpGiraffeServerCodegen.java index d8d4f7fa3df3..b62591c1d0e3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpGiraffeServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpGiraffeServerCodegen.java @@ -280,4 +280,17 @@ public Mustache.Compiler processCompiler(Mustache.Compiler compiler) { public String toRegularExpression(String pattern) { return escapeText(pattern); } -} \ No newline at end of file + + @Override + public void postProcess() { + System.out.println("################################################################################"); + System.out.println("# Thanks for using OpenAPI Generator. #"); + System.out.println("# Please consider donation to help us maintain this project \uD83D\uDE4F #"); + System.out.println("# https://opencollective.com/openapi_generator/donate #"); + System.out.println("# #"); + System.out.println("# This generator's contributed by Nick Fisher (https://github.com/nmfisher) #"); + System.out.println("# Please support his work directly via https://paypal.me/nickfisher1984 \uD83D\uDE4F #"); + System.out.println("################################################################################"); + } + +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoEchoServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoEchoServerCodegen.java new file mode 100644 index 000000000000..3bd2a37a5e5b --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoEchoServerCodegen.java @@ -0,0 +1,184 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.languages; + +import org.openapitools.codegen.*; + +import java.io.File; +import java.util.*; + +import org.openapitools.codegen.meta.features.*; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class GoEchoServerCodegen extends AbstractGoCodegen { + static final Logger LOGGER = LoggerFactory.getLogger(GoEchoServerCodegen.class); + + protected String apiVersion = "1.0.0"; + protected int serverPort = 8080; + protected String projectName = "openapi-go-echo-server"; + protected String apiPath = "go"; + + private static final String MODEL_PACKAGE_NAME = "models"; + private static final String API_PACKAGE_NAME = "handlers"; + private static final String OUTPUT_PATH = "generated-code" + File.separator + "go-echo-server"; + + public CodegenType getTag() { + return CodegenType.SERVER; + } + + public String getName() { + return "go-echo-server"; + } + + public String getHelp() { + return "Generates a go-echo server. (Beta)"; + } + + public GoEchoServerCodegen() { + super(); + + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.BETA) + .build(); + + modifyFeatureSet(features -> features + .includeDocumentationFeatures(DocumentationFeature.Readme) + .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) + .securityFeatures(EnumSet.noneOf( + SecurityFeature.class + )) + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling + ) + .excludeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) + .excludeParameterFeatures( + ParameterFeature.Cookie + ) + ); + + outputFolder = OUTPUT_PATH; + modelTemplateFiles.put("model.mustache", ".go"); + setModelPackage(MODEL_PACKAGE_NAME); + apiTemplateFiles.put("api.mustache", ".go"); + embeddedTemplateDir = templateDir = "go-echo-server"; + + /* + * Reserved words. Override this with reserved words specific to your language + */ + setReservedWordsLowerCase( + Arrays.asList( + // data type + "string", "bool", "uint", "uint8", "uint16", "uint32", "uint64", + "int", "int8", "int16", "int32", "int64", "float32", "float64", + "complex64", "complex128", "rune", "byte", "uintptr", + "break", "default", "func", "interface", "select", + "case", "defer", "go", "map", "struct", + "chan", "else", "goto", "package", "switch", + "const", "fallthrough", "if", "range", "type", + "continue", "for", "import", "return", "var", "error", "nil") + // Added "error" as it's used so frequently that it may as well be a keyword + ); + + CliOption optServerPort = new CliOption("serverPort", "The network port the generated server binds to"); + optServerPort.setType("int"); + optServerPort.defaultValue(Integer.toString(serverPort)); + cliOptions.add(optServerPort); + } + + @Override + public Map postProcessOperationsWithModels(Map objs, List allModels) { + objs = super.postProcessOperationsWithModels(objs, allModels); + + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + if (op.path != null) { + op.path = op.path.replaceAll("\\{(.*?)\\}", ":$1"); + } + } + return objs; + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } else { + setPackageName("openapi"); + additionalProperties.put(CodegenConstants.PACKAGE_NAME, this.packageName); + } + + /* + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + if (additionalProperties.containsKey("apiVersion")) { + this.apiVersion = (String) additionalProperties.get("apiVersion"); + } else { + additionalProperties.put("apiVersion", apiVersion); + } + + if (additionalProperties.containsKey("serverPort")) { + this.serverPort = Integer.parseInt((String) additionalProperties.get("serverPort")); + } else { + additionalProperties.put("serverPort", serverPort); + } + + if (additionalProperties.containsKey("apiPath")) { + this.apiPath = (String) additionalProperties.get("apiPath"); + } else { + additionalProperties.put("apiPath", apiPath); + } + + if (additionalProperties.containsKey(CodegenConstants.ENUM_CLASS_PREFIX)) { + setEnumClassPrefix(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.ENUM_CLASS_PREFIX).toString())); + if (enumClassPrefix) { + additionalProperties.put(CodegenConstants.ENUM_CLASS_PREFIX, true); + } + } + + /* + set model and package names, this is mainly used inside the templates. + */ + modelPackage = MODEL_PACKAGE_NAME; + apiPackage = API_PACKAGE_NAME; + + /* + * Supporting Files. You can write single files for the generator with the + * entire object tree available. If the input file has a suffix of `.mustache + * it will be processed by the template engine. Otherwise, it will be copied + */ + supportingFiles.add(new SupportingFile("openapi.mustache", ".docs/api", "openapi.yaml")); + supportingFiles.add(new SupportingFile("hello-world.mustache", "models", "hello-world.go")); + supportingFiles.add(new SupportingFile("go-mod.mustache", "", "go.mod")); + supportingFiles.add(new SupportingFile("handler-container.mustache", "handlers", "container.go")); + supportingFiles.add(new SupportingFile("main.mustache", "", "main.go")); + supportingFiles.add(new SupportingFile("Dockerfile.mustache", "", "Dockerfile")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md") + .doNotOverwrite()); + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java index 17afe550c709..5c9b27ae59d9 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java @@ -17,6 +17,8 @@ package org.openapitools.codegen.languages; +import static java.util.Collections.sort; + import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.CliOption; import org.openapitools.codegen.CodegenConstants; @@ -59,6 +61,10 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { public static final String REQUEST_DATE_CONVERTER = "requestDateConverter"; public static final String COLLECTION_TYPE = "collectionType"; + public static final String MOSHI_CODE_GEN = "moshiCodeGen"; + + public static final String SUPPORT_ANDROID_API_LEVEL_25_AND_BELLOW = "supportAndroidApiLevel25AndBelow"; + protected static final String VENDOR_EXTENSION_BASE_NAME_LITERAL = "x-base-name-literal"; protected String dateLibrary = DateLibrary.JAVA8.value; @@ -202,6 +208,10 @@ public KotlinClientCodegen() { cliOptions.add(CliOption.newBoolean(USE_RX_JAVA2, "Whether to use the RxJava2 adapter with the retrofit2 library.")); cliOptions.add(CliOption.newBoolean(USE_RX_JAVA3, "Whether to use the RxJava3 adapter with the retrofit2 library.")); cliOptions.add(CliOption.newBoolean(USE_COROUTINES, "Whether to use the Coroutines adapter with the retrofit2 library.")); + + cliOptions.add(CliOption.newBoolean(MOSHI_CODE_GEN, "Whether to enable codegen with the Moshi library. Refer to the [official Moshi doc](https://github.com/square/moshi#codegen) for more info.")); + + cliOptions.add(CliOption.newBoolean(SUPPORT_ANDROID_API_LEVEL_25_AND_BELLOW, "[WARNING] This flag will generate code that has a known security vulnerability. It uses `kotlin.io.createTempFile` instead of `java.nio.file.Files.createTempFile` in oder to support Android API level 25 and bellow. For more info, please check the following links https://github.com/OpenAPITools/openapi-generator/security/advisories/GHSA-23x4-m842-fmwf, https://github.com/OpenAPITools/openapi-generator/pull/9284")); } public CodegenType getTag() { @@ -463,6 +473,9 @@ private void addSupportingSerializerAdapters(final String infrastructureFolder) supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateAdapter.kt.mustache", infrastructureFolder, "LocalDateAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache", infrastructureFolder, "LocalDateTimeAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/OffsetDateTimeAdapter.kt.mustache", infrastructureFolder, "OffsetDateTimeAdapter.kt")); + supportingFiles.add(new SupportingFile("jvm-common/infrastructure/BigDecimalAdapter.kt.mustache", infrastructureFolder, "BigDecimalAdapter.kt")); + supportingFiles.add(new SupportingFile("jvm-common/infrastructure/BigIntegerAdapter.kt.mustache", infrastructureFolder, "BigIntegerAdapter.kt")); + supportingFiles.add(new SupportingFile("jvm-common/infrastructure/URIAdapter.kt.mustache", infrastructureFolder, "URIAdapter.kt")); break; case gson: @@ -512,7 +525,6 @@ private void processJVMOkHttpLibrary(final String infrastructureFolder) { setLibrary(JVM_OKHTTP); // jvm specific supporting files - supportingFiles.add(new SupportingFile("infrastructure/ApplicationDelegates.kt.mustache", infrastructureFolder, "ApplicationDelegates.kt")); supportingFiles.add(new SupportingFile("infrastructure/Errors.kt.mustache", infrastructureFolder, "Errors.kt")); supportingFiles.add(new SupportingFile("infrastructure/ResponseExtensions.kt.mustache", infrastructureFolder, "ResponseExtensions.kt")); supportingFiles.add(new SupportingFile("infrastructure/ApiInfrastructureResponse.kt.mustache", infrastructureFolder, "ApiInfrastructureResponse.kt")); @@ -654,6 +666,20 @@ public Map postProcessOperationsWithModels(Map o operation.path = operation.path.substring(1); } + // sorting operation parameters to make sure path params are parsed before query params + if (operation.allParams != null) { + sort(operation.allParams, (one, another) -> { + if (one.isPathParam && another.isQueryParam) { + return -1; + } + if (one.isQueryParam && another.isPathParam){ + return 1; + } + + return 0; + }); + } + // modify the data type of binary form parameters to a more friendly type for multiplatform builds if (MULTIPLATFORM.equals(getLibrary()) && operation.allParams != null) { for (CodegenParameter param : operation.allParams) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java index d4d9902da7f0..0c182417c943 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java @@ -42,15 +42,17 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { private Boolean hstsFeatureEnabled = true; private Boolean corsFeatureEnabled = false; private Boolean compressionFeatureEnabled = true; + private Boolean locationsFeatureEnabled = true; - // This is here to potentially warn the user when an option is not supoprted by the target framework. + // This is here to potentially warn the user when an option is not supported by the target framework. private Map> optionsSupportedPerFramework = new ImmutableMap.Builder>() .put(Constants.KTOR, Arrays.asList( Constants.AUTOMATIC_HEAD_REQUESTS, Constants.CONDITIONAL_HEADERS, Constants.HSTS, Constants.CORS, - Constants.COMPRESSION + Constants.COMPRESSION, + Constants.LOCATIONS )) .build(); @@ -85,6 +87,8 @@ public KotlinServerCodegen() { artifactId = "kotlin-server"; packageName = "org.openapitools.server"; + typeMapping.put("array", "kotlin.collections.List"); + // cliOptions default redefinition need to be updated updateOption(CodegenConstants.ARTIFACT_ID, this.artifactId); updateOption(CodegenConstants.PACKAGE_NAME, this.packageName); @@ -110,6 +114,7 @@ public KotlinServerCodegen() { addSwitch(Constants.HSTS, Constants.HSTS_DESC, getHstsFeatureEnabled()); addSwitch(Constants.CORS, Constants.CORS_DESC, getCorsFeatureEnabled()); addSwitch(Constants.COMPRESSION, Constants.COMPRESSION_DESC, getCompressionFeatureEnabled()); + addSwitch(Constants.LOCATIONS, Constants.LOCATIONS_DESC, getLocationsFeatureEnabled()); } public Boolean getAutoHeadFeatureEnabled() { @@ -156,6 +161,14 @@ public void setHstsFeatureEnabled(Boolean hstsFeatureEnabled) { this.hstsFeatureEnabled = hstsFeatureEnabled; } + public Boolean getLocationsFeatureEnabled() { + return locationsFeatureEnabled; + } + + public void setLocationsFeatureEnabled(Boolean locationsFeatureEnabled) { + this.locationsFeatureEnabled = locationsFeatureEnabled; + } + public String getName() { return "kotlin-server"; } @@ -209,6 +222,12 @@ public void processOpts() { additionalProperties.put(Constants.COMPRESSION, getCompressionFeatureEnabled()); } + if (additionalProperties.containsKey(Constants.LOCATIONS)) { + setLocationsFeatureEnabled(convertPropertyToBooleanAndWriteBack(Constants.LOCATIONS)); + } else { + additionalProperties.put(Constants.LOCATIONS, getLocationsFeatureEnabled()); + } + boolean generateApis = additionalProperties.containsKey(CodegenConstants.GENERATE_APIS) && (Boolean) additionalProperties.get(CodegenConstants.GENERATE_APIS); String packageFolder = (sourceFolder + File.separator + packageName).replace(".", File.separator); String resourcesFolder = "src/main/resources"; // not sure this can be user configurable. @@ -223,7 +242,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("AppMain.kt.mustache", packageFolder, "AppMain.kt")); supportingFiles.add(new SupportingFile("Configuration.kt.mustache", packageFolder, "Configuration.kt")); - if (generateApis) { + if (generateApis && locationsFeatureEnabled) { supportingFiles.add(new SupportingFile("Paths.kt.mustache", packageFolder, "Paths.kt")); } @@ -247,6 +266,8 @@ public static class Constants { public final static String CORS_DESC = "Ktor by default provides an interceptor for implementing proper support for Cross-Origin Resource Sharing (CORS). See enable-cors.org."; public final static String COMPRESSION = "featureCompression"; public final static String COMPRESSION_DESC = "Adds ability to compress outgoing content using gzip, deflate or custom encoder and thus reduce size of the response."; + public final static String LOCATIONS = "featureLocations"; + public final static String LOCATIONS_DESC = "Generates routes in a typed way, for both: constructing URLs and reading the parameters."; } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerDeprecatedCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerDeprecatedCodegen.java new file mode 100644 index 000000000000..84cee1d2aa97 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerDeprecatedCodegen.java @@ -0,0 +1,270 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright 2018 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.languages; + +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; +import org.openapitools.codegen.meta.features.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; + +public class KotlinServerDeprecatedCodegen extends AbstractKotlinCodegen { + + public static final String DEFAULT_LIBRARY = Constants.KTOR; + private final Logger LOGGER = LoggerFactory.getLogger(KotlinServerDeprecatedCodegen.class); + private Boolean autoHeadFeatureEnabled = true; + private Boolean conditionalHeadersFeatureEnabled = false; + private Boolean hstsFeatureEnabled = true; + private Boolean corsFeatureEnabled = false; + private Boolean compressionFeatureEnabled = true; + + // This is here to potentially warn the user when an option is not supported by the target framework. + private Map> optionsSupportedPerFramework = new ImmutableMap.Builder>() + .put(Constants.KTOR, Arrays.asList( + Constants.AUTOMATIC_HEAD_REQUESTS, + Constants.CONDITIONAL_HEADERS, + Constants.HSTS, + Constants.CORS, + Constants.COMPRESSION + )) + .build(); + + /** + * Constructs an instance of `KotlinServerDeprecatedCodegen`. + */ + public KotlinServerDeprecatedCodegen() { + super(); + + modifyFeatureSet(features -> features + .includeDocumentationFeatures(DocumentationFeature.Readme) + .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) + .securityFeatures(EnumSet.of( + SecurityFeature.BasicAuth, + SecurityFeature.ApiKey, + SecurityFeature.OAuth2_Implicit + )) + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling + ) + .excludeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) + .excludeParameterFeatures( + ParameterFeature.Cookie + ) + ); + + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.DEPRECATED) + .build(); + + artifactId = "kotlin-server-deprecated"; + packageName = "org.openapitools.server"; + + // cliOptions default redefinition need to be updated + updateOption(CodegenConstants.ARTIFACT_ID, this.artifactId); + updateOption(CodegenConstants.PACKAGE_NAME, this.packageName); + + outputFolder = "generated-code" + File.separator + "kotlin-server-deprecated"; + modelTemplateFiles.put("model.mustache", ".kt"); + apiTemplateFiles.put("api.mustache", ".kt"); + embeddedTemplateDir = templateDir = "kotlin-server-deprecated"; + apiPackage = packageName + ".apis"; + modelPackage = packageName + ".models"; + + supportedLibraries.put(Constants.KTOR, "ktor framework"); + + // TODO: Configurable server engine. Defaults to netty in build.gradle. + CliOption library = new CliOption(CodegenConstants.LIBRARY, CodegenConstants.LIBRARY_DESC); + library.setDefault(DEFAULT_LIBRARY); + library.setEnum(supportedLibraries); + + cliOptions.add(library); + + addSwitch(Constants.AUTOMATIC_HEAD_REQUESTS, Constants.AUTOMATIC_HEAD_REQUESTS_DESC, getAutoHeadFeatureEnabled()); + addSwitch(Constants.CONDITIONAL_HEADERS, Constants.CONDITIONAL_HEADERS_DESC, getConditionalHeadersFeatureEnabled()); + addSwitch(Constants.HSTS, Constants.HSTS_DESC, getHstsFeatureEnabled()); + addSwitch(Constants.CORS, Constants.CORS_DESC, getCorsFeatureEnabled()); + addSwitch(Constants.COMPRESSION, Constants.COMPRESSION_DESC, getCompressionFeatureEnabled()); + } + + public Boolean getAutoHeadFeatureEnabled() { + return autoHeadFeatureEnabled; + } + + public void setAutoHeadFeatureEnabled(Boolean autoHeadFeatureEnabled) { + this.autoHeadFeatureEnabled = autoHeadFeatureEnabled; + } + + public Boolean getCompressionFeatureEnabled() { + return compressionFeatureEnabled; + } + + public void setCompressionFeatureEnabled(Boolean compressionFeatureEnabled) { + this.compressionFeatureEnabled = compressionFeatureEnabled; + } + + public Boolean getConditionalHeadersFeatureEnabled() { + return conditionalHeadersFeatureEnabled; + } + + public void setConditionalHeadersFeatureEnabled(Boolean conditionalHeadersFeatureEnabled) { + this.conditionalHeadersFeatureEnabled = conditionalHeadersFeatureEnabled; + } + + public Boolean getCorsFeatureEnabled() { + return corsFeatureEnabled; + } + + public void setCorsFeatureEnabled(Boolean corsFeatureEnabled) { + this.corsFeatureEnabled = corsFeatureEnabled; + } + + public String getHelp() { + return "Generates a Kotlin server (Ktor v1.1.3). IMPORTANT: this generator has been deprecated." + + " Please migrate to `kotlin-server` which supports Ktor v1.5.2+."; + } + + public Boolean getHstsFeatureEnabled() { + return hstsFeatureEnabled; + } + + public void setHstsFeatureEnabled(Boolean hstsFeatureEnabled) { + this.hstsFeatureEnabled = hstsFeatureEnabled; + } + + public String getName() { + return "kotlin-server-deprecated"; + } + + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(CodegenConstants.LIBRARY)) { + this.setLibrary((String) additionalProperties.get(CodegenConstants.LIBRARY)); + } + + // set default library to "ktor" + if (StringUtils.isEmpty(library)) { + this.setLibrary(DEFAULT_LIBRARY); + additionalProperties.put(CodegenConstants.LIBRARY, DEFAULT_LIBRARY); + LOGGER.info("`library` option is empty. Default to " + DEFAULT_LIBRARY); + } + + if (additionalProperties.containsKey(Constants.AUTOMATIC_HEAD_REQUESTS)) { + setAutoHeadFeatureEnabled(convertPropertyToBooleanAndWriteBack(Constants.AUTOMATIC_HEAD_REQUESTS)); + } else { + additionalProperties.put(Constants.AUTOMATIC_HEAD_REQUESTS, getAutoHeadFeatureEnabled()); + } + + if (additionalProperties.containsKey(Constants.CONDITIONAL_HEADERS)) { + setConditionalHeadersFeatureEnabled(convertPropertyToBooleanAndWriteBack(Constants.CONDITIONAL_HEADERS)); + } else { + additionalProperties.put(Constants.CONDITIONAL_HEADERS, getConditionalHeadersFeatureEnabled()); + } + + if (additionalProperties.containsKey(Constants.HSTS)) { + setHstsFeatureEnabled(convertPropertyToBooleanAndWriteBack(Constants.HSTS)); + } else { + additionalProperties.put(Constants.HSTS, getHstsFeatureEnabled()); + } + + if (additionalProperties.containsKey(Constants.CORS)) { + setCorsFeatureEnabled(convertPropertyToBooleanAndWriteBack(Constants.CORS)); + } else { + additionalProperties.put(Constants.CORS, getCorsFeatureEnabled()); + } + + if (additionalProperties.containsKey(Constants.COMPRESSION)) { + setCompressionFeatureEnabled(convertPropertyToBooleanAndWriteBack(Constants.COMPRESSION)); + } else { + additionalProperties.put(Constants.COMPRESSION, getCompressionFeatureEnabled()); + } + + boolean generateApis = additionalProperties.containsKey(CodegenConstants.GENERATE_APIS) && (Boolean) additionalProperties.get(CodegenConstants.GENERATE_APIS); + String packageFolder = (sourceFolder + File.separator + packageName).replace(".", File.separator); + String resourcesFolder = "src/main/resources"; // not sure this can be user configurable. + + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("Dockerfile.mustache", "", "Dockerfile")); + + supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); + supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); + supportingFiles.add(new SupportingFile("gradle.properties", "", "gradle.properties")); + + supportingFiles.add(new SupportingFile("AppMain.kt.mustache", packageFolder, "AppMain.kt")); + supportingFiles.add(new SupportingFile("Configuration.kt.mustache", packageFolder, "Configuration.kt")); + + if (generateApis) { + supportingFiles.add(new SupportingFile("Paths.kt.mustache", packageFolder, "Paths.kt")); + } + + supportingFiles.add(new SupportingFile("application.conf.mustache", resourcesFolder, "application.conf")); + supportingFiles.add(new SupportingFile("logback.xml", resourcesFolder, "logback.xml")); + + final String infrastructureFolder = (sourceFolder + File.separator + packageName + File.separator + "infrastructure").replace(".", File.separator); + + supportingFiles.add(new SupportingFile("ApiKeyAuth.kt.mustache", infrastructureFolder, "ApiKeyAuth.kt")); + } + + public static class Constants { + public final static String KTOR = "ktor"; + public final static String AUTOMATIC_HEAD_REQUESTS = "featureAutoHead"; + public final static String AUTOMATIC_HEAD_REQUESTS_DESC = "Automatically provide responses to HEAD requests for existing routes that have the GET verb defined."; + public final static String CONDITIONAL_HEADERS = "featureConditionalHeaders"; + public final static String CONDITIONAL_HEADERS_DESC = "Avoid sending content if client already has same content, by checking ETag or LastModified properties."; + public final static String HSTS = "featureHSTS"; + public final static String HSTS_DESC = "Avoid sending content if client already has same content, by checking ETag or LastModified properties."; + public final static String CORS = "featureCORS"; + public final static String CORS_DESC = "Ktor by default provides an interceptor for implementing proper support for Cross-Origin Resource Sharing (CORS). See enable-cors.org."; + public final static String COMPRESSION = "featureCompression"; + public final static String COMPRESSION_DESC = "Adds ability to compress outgoing content using gzip, deflate or custom encoder and thus reduce size of the response."; + } + + @Override + public void postProcess() { + System.out.println("################################################################################"); + System.out.println("# Thanks for using OpenAPI Generator. #"); + System.out.println("# Please consider donation to help us maintain this project \uD83D\uDE4F #"); + System.out.println("# https://opencollective.com/openapi_generator/donate #"); + System.out.println("# #"); + System.out.println("# This generator's contributed by Jim Schubert (https://github.com/jimschubert)#"); + System.out.println("# Please support his work directly via https://patreon.com/jimschubert \uD83D\uDE4F #"); + System.out.println("################################################################################"); + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java index cf3c64b03383..cdaae2afe679 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java @@ -540,8 +540,10 @@ public Map postProcessModelsEnum(Map objs) { .filter(cm -> Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) .forEach(cm -> { cm.imports.add(importMapping.get("JsonValue")); + cm.imports.add(importMapping.get("JsonProperty")); Map item = new HashMap<>(); item.put("import", importMapping.get("JsonValue")); + item.put("import", importMapping.get("JsonProperty")); imports.add(item); }); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NimClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NimClientCodegen.java index 02e4f1b701c2..ff07db2ede8f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NimClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NimClientCodegen.java @@ -31,6 +31,8 @@ import java.io.File; import java.util.*; +import static org.openapitools.codegen.utils.StringUtils.camelize; + public class NimClientCodegen extends DefaultCodegen implements CodegenConfig { final Logger LOGGER = LoggerFactory.getLogger(NimClientCodegen.class); @@ -297,14 +299,32 @@ public String getTypeDeclaration(Schema p) { @Override public String toVarName(String name) { - if (isReservedWord(name)) { - name = escapeReservedWord(name); + // sanitize name + name = sanitizeName(name, "\\W-[\\$]"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + if ("_".equals(name)) { + name = "_u"; } + // numbers are not allowed at the beginning if (name.matches("^\\d.*")) { name = "`" + name + "`"; } + // if it's all uppper case, do nothing + if (name.matches("^[A-Z0-9_]*$")) { + return name; + } + + // camelize (lower first character) the variable name + // pet_id => petId + name = camelize(name, true); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name)) { + name = escapeReservedWord(name); + } + return name; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpMezzioPathHandlerServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpMezzioPathHandlerServerCodegen.java index 658537e414b2..529c5a27e217 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpMezzioPathHandlerServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpMezzioPathHandlerServerCodegen.java @@ -21,9 +21,13 @@ import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.PathItem; import io.swagger.v3.oas.models.PathItem.HttpMethod; +import io.swagger.v3.oas.models.Paths; import io.swagger.v3.oas.models.media.*; import io.swagger.v3.oas.models.parameters.Parameter; import io.swagger.v3.oas.models.parameters.QueryParameter; +import io.swagger.v3.oas.models.parameters.RequestBody; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.responses.ApiResponses; import org.openapitools.codegen.*; import org.openapitools.codegen.meta.features.*; import org.openapitools.codegen.utils.ModelUtils; @@ -35,12 +39,17 @@ public class PhpMezzioPathHandlerServerCodegen extends AbstractPhpCodegen { private final Logger LOGGER = LoggerFactory.getLogger(PhpMezzioPathHandlerServerCodegen.class); - - // TODO: Rename to x- prefixed vendor extensions, per specification. + // Custom generator option names + public static final String OPT_MODERN = "modern"; + // Internal vendor extension names for extra template data that should not be set in specification public static final String VEN_FROM_QUERY = "internal.ze-ph.fromQuery"; public static final String VEN_COLLECTION_FORMAT = "internal.ze-ph.collectionFormat"; public static final String VEN_QUERY_DATA_TYPE = "internal.ze-ph.queryDataType"; public static final String VEN_HAS_QUERY_DATA = "internal.ze-ph.hasQueryData"; + public static final String VEN_FROM_CONTAINER = "internal.ze-ph.fromContainer"; + public static final String VEN_CONTAINER_DATA_TYPE = "internal.ze-ph.containerDataType"; + + private boolean useModernSyntax = false; @Override public CodegenType getTag() { @@ -85,6 +94,8 @@ public PhpMezzioPathHandlerServerCodegen() { modelDirName = "DTO"; apiPackage = invokerPackage + "\\" + apiDirName; modelPackage = invokerPackage + "\\" + modelDirName; + //"Api" classes have dedicated namespace so there is no need to add non-empty suffix by default + apiNameSuffix = ""; apiTestTemplateFiles.clear(); modelTestTemplateFiles.clear(); @@ -103,6 +114,17 @@ public PhpMezzioPathHandlerServerCodegen() { supportingFiles.add(new SupportingFile("InternalServerError.php.mustache", srcBasePath + File.separator + "Middleware", "InternalServerError.php")); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, "1.0.0"); + //Register custom CLI options + addSwitch(OPT_MODERN, "use modern language features (generated code will require PHP 8.0)", useModernSyntax); + } + + @Override + public void processOpts() { + super.processOpts(); + if (additionalProperties.containsKey(OPT_MODERN)) { + embeddedTemplateDir = templateDir = "php-mezzio-ph-modern"; + useModernSyntax = true; + } } /** @@ -136,29 +158,31 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera } } - /** - * Return the file name of the Api Test - * - * @param name the file name of the Api - * @return the file name of the Api - */ @Override - public String toApiFilename(String name) { - return toApiName(name); + public String toApiName(String name) { + return super.toApiName(toModelName(name)); } - /** - * Output the API (class) name (capitalized) ending with "Api" - * Return DefaultApi if name is empty - * - * @param name the name of the Api - * @return capitalized Api name ending with "Api" - */ @Override - public String toApiName(String name) { - //Remove } - name = name.replaceAll("[\\}]", ""); - return super.toModelName(name); + public String getTypeDeclaration(Schema p) { + String result; + Map extensions = p.getExtensions(); + if ((extensions != null) && extensions.containsKey(VEN_CONTAINER_DATA_TYPE)) { + result = (String) extensions.get(VEN_CONTAINER_DATA_TYPE); + } else if (useModernSyntax && (ModelUtils.isArraySchema(p) || ModelUtils.isMapSchema(p))) { + result = "array"; + } else { + result = super.getTypeDeclaration(p); + } + return result; + } + + @Override + public void preprocessOpenAPI(OpenAPI openAPI) { + super.preprocessOpenAPI(openAPI); + + generateParameterSchemas(openAPI); + generateContainerSchemas(openAPI); } /** @@ -166,10 +190,7 @@ public String toApiName(String name) { * * @param openAPI OpenAPI object */ - @Override - public void preprocessOpenAPI(OpenAPI openAPI) { - super.preprocessOpenAPI(openAPI); - + protected void generateParameterSchemas(OpenAPI openAPI) { Map paths = openAPI.getPaths(); if (paths != null) { for (String pathname : paths.keySet()) { @@ -178,34 +199,34 @@ public void preprocessOpenAPI(OpenAPI openAPI) { if (operationMap != null) { for (HttpMethod method : operationMap.keySet()) { Operation operation = operationMap.get(method); - Map schemas = new HashMap<>(); + Map propertySchemas = new HashMap<>(); if (operation == null || operation.getParameters() == null) { continue; } List requiredProperties = new ArrayList<>(); for (Parameter parameter : operation.getParameters()) { - Schema schema = convertParameterToSchema(parameter); - if (schema != null) { - schemas.put(schema.getName(), schema); - if (Boolean.TRUE.equals(parameter.getRequired())) { - requiredProperties.add(schema.getName()); + Parameter referencedParameter = ModelUtils.getReferencedParameter(openAPI, parameter); + Schema propertySchema = convertParameterToSchema(openAPI, referencedParameter); + if (propertySchema != null) { + propertySchemas.put(propertySchema.getName(), propertySchema); + if (Boolean.TRUE.equals(referencedParameter.getRequired())) { + requiredProperties.add(propertySchema.getName()); } } } - if (!schemas.isEmpty()) { - ObjectSchema model = new ObjectSchema(); + if (!propertySchemas.isEmpty()) { + ObjectSchema schema = new ObjectSchema(); String operationId = getOrGenerateOperationId(operation, pathname, method.name()); - model.setDescription("Query parameters for " + operationId); - model.setProperties(schemas); - model.setRequired(requiredProperties); - //Add internal extension directly, because addExtension filters extension names - addInternalExtensionToSchema(model, VEN_FROM_QUERY, Boolean.TRUE); - String definitionName = generateUniqueDefinitionName(operationId + "QueryData", openAPI); - openAPI.getComponents().addSchemas(definitionName, model); - String definitionModel = "\\" + modelPackage + "\\" + toModelName(definitionName); - addInternalExtensionToOperation(operation, VEN_QUERY_DATA_TYPE, definitionModel); + schema.setDescription("Query parameters for " + operationId); + schema.setProperties(propertySchemas); + schema.setRequired(requiredProperties); + addInternalExtensionToSchema(schema, VEN_FROM_QUERY, Boolean.TRUE); + String schemaName = generateUniqueSchemaName(openAPI, operationId + "QueryData"); + openAPI.getComponents().addSchemas(schemaName, schema); + String schemaDataType = getTypeDeclaration(toModelName(schemaName)); + addInternalExtensionToOperation(operation, VEN_QUERY_DATA_TYPE, schemaDataType); addInternalExtensionToOperation(operation, VEN_HAS_QUERY_DATA, Boolean.TRUE); } } @@ -214,17 +235,18 @@ public void preprocessOpenAPI(OpenAPI openAPI) { } } - protected Schema convertParameterToSchema(Parameter parameter) { + protected Schema convertParameterToSchema(OpenAPI openAPI, Parameter parameter) { Schema property = null; if (parameter instanceof QueryParameter) { QueryParameter queryParameter = (QueryParameter) parameter; + Schema parameterSchema = ModelUtils.getReferencedSchema(openAPI, queryParameter.getSchema()); // array - if (ModelUtils.isArraySchema(queryParameter.getSchema())) { - Schema inner = ((ArraySchema) queryParameter.getSchema()).getItems(); + if (ModelUtils.isArraySchema(parameterSchema)) { + Schema itemSchema = ((ArraySchema) parameterSchema).getItems(); ArraySchema arraySchema = new ArraySchema(); - arraySchema.setMinItems(queryParameter.getSchema().getMinItems()); - arraySchema.setMaxItems(queryParameter.getSchema().getMaxItems()); - arraySchema.setItems(inner); + arraySchema.setMinItems(parameterSchema.getMinItems()); + arraySchema.setMaxItems(parameterSchema.getMaxItems()); + arraySchema.setItems(itemSchema); String collectionFormat = getCollectionFormat(queryParameter); if (collectionFormat == null) { collectionFormat = "csv"; @@ -232,25 +254,25 @@ protected Schema convertParameterToSchema(Parameter parameter) { addInternalExtensionToSchema(arraySchema, VEN_COLLECTION_FORMAT, collectionFormat); property = arraySchema; } else { // non-array e.g. string, integer - switch (queryParameter.getSchema().getType()) { + switch (parameterSchema.getType()) { case "string": StringSchema stringSchema = new StringSchema(); - stringSchema.setMinLength(queryParameter.getSchema().getMinLength()); - stringSchema.setMaxLength(queryParameter.getSchema().getMaxLength()); - stringSchema.setPattern(queryParameter.getSchema().getPattern()); - stringSchema.setEnum(queryParameter.getSchema().getEnum()); + stringSchema.setMinLength(parameterSchema.getMinLength()); + stringSchema.setMaxLength(parameterSchema.getMaxLength()); + stringSchema.setPattern(parameterSchema.getPattern()); + stringSchema.setEnum(parameterSchema.getEnum()); property = stringSchema; break; case "integer": IntegerSchema integerSchema = new IntegerSchema(); - integerSchema.setMinimum(queryParameter.getSchema().getMinimum()); - integerSchema.setMaximum(queryParameter.getSchema().getMaximum()); + integerSchema.setMinimum(parameterSchema.getMinimum()); + integerSchema.setMaximum(parameterSchema.getMaximum()); property = integerSchema; break; case "number": NumberSchema floatSchema = new NumberSchema(); - floatSchema.setMinimum(queryParameter.getSchema().getMinimum()); - floatSchema.setMaximum(queryParameter.getSchema().getMaximum()); + floatSchema.setMinimum(parameterSchema.getMinimum()); + floatSchema.setMaximum(parameterSchema.getMaximum()); property = floatSchema; break; case "boolean": @@ -264,6 +286,7 @@ protected Schema convertParameterToSchema(Parameter parameter) { break; } } + if (property != null) { property.setName(queryParameter.getName()); property.setDescription(queryParameter.getDescription()); @@ -289,7 +312,7 @@ protected void addInternalExtensionToOperation(Operation operation, String name, operation.getExtensions().put(name, value); } - protected String generateUniqueDefinitionName(String name, OpenAPI openAPI) { + protected String generateUniqueSchemaName(OpenAPI openAPI, String name) { String result = name; if (openAPI.getComponents().getSchemas() != null) { int count = 1; @@ -301,6 +324,90 @@ protected String generateUniqueDefinitionName(String name, OpenAPI openAPI) { return result; } + /** + * Generate additional model definitions for containers in whole specification + * + * @param openAPI OpenAPI object + */ + protected void generateContainerSchemas(OpenAPI openAPI) { + Paths paths = openAPI.getPaths(); + for (String pathName : paths.keySet()) { + for (Operation operation : paths.get(pathName).readOperations()) { + List parameters = operation.getParameters(); + if (parameters != null) { + for (Parameter parameter : parameters) { + generateContainerSchemas(openAPI, ModelUtils.getReferencedParameter(openAPI, parameter).getSchema()); + } + } + RequestBody requestBody = ModelUtils.getReferencedRequestBody(openAPI, operation.getRequestBody()); + if (requestBody != null) { + Content requestBodyContent = requestBody.getContent(); + if (requestBodyContent != null) { + for (String mediaTypeName : requestBodyContent.keySet()) { + generateContainerSchemas(openAPI, requestBodyContent.get(mediaTypeName).getSchema()); + } + } + } + ApiResponses responses = operation.getResponses(); + for (String responseCode : responses.keySet()) { + ApiResponse response = ModelUtils.getReferencedApiResponse(openAPI, responses.get(responseCode)); + Content responseContent = response.getContent(); + if (responseContent != null) { + for (String mediaTypeName : responseContent.keySet()) { + generateContainerSchemas(openAPI, responseContent.get(mediaTypeName).getSchema()); + } + } + } + } + } + } + + /** + * Generate additional model definitions for containers in specified schema + * + * @param openAPI OpenAPI object + * @param schema OAS schema to process + */ + protected void generateContainerSchemas(OpenAPI openAPI, Schema schema) { + if (schema != null) { + //Dereference schema + schema = ModelUtils.getReferencedSchema(openAPI, schema); + Boolean isContainer = Boolean.FALSE; + + if (ModelUtils.isObjectSchema(schema)) { + //Recursively process all schemas of object properties + Map properties = schema.getProperties(); + if (properties != null) { + for (String propertyName: properties.keySet()) { + generateContainerSchemas(openAPI, properties.get(propertyName)); + } + } + } else if (ModelUtils.isArraySchema(schema)) { + //Recursively process schema of array items + generateContainerSchemas(openAPI, ((ArraySchema) schema).getItems()); + isContainer = Boolean.TRUE; + } else if (ModelUtils.isMapSchema(schema)) { + //Recursively process schema of map items + Object itemSchema = schema.getAdditionalProperties(); + if (itemSchema instanceof Schema) { + generateContainerSchemas(openAPI, (Schema) itemSchema); + } + isContainer = Boolean.TRUE; + } + + if (isContainer) { + //Generate special component schema for container + String containerSchemaName = generateUniqueSchemaName(openAPI, "Collection"); + Schema containerSchema = new ObjectSchema(); + containerSchema.addProperties("inner", schema); + addInternalExtensionToSchema(containerSchema, VEN_FROM_CONTAINER, Boolean.TRUE); + openAPI.getComponents().addSchemas(containerSchemaName, containerSchema); + String containerDataType = getTypeDeclaration(toModelName(containerSchemaName)); + addInternalExtensionToSchema(schema, VEN_CONTAINER_DATA_TYPE, containerDataType); + } + } + } + @Override public Map postProcessOperationsWithModels(Map objs, List allModels) { objs = super.postProcessOperationsWithModels(objs, allModels); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java index d45bf289e7f2..9105a4fe8de4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java @@ -16,6 +16,14 @@ package org.openapitools.codegen.languages; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.servers.Server; +import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenSecurity; import org.openapitools.codegen.CliOption; import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.SupportingFile; @@ -26,12 +34,22 @@ import org.slf4j.LoggerFactory; import java.io.File; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.*; -public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen { +import static org.openapitools.codegen.utils.StringUtils.camelize; + +public class PhpSlim4ServerCodegen extends AbstractPhpCodegen { private final Logger LOGGER = LoggerFactory.getLogger(PhpSlim4ServerCodegen.class); + public static final String USER_CLASSNAME_KEY = "userClassname"; public static final String PSR7_IMPLEMENTATION = "psr7Implementation"; + protected String groupId = "org.openapitools"; + protected String artifactId = "openapi-server"; + protected String authDirName = "Auth"; + protected String authPackage = ""; protected String psr7Implementation = "slim-psr7"; protected String interfacesDirName = "Interfaces"; protected String interfacesPackage = ""; @@ -40,6 +58,18 @@ public PhpSlim4ServerCodegen() { super(); modifyFeatureSet(features -> features + .includeDocumentationFeatures(DocumentationFeature.Readme) + .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) + .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling + ) + .excludeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) .includeClientModificationFeatures(ClientModificationFeature.MockServer) ); @@ -47,10 +77,29 @@ public PhpSlim4ServerCodegen() { .stability(Stability.STABLE) .build(); + // clear import mapping (from default generator) as slim does not use it + // at the moment + importMapping.clear(); + + variableNamingConvention = "camelCase"; + artifactVersion = "1.0.0"; + setInvokerPackage("OpenAPIServer"); + apiPackage = invokerPackage + "\\" + apiDirName; + modelPackage = invokerPackage + "\\" + modelDirName; + authPackage = invokerPackage + "\\" + authDirName; interfacesPackage = invokerPackage + "\\" + interfacesDirName; outputFolder = "generated-code" + File.separator + "slim4"; + + modelTestTemplateFiles.put("model_test.mustache", ".php"); + // no doc files + modelDocTemplateFiles.clear(); + apiDocTemplateFiles.clear(); + embeddedTemplateDir = templateDir = "php-slim4-server"; + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + // override cliOptions from AbstractPhpCodegen updateOption(AbstractPhpCodegen.VARIABLE_NAMING_CONVENTION, "camelCase"); @@ -68,6 +117,11 @@ public PhpSlim4ServerCodegen() { cliOptions.add(psr7Option); } + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + @Override public String getName() { return "php-slim4"; @@ -78,15 +132,39 @@ public String getHelp() { return "Generates a PHP Slim 4 Framework server library(with Mock server)."; } + @Override + public String apiFileFolder() { + if (apiPackage.startsWith(invokerPackage + "\\")) { + // need to strip out invokerPackage from path + return (outputFolder + File.separator + toSrcPath(StringUtils.removeStart(apiPackage, invokerPackage + "\\"), srcBasePath)); + } + return (outputFolder + File.separator + toSrcPath(apiPackage, srcBasePath)); + } + + @Override + public String modelFileFolder() { + if (modelPackage.startsWith(invokerPackage + "\\")) { + // need to strip out invokerPackage from path + return (outputFolder + File.separator + toSrcPath(StringUtils.removeStart(modelPackage, invokerPackage + "\\"), srcBasePath)); + } + return (outputFolder + File.separator + toSrcPath(modelPackage, srcBasePath)); + } + @Override public void processOpts() { super.processOpts(); if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + // Update the invokerPackage for the default authPackage + authPackage = invokerPackage + "\\" + authDirName; // Update interfacesPackage interfacesPackage = invokerPackage + "\\" + interfacesDirName; } + // make auth src path available in mustache template + additionalProperties.put("authPackage", authPackage); + additionalProperties.put("authSrcPath", "./" + toSrcPath(authPackage, srcBasePath)); + // same for interfaces package additionalProperties.put("interfacesPackage", interfacesPackage); additionalProperties.put("interfacesSrcPath", "./" + toSrcPath(interfacesPackage, srcBasePath)); @@ -121,6 +199,14 @@ public void processOpts() { additionalProperties.put("isSlimPsr7", Boolean.TRUE); } + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("composer.mustache", "", "composer.json")); + supportingFiles.add(new SupportingFile("index.mustache", "", "index.php")); + supportingFiles.add(new SupportingFile(".htaccess", "", ".htaccess")); + supportingFiles.add(new SupportingFile("SlimRouter.mustache", toSrcPath(invokerPackage, srcBasePath), "SlimRouter.php")); + supportingFiles.add(new SupportingFile("phpunit.xml.mustache", "", "phpunit.xml.dist")); + supportingFiles.add(new SupportingFile("phpcs.xml.mustache", "", "phpcs.xml.dist")); + // Slim 4 doesn't parse JSON body anymore we need to add suggested middleware // ref: https://www.slimframework.com/docs/v4/objects/request.html#the-request-body supportingFiles.add(new SupportingFile("htaccess_deny_all", "config", ".htaccess")); @@ -131,6 +217,126 @@ public void processOpts() { supportingFiles.add(new SupportingFile("base_model_test.mustache", toSrcPath(invokerPackage, testBasePath), "BaseModelTest.php")); } + @Override + public Map postProcessOperationsWithModels(Map objs, List allModels) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + addUserClassnameToOperations(operations); + escapeMediaType(operationList); + return objs; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + Map apiInfo = (Map) objs.get("apiInfo"); + List> apiList = (List>) apiInfo.get("apis"); + for (HashMap api : apiList) { + HashMap operations = (HashMap) api.get("operations"); + List operationList = (List) operations.get("operation"); + + // Sort operations to avoid static routes shadowing + // ref: https://github.com/nikic/FastRoute/blob/master/src/DataGenerator/RegexBasedAbstract.php#L92-L101 + Collections.sort(operationList, new Comparator() { + @Override + public int compare(CodegenOperation one, CodegenOperation another) { + if (one.getHasPathParams() && !another.getHasPathParams()) return 1; + if (!one.getHasPathParams() && another.getHasPathParams()) return -1; + return 0; + } + }); + } + return objs; + } + + @Override + public List fromSecurity(Map securitySchemeMap) { + List codegenSecurities = super.fromSecurity(securitySchemeMap); + if (Boolean.FALSE.equals(codegenSecurities.isEmpty())) { + supportingFiles.add(new SupportingFile("abstract_authenticator.mustache", toSrcPath(authPackage, srcBasePath), toAbstractName("Authenticator") + ".php")); + } + return codegenSecurities; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return toAbstractName("DefaultApi"); + } + return toAbstractName(camelize(name) + "Api"); + } + + @Override + public String toApiTestFilename(String name) { + if (name.length() == 0) { + return "DefaultApiTest"; + } + return camelize(name) + "ApiTest"; + } + + /** + * Strips out abstract prefix and suffix from classname and puts it in "userClassname" property of operations object. + * + * @param operations codegen object with operations + */ + private void addUserClassnameToOperations(Map operations) { + String classname = (String) operations.get("classname"); + classname = classname.replaceAll("^" + abstractNamePrefix, ""); + classname = classname.replaceAll(abstractNameSuffix + "$", ""); + operations.put(USER_CLASSNAME_KEY, classname); + } + + @Override + public String encodePath(String input) { + if (input == null) { + return input; + } + + // from DefaultCodegen.java + // remove \t, \n, \r + // replace \ with \\ + // replace " with \" + // outter unescape to retain the original multi-byte characters + // finally escalate characters avoiding code injection + input = super.escapeUnsafeCharacters( + StringEscapeUtils.unescapeJava( + StringEscapeUtils.escapeJava(input) + .replace("\\/", "/")) + .replaceAll("[\\t\\n\\r]", " ") + .replace("\\", "\\\\")); + // .replace("\"", "\\\"")); + + // from AbstractPhpCodegen.java + // Trim the string to avoid leading and trailing spaces. + input = input.trim(); + try { + + input = URLEncoder.encode(input, "UTF-8") + .replaceAll("\\+", "%20") + .replaceAll("\\%2F", "/") + .replaceAll("\\%7B", "{") // keep { part of complex placeholders + .replaceAll("\\%7D", "}") // } part + .replaceAll("\\%5B", "[") // [ part + .replaceAll("\\%5D", "]") // ] part + .replaceAll("\\%3A", ":") // : part + .replaceAll("\\%2B", "+") // + part + .replaceAll("\\%5C\\%5Cd", "\\\\d"); // \d part + } catch (UnsupportedEncodingException e) { + // continue + LOGGER.error(e.getMessage(), e); + } + return input; + } + + @Override + public CodegenOperation fromOperation(String path, + String httpMethod, + Operation operation, + List servers) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers); + op.path = encodePath(path); + return op; + } + /** * Set PSR-7 implementation package. * Ref: https://www.slimframework.com/docs/v4/concepts/value-objects.html diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java index 3b0b5deeb819..a00683cbd4a0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java @@ -67,10 +67,6 @@ public PythonClientCodegen() { // in other code generators, support needs to be enabled on a case-by-case basis. supportsAdditionalPropertiesWithComposedSchema = true; - // When the 'additionalProperties' keyword is not present in a OAS schema, allow - // undeclared properties. This is compliant with the JSON schema specification. - this.setDisallowAdditionalPropertiesIfNotPresent(false); - modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) @@ -96,9 +92,8 @@ public PythonClientCodegen() { ParameterFeature.Cookie ) ); - - // this may set datatype right for additional properties - instantiationTypes.put("map", "dict"); + // needed for type object with additionalProperties: false + typeMapping.put("object", "dict"); languageSpecificPrimitives.add("file_type"); languageSpecificPrimitives.add("none_type"); @@ -113,6 +108,20 @@ public PythonClientCodegen() { cliOptions.add(new CliOption(CodegenConstants.PYTHON_ATTR_NONE_IF_UNSET, CodegenConstants.PYTHON_ATTR_NONE_IF_UNSET_DESC) .defaultValue(Boolean.FALSE.toString())); + // option to change how we process + set the data in the 'additionalProperties' keyword. + CliOption disallowAdditionalPropertiesIfNotPresentOpt = CliOption.newBoolean( + CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, + CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_DESC).defaultValue(Boolean.FALSE.toString()); + Map disallowAdditionalPropertiesIfNotPresentOpts = new HashMap<>(); + disallowAdditionalPropertiesIfNotPresentOpts.put("false", + "The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications."); + disallowAdditionalPropertiesIfNotPresentOpts.put("true", + "Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default. NOTE: "+ + "this option breaks composition and will be removed in 6.0.0" + ); + disallowAdditionalPropertiesIfNotPresentOpt.setEnum(disallowAdditionalPropertiesIfNotPresentOpts); + cliOptions.add(disallowAdditionalPropertiesIfNotPresentOpt); + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) .stability(Stability.EXPERIMENTAL) .build(); @@ -162,6 +171,18 @@ public void processOpts() { } additionalProperties.put("attrNoneIfUnset", attrNoneIfUnset); + // When the 'additionalProperties' keyword is not present in a OAS schema, allow + // undeclared properties. This is compliant with the JSON schema specification. + // setting this to false is required to have composed schemas work because: + // anyOf SchemaA + SchemaB, requires that props present only in A are accepted in B because in B + // they are additional properties + Boolean disallowAddProps = false; + if (additionalProperties.containsKey(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT)) { + disallowAddProps = Boolean.valueOf(additionalProperties.get(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT).toString()); + } + this.setDisallowAdditionalPropertiesIfNotPresent(disallowAddProps); + + // check library option to ensure only urllib3 is supported if (!DEFAULT_LIBRARY.equals(getLibrary())) { throw new RuntimeException("Only the `urllib3` library is supported in the refactored `python` client generator at the moment. Please fall back to `python-legacy` client generator for the time being. We welcome contributions to add back `asyncio`, `tornado` support to the `python` client generator."); @@ -730,6 +751,62 @@ public String getModelName(Schema sc) { return null; } + @Override + protected Schema getAdditionalProperties(Schema schema) { + /* + Use cases: + 1. addProps set to schema in spec: return that schema + 2. addProps unset w/ getDisallowAdditionalPropertiesIfNotPresent -> null + 3. addProps unset w/ getDisallowAdditionalPropertiesIfNotPresent=False -> new Schema() + 4. addProps true -> new Schema() NOTE: v3 only + 5. addprops false -> null NOTE: v3 only + */ + Object addProps = schema.getAdditionalProperties(); + if (addProps instanceof Schema) { + return (Schema) addProps; + } + if (addProps == null) { + // When reaching this code path, this should indicate the 'additionalProperties' keyword is + // not present in the OAS schema. This is true for OAS 3.0 documents. + // However, the parsing logic is broken for OAS 2.0 documents because of the + // https://github.com/swagger-api/swagger-parser/issues/1369 issue. + // When OAS 2.0 documents are parsed, the swagger-v2-converter ignores the 'additionalProperties' + // keyword if the value is boolean. That means codegen is unable to determine whether + // additional properties are allowed or not. + // + // The original behavior was to assume additionalProperties had been set to false. + if (getDisallowAdditionalPropertiesIfNotPresent()) { + // If the 'additionalProperties' keyword is not present in a OAS schema, + // interpret as if the 'additionalProperties' keyword had been set to false. + // This is NOT compliant with the JSON schema specification. It is the original + // 'openapi-generator' behavior. + return null; + } + /* + // The disallowAdditionalPropertiesIfNotPresent CLI option has been set to true, + // but for now that only works with OAS 3.0 documents. + // The new behavior does not work with OAS 2.0 documents. + if (extensions == null || !extensions.containsKey(EXTENSION_OPENAPI_DOC_VERSION)) { + // Fallback to the legacy behavior. + return null; + } + // Get original swagger version from OAS extension. + // Note openAPI.getOpenapi() is always set to 3.x even when the document + // is converted from a OAS/Swagger 2.0 document. + // https://github.com/swagger-api/swagger-parser/pull/1374 + SemVer version = new SemVer((String)extensions.get(EXTENSION_OPENAPI_DOC_VERSION)); + if (version.major != 3) { + return null; + } + */ + } + if (addProps == null || (addProps instanceof Boolean && (Boolean) addProps)) { + // Return empty schema to allow any type + return new Schema(); + } + return null; + } + /** * Return a string representation of the Python types for the specified OAS schema. * Primitive types in the OAS specification are implemented in Python using the corresponding @@ -769,16 +846,39 @@ private String getTypeString(Schema p, String prefix, String suffix, List both become use case 1 + // switch to v3 if you need use cases 1 + 2 to work correctly + return prefix + "bool, date, datetime, dict, float, int, list, str, none_type" + fullSuffix; + } // Resolve $ref because ModelUtils.isXYZ methods do not automatically resolve references. if (ModelUtils.isNullable(ModelUtils.getReferencedSchema(this.openAPI, p))) { fullSuffix = ", none_type" + suffix; } - if (isFreeFormObject(p) && getAdditionalProperties(p) == null) { - return prefix + "bool, date, datetime, dict, float, int, list, str" + fullSuffix; - } - if ((ModelUtils.isMapSchema(p) || "object".equals(p.getType())) && getAdditionalProperties(p) != null) { + Boolean v3WithCompositionAddPropsAnyTypeSchemaCase = (getAdditionalProperties(p) != null && emptySchema.equals(getAdditionalProperties(p)) && originalSpecVersion.equals("3")); + if (isFreeFormObject(p) && v3WithCompositionAddPropsAnyTypeSchemaCase) { + // v3 code path, use case: type object schema with no other schema info + return prefix + "{str: (bool, date, datetime, dict, float, int, list, str, none_type)}" + fullSuffix; + } else if ((ModelUtils.isMapSchema(p) || "object".equals(p.getType())) && getAdditionalProperties(p) != null) { Schema inner = getAdditionalProperties(p); return prefix + "{str: " + getTypeString(inner, "(", ")", referencedModelNames) + "}" + fullSuffix; } else if (ModelUtils.isArraySchema(p)) { @@ -837,7 +937,7 @@ protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Sc // The 'addProps' may be a reference, getTypeDeclaration will resolve // the reference. List referencedModelNames = new ArrayList(); - codegenModel.additionalPropertiesType = getTypeString(addProps, "", "", referencedModelNames); + getTypeString(addProps, "", "", referencedModelNames); if (referencedModelNames.size() != 0) { // Models that are referenced in the 'additionalPropertiesType' keyword // must be added to the imports. @@ -1223,6 +1323,23 @@ private String exampleForObjectModel(Schema schema, String fullPrefix, String cl for (Map.Entry entry : requiredAndOptionalProps.entrySet()) { String propName = entry.getKey(); Schema propSchema = entry.getValue(); + boolean readOnly = false; + if (propSchema.getReadOnly() != null) { + readOnly = propSchema.getReadOnly(); + } + if (readOnly) { + continue; + } + String ref = propSchema.get$ref(); + if (ref != null) { + Schema refSchema = ModelUtils.getSchema(this.openAPI, ModelUtils.getSimpleRef(ref)); + if (refSchema.getReadOnly() != null) { + readOnly = refSchema.getReadOnly(); + } + if (readOnly) { + continue; + } + } propName = toVarName(propName); String propModelName = null; Object propExample = null; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFastAPIServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFastAPIServerCodegen.java new file mode 100644 index 000000000000..5cf315ab1357 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFastAPIServerCodegen.java @@ -0,0 +1,290 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.languages; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.module.SimpleModule; +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.Schema; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.*; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; +import org.openapitools.codegen.meta.features.*; +import org.openapitools.codegen.utils.ModelUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.util.*; + +import static org.openapitools.codegen.utils.StringUtils.underscore; + +public class PythonFastAPIServerCodegen extends AbstractPythonCodegen { + private static class SnakeCaseKeySerializer extends JsonSerializer { + @Override + public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeFieldName(underscore(value)); + } + } + + private static class PythonBooleanSerializer extends JsonSerializer { + @Override + public void serialize(Boolean value, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeNumber(value ? 1 : 0); + } + } + + // An object mapper that is used to convert an example string to + // a "python-compliant" example string (keys in snake case, boolean as 1/0). + final ObjectMapper MAPPER = new ObjectMapper(); + + final Logger LOGGER = LoggerFactory.getLogger(PythonFastAPIServerCodegen.class); + + private static final String NAME = "python-fastapi"; + private static final int DEFAULT_SERVER_PORT = 8080; + private static final String DEFAULT_PACKAGE_NAME = "openapi_server"; + private static final String SRC_DIR = "src"; + + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public String getHelp() { + return "Generates a Python FastAPI server (beta)."; + } + + public PythonFastAPIServerCodegen() { + super(); + + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.BETA) + .build(); + + SimpleModule simpleModule = new SimpleModule(); + simpleModule.addKeySerializer(String.class, new SnakeCaseKeySerializer()); + simpleModule.addSerializer(Boolean.class, new PythonBooleanSerializer()); + MAPPER.registerModule(simpleModule); + + /* + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("serverPort", DEFAULT_SERVER_PORT); + additionalProperties.put(CodegenConstants.PACKAGE_NAME, DEFAULT_PACKAGE_NAME); + + languageSpecificPrimitives.add("List"); + languageSpecificPrimitives.add("Dict"); + typeMapping.put("array", "List"); + typeMapping.put("map", "Dict"); + + outputFolder = "generated-code" + File.separator + NAME; + modelTemplateFiles.put("model.mustache", ".py"); + apiTemplateFiles.put("api.mustache", ".py"); + embeddedTemplateDir = templateDir = NAME; + apiPackage = "apis"; + modelPackage = "models"; + testPackage = "tests"; + apiTestTemplateFiles().put("api_test.mustache", ".py"); + + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "python package name (convention: snake_case).") + .defaultValue(DEFAULT_PACKAGE_NAME)); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "python package version.") + .defaultValue("1.0.0")); + cliOptions.add(new CliOption("serverPort", "TCP port to listen to in app.run"). + defaultValue(String.valueOf(DEFAULT_SERVER_PORT))); + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } + + modelPackage = packageName + "." + modelPackage; + apiPackage = packageName + "." + apiPackage; + + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("openapi.mustache", "", "openapi.yaml")); + supportingFiles.add(new SupportingFile("main.mustache", SRC_DIR + File.separator + packageName.replace('.', File.separatorChar), "main.py")); + supportingFiles.add(new SupportingFile("docker-compose.mustache", "", "docker-compose.yaml")); + supportingFiles.add(new SupportingFile("Dockerfile.mustache", "", "Dockerfile")); + supportingFiles.add(new SupportingFile("requirements.mustache", "", "requirements.txt")); + supportingFiles.add(new SupportingFile("security_api.mustache", SRC_DIR + File.separator + packageName.replace('.', File.separatorChar), "security_api.py")); + supportingFiles.add(new SupportingFile("extra_models.mustache", StringUtils.substringAfter(modelFileFolder(), outputFolder), "extra_models.py")); + + // Add __init__.py to all sub-folders under namespace pkg + StringBuilder namespacePackagePath = new StringBuilder(SRC_DIR + File.separator + StringUtils.substringBefore(packageName, ".")); + for (String tmp : StringUtils.split(StringUtils.substringAfter(packageName, "."), '.')) { + namespacePackagePath.append(File.separator).append(tmp); + supportingFiles.add(new SupportingFile("__init__.mustache", namespacePackagePath.toString(), "__init__.py")); + } + supportingFiles.add(new SupportingFile("__init__.mustache", StringUtils.substringAfter(modelFileFolder(), outputFolder), "__init__.py")); + supportingFiles.add(new SupportingFile("__init__.mustache", StringUtils.substringAfter(apiFileFolder(), outputFolder), "__init__.py")); + + supportingFiles.add(new SupportingFile("conftest.mustache", testPackage.replace('.', File.separatorChar), "conftest.py")); + + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("pyproject_toml.mustache", "", "pyproject.toml")); + supportingFiles.add(new SupportingFile("setup_cfg.mustache", "", "setup.cfg")); + } + + @Override + public String getName() { + return NAME; + } + + @Override + public String toModelImport(String name) { + String modelImport; + if (StringUtils.startsWithAny(name, "import", "from")) { + modelImport = name; + } else { + modelImport = "from "; + if (!"".equals(modelPackage())) { + modelImport += modelPackage() + "."; + } + modelImport += toModelFilename(name) + " import " + name; + } + return modelImport; + } + + @Override + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = getAdditionalProperties(p); + return getSchemaType(p) + "[str, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public Map postProcessOperationsWithModels(Map objs, List allModels) { + Map operations = (Map) objs.get("operations"); + // Set will make sure that no duplicated items are used. + Set securityImports = new HashSet<>(); + if (operations != null) { + List ops = (List) operations.get("operation"); + for (final CodegenOperation operation : ops) { + List responses = operation.responses; + if (responses != null) { + for (final CodegenResponse resp : responses) { + // Convert "default" value (0) to OK (200). + if ("0".equals(resp.code)) { + resp.code = "200"; + } + } + } + List securityMethods = operation.authMethods; + if (securityMethods != null) { + for (final CodegenSecurity securityMethod : securityMethods) { + securityImports.add(securityMethod.name); + } + } + + if (operation.requestBodyExamples != null) { + for (Map example : operation.requestBodyExamples) { + if (example.get("contentType") != null && example.get("contentType").equals("application/json")) { + // Make an example dictionary more python-like (snake-case, etc.). + // If fails, use the original string. + try { + Map result = MAPPER.readValue(example.get("example"), + new TypeReference>() { + }); + operation.bodyParam.example = MAPPER.writeValueAsString(result); + } catch (IOException e) { + operation.bodyParam.example = example.get("example"); + } + } + } + } + } + } + + objs.put("securityImports", new ArrayList(securityImports)); + + return objs; + } + + @Override + public Map postProcessAllModels(Map objs) { + Map result = super.postProcessAllModels(objs); + for (Map.Entry entry : result.entrySet()) { + Map inner = (Map) entry.getValue(); + List> models = (List>) inner.get("models"); + for (Map mo : models) { + CodegenModel cm = (CodegenModel) mo.get("model"); + // Add additional filename information for imports + mo.put("pyImports", toPyImports(cm, cm.imports)); + } + } + return result; + } + + private List> toPyImports(CodegenModel cm, Set imports) { + List> pyImports = new ArrayList<>(); + for (String im : imports) { + if (!im.equals(cm.classname)) { + HashMap pyImport = new HashMap<>(); + pyImport.put("import", toModelImport(im)); + pyImports.add(pyImport); + } + } + return pyImports; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + generateYAMLSpecFile(objs); + return objs; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + SRC_DIR + File.separator + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separator + SRC_DIR + File.separator + modelPackage().replace('.', File.separatorChar); + } + + @Override + public void postProcess() { + System.out.println("################################################################################"); + System.out.println("# Thanks for using OpenAPI Generator. #"); + System.out.println("# Please consider donation to help us maintain this project \uD83D\uDE4F #"); + System.out.println("# https://opencollective.com/openapi_generator/donate #"); + System.out.println("# #"); + System.out.println("# This generator's contributed by Nikita Vakula (https://github.com/krjakbrjak)#"); + System.out.println("# Please support his work directly via https://paypal.me/krjakbrjaki \uD83D\uDE4F #"); + System.out.println("################################################################################"); + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonLegacyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonLegacyClientCodegen.java index 8a213a37757a..138b1c543566 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonLegacyClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonLegacyClientCodegen.java @@ -36,6 +36,7 @@ public class PythonLegacyClientCodegen extends AbstractPythonCodegen implements // nose is a python testing framework, we use pytest if USE_NOSE is unset public static final String USE_NOSE = "useNose"; public static final String RECURSION_LIMIT = "recursionLimit"; + public static final String PYTHON_ATTR_NONE_IF_UNSET = "pythonAttrNoneIfUnset"; protected String packageUrl; protected String apiDocPath = "docs/"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java index 40b2d9c22eed..96a5f5d7c3f1 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java @@ -748,8 +748,14 @@ private String constructExampleCode(CodegenModel codegenModel, HashMap(); typeMapping.put("array", "Array"); - typeMapping.put("List", "Array"); typeMapping.put("map", "Dictionary"); typeMapping.put("set", "Set"); typeMapping.put("date", "Date"); @@ -220,8 +233,8 @@ public Swift5ClientCodegen() { typeMapping.put("UUID", "UUID"); typeMapping.put("URI", "String"); typeMapping.put("decimal", "Decimal"); - typeMapping.put("object", "Any"); - typeMapping.put("AnyType", "Any"); + typeMapping.put("object", "AnyCodable"); + typeMapping.put("AnyType", "AnyCodable"); importMapping = new HashMap<>(); @@ -259,8 +272,28 @@ public Swift5ClientCodegen() { "Accept and cast values for simple types (string->bool, " + "string->int, int->string)") .defaultValue(Boolean.FALSE.toString())); + cliOptions.add(new CliOption(USE_BACKTICK_ESCAPES, + "Escape reserved words using backticks (default: false)") + .defaultValue(Boolean.FALSE.toString())); + cliOptions.add(new CliOption(GENERATE_MODEL_ADDITIONAL_PROPERTIES, + "Generate model additional properties (default: true)") + .defaultValue(Boolean.TRUE.toString())); cliOptions.add(new CliOption(CodegenConstants.API_NAME_PREFIX, CodegenConstants.API_NAME_PREFIX_DESC)); + cliOptions.add(new CliOption(USE_SPM_FILE_STRUCTURE, "Use SPM file structure" + + " and set the source path to Sources" + File.separator + "{{projectName}} (default: false).")); + cliOptions.add(new CliOption(SWIFT_PACKAGE_PATH, "Set a custom source path instead of " + + projectName + File.separator + "Classes" + File.separator + "OpenAPIs" + ".")); + cliOptions.add(new CliOption(USE_CLASSES, "Use final classes for models instead of structs (default: false)") + .defaultValue(Boolean.FALSE.toString())); + + cliOptions.add(new CliOption(HASHABLE_MODELS, + "Make hashable models (default: true)") + .defaultValue(Boolean.TRUE.toString())); + + cliOptions.add(new CliOption(MAP_FILE_BINARY_TO_DATA, + "[WARNING] This option will be removed and enabled by default in the future once we've enhanced the code to work with `Data` in all the different situations. Map File and Binary to Data (default: false)") + .defaultValue(Boolean.FALSE.toString())); supportedLibraries.put(LIBRARY_URLSESSION, "[DEFAULT] HTTP client: URLSession"); supportedLibraries.put(LIBRARY_ALAMOFIRE, "HTTP client: Alamofire"); @@ -334,7 +367,15 @@ protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, final Schema additionalProperties = getAdditionalProperties(schema); if (additionalProperties != null) { - codegenModel.additionalPropertiesType = getSchemaType(additionalProperties); + Schema inner = null; + if (ModelUtils.isArraySchema(schema)) { + ArraySchema ap = (ArraySchema) schema; + inner = ap.getItems(); + } else if (ModelUtils.isMapSchema(schema)) { + inner = getAdditionalProperties(schema); + } + + codegenModel.additionalPropertiesType = inner != null ? getTypeDeclaration(inner) : getSchemaType(additionalProperties); } } @@ -405,7 +446,7 @@ public void processOpts() { additionalProperties.put(READONLY_PROPERTIES, readonlyProperties); // Setup swiftUseApiNamespace option, which makes all the API - // classes inner-class of {{projectName}}API + // classes inner-class of {{projectName}} if (additionalProperties.containsKey(SWIFT_USE_API_NAMESPACE)) { setSwiftUseApiNamespace(convertPropertyToBooleanAndWriteBack(SWIFT_USE_API_NAMESPACE)); } @@ -414,6 +455,44 @@ public void processOpts() { additionalProperties.put(POD_AUTHORS, DEFAULT_POD_AUTHORS); } + if (additionalProperties.containsKey(USE_SPM_FILE_STRUCTURE)) { + setUseSPMFileStructure(convertPropertyToBooleanAndWriteBack(USE_SPM_FILE_STRUCTURE)); + sourceFolder = "Sources" + File.separator + projectName; + } + + if (additionalProperties.containsKey(SWIFT_PACKAGE_PATH) && ((String)additionalProperties.get(SWIFT_PACKAGE_PATH)).length() > 0) { + setSwiftPackagePath((String)additionalProperties.get(SWIFT_PACKAGE_PATH)); + sourceFolder = swiftPackagePath; + } + + if (additionalProperties.containsKey(USE_BACKTICK_ESCAPES)) { + setUseBacktickEscapes(convertPropertyToBooleanAndWriteBack(USE_BACKTICK_ESCAPES)); + } + + if (additionalProperties.containsKey(GENERATE_MODEL_ADDITIONAL_PROPERTIES)) { + setGenerateModelAdditionalProperties(convertPropertyToBooleanAndWriteBack(GENERATE_MODEL_ADDITIONAL_PROPERTIES)); + } + additionalProperties.put(GENERATE_MODEL_ADDITIONAL_PROPERTIES, generateModelAdditionalProperties); + + if (additionalProperties.containsKey(HASHABLE_MODELS)) { + setHashableModels(convertPropertyToBooleanAndWriteBack(HASHABLE_MODELS)); + } + additionalProperties.put(HASHABLE_MODELS, hashableModels); + + if (additionalProperties.containsKey(MAP_FILE_BINARY_TO_DATA)) { + setMapFileBinaryToData(convertPropertyToBooleanAndWriteBack(MAP_FILE_BINARY_TO_DATA)); + } + additionalProperties.put(MAP_FILE_BINARY_TO_DATA, mapFileBinaryToData); + if (mapFileBinaryToData) { + typeMapping.put("file", "Data"); + typeMapping.put("binary", "Data"); + } + + if (additionalProperties.containsKey(USE_CLASSES)) { + setUseClasses(convertPropertyToBooleanAndWriteBack(USE_CLASSES)); + } + additionalProperties.put(USE_CLASSES, useClasses); + setLenientTypeCast(convertPropertyToBooleanAndWriteBack(LENIENT_TYPE_CAST)); // make api and model doc path available in mustache template @@ -491,6 +570,14 @@ public void processOpts() { } + public boolean isMapFileBinaryToData() { + return mapFileBinaryToData; + } + + public void setMapFileBinaryToData(boolean mapFileBinaryToData) { + this.mapFileBinaryToData = mapFileBinaryToData; + } + @Override protected boolean isReservedWord(String word) { return word != null && reservedWords.contains(word); //don't lowercase as super does @@ -501,7 +588,7 @@ public String escapeReservedWord(String name) { if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } - return "_" + name; // add an underscore to the name + return useBacktickEscapes && !objcCompatible ? "`" + name + "`" : "_" + name; } @Override @@ -720,11 +807,16 @@ public String toVarName(String name) { // pet_id => petId name = camelize(name, true); - // for reserved word or word starting with number, append _ - if (isReservedWord(name) || name.matches("^\\d.*")) { + // for reserved words surround with `` or append _ + if (isReservedWord(name)) { name = escapeReservedWord(name); } + // for words starting with number, append _ + if (name.matches("^\\d.*")) { + name = "_" + name; + } + return name; } @@ -745,11 +837,16 @@ public String toParamName(String name) { // pet_id => petId name = camelize(name, true); - // for reserved word or word starting with number, append _ - if (isReservedWord(name) || name.matches("^\\d.*")) { + // for reserved words surround with `` + if (isReservedWord(name)) { name = escapeReservedWord(name); } + // for words starting with number, append _ + if (name.matches("^\\d.*")) { + name = "_" + name; + } + return name; } @@ -774,7 +871,9 @@ public CodegenModel fromModel(String name, Schema model) { parentSchema = parentCodegenModel.parentSchema; } } - + if (hashableModels) { + codegenModel.vendorExtensions.put("x-swift-hashable", true); + } return codegenModel; } @@ -806,6 +905,30 @@ public void setSwiftUseApiNamespace(boolean swiftUseApiNamespace) { this.swiftUseApiNamespace = swiftUseApiNamespace; } + public void setUseSPMFileStructure(boolean useSPMFileStructure) { + this.useSPMFileStructure = useSPMFileStructure; + } + + public void setSwiftPackagePath(String swiftPackagePath) { + this.swiftPackagePath = swiftPackagePath; + } + + public void setUseClasses(boolean useClasses) { + this.useClasses = useClasses; + } + + public void setUseBacktickEscapes(boolean useBacktickEscapes) { + this.useBacktickEscapes = useBacktickEscapes; + } + + public void setGenerateModelAdditionalProperties(boolean generateModelAdditionalProperties) { + this.generateModelAdditionalProperties = generateModelAdditionalProperties; + } + + public void setHashableModels(boolean hashableModels) { + this.hashableModels = hashableModels; + } + @Override public String toEnumValue(String value, String datatype) { // for string, array of string @@ -1027,6 +1150,8 @@ public String constructExampleCode(CodegenParameter codegenParameter, HashMap postProcessOperationsWithModels(Map objs, + List allModels) { + + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + op.operationId = this.generateOperationId(op); + + // for xml compliant primitives, lowercase dataType of openapi + for (CodegenParameter param : op.allParams) { + Map paramVendorExtensions = param.vendorExtensions; + + normalizeDataType(param); + + // prevent default="null" in wsdl-tag if no default was specified for a param + if ("null".equals(param.defaultValue) || param.defaultValue == null) { + paramVendorExtensions.put("x-param-has-defaultvalue", false); + } else { + paramVendorExtensions.put("x-param-has-defaultvalue", true); + } + + // check if param has a minimum or maximum number or lenght + if (param.minimum != null + || param.maximum != null + || param.minLength != null + || param.maxLength != null) { + paramVendorExtensions.put("x-param-has-minormax", true); + } else { + paramVendorExtensions.put("x-param-has-minormax", false); + } + + // if param is enum, uppercase 'baseName' to have a reference to wsdl simpletype + if (param.isEnum) { + char[] c = param.baseName.toCharArray(); + c[0] = Character.toUpperCase(c[0]); + param.baseName = new String(c); + } + } + + for (CodegenParameter param : op.bodyParams) { + normalizeDataType(param); + } + for (CodegenParameter param : op.pathParams) { + normalizeDataType(param); + } + for (CodegenParameter param : op.queryParams) { + normalizeDataType(param); + } + for (CodegenParameter param : op.formParams) { + normalizeDataType(param); + } + } + + return objs; + } + + private void normalizeDataType(CodegenParameter param) { + if (param.isPrimitiveType) { + param.dataType = param.dataType.toLowerCase(Locale.getDefault()); + } + if (param.dataFormat != null && param.dataFormat.equalsIgnoreCase("date")) { + param.dataType = "date"; + } + if (param.dataFormat != null && param.dataFormat.equalsIgnoreCase("date-time")) { + param.dataType = "dateTime"; + } + if (param.dataFormat != null && param.dataFormat.equalsIgnoreCase("uuid")) { + param.dataType = "string"; + } + } + + @Override + public Map postProcessModels(Map objs) { + List models = (List) objs.get("models"); + + for (Object mo : models) { + Map mod = (Map) mo; + CodegenModel model = (CodegenModel) mod.get("model"); + Map modelVendorExtensions = model.getVendorExtensions(); + + /* check if model is a model with no properties + * Used in the mustache template to ensure that no complextype is created + * if model is just a schema with an enum defined in the openapi specification + */ + if (model.allowableValues != null) { + modelVendorExtensions.put("x-is-openapimodel-enum", true); + } else { + modelVendorExtensions.put("x-is-openapimodel-enum", false); + } + + for (CodegenProperty var : model.vars) { + Map propertyVendorExtensions = var.getVendorExtensions(); + + // lowercase basetypes if openapitype is string + if ("string".equals(var.openApiType)) { + char[] c = var.baseType.toCharArray(); + c[0] = Character.toLowerCase(c[0]); + var.baseType = new String(c); + } + // if string enum, uppercase 'name' to have a reference to wsdl simpletype + if (var.isEnum) { + char[] c = var.name.toCharArray(); + c[0] = Character.toUpperCase(c[0]); + var.name = new String(c); + } + + // prevent default="null" in wsdl-tag if no default was specified for a property + if ("null".equals(var.defaultValue) || var.defaultValue == null) { + propertyVendorExtensions.put("x-prop-has-defaultvalue", false); + } else { + propertyVendorExtensions.put("x-prop-has-defaultvalue", true); + } + + // check if model property has a minimum or maximum number or lenght + if (var.minimum != null + || var.maximum != null + || var.minLength != null + || var.maxLength != null) { + propertyVendorExtensions.put("x-prop-has-minormax", true); + } else { + propertyVendorExtensions.put("x-prop-has-minormax", false); + } + } + } + return super.postProcessModelsEnum(objs); + } + + public String generateOperationId(CodegenOperation op) { + String newOperationid = this.lowerCaseStringExceptFirstLetter(op.httpMethod); + String[] pathElements = op.path.split("/"); + List pathParameters = new ArrayList(); + + for (int i = 0; i < pathElements.length; i++) { + if (pathElements[i].contains("{")) { + pathParameters.add(pathElements[i]); + pathElements[i] = ""; + } + if (pathElements[i].length() > 0) { + newOperationid = newOperationid + this.lowerCaseStringExceptFirstLetter(pathElements[i]); + } + } + + if (pathParameters.size() > 0) { + for (int i = 0; i < pathParameters.size(); i++) { + String pathParameter = pathParameters.get(i); + pathParameter = this.lowerCaseStringExceptFirstLetter(pathParameter + .substring(1, pathParameter.length() - 1)); + if (i == 0) { + newOperationid = newOperationid + "By" + pathParameter; + } else { + newOperationid = newOperationid + "And" + pathParameter; + } + } + } + return newOperationid; + } + + public String lowerCaseStringExceptFirstLetter(String value) { + String newOperationid = value.toLowerCase(Locale.getDefault()); + return newOperationid.substring(0, 1).toUpperCase(Locale.getDefault()) + + newOperationid.substring(1); + } + + @Override + public String escapeQuotationMark(String input) { + // just return the original string + return input; + } + + @Override + public String escapeUnsafeCharacters(String input) { + // just return the original string + return input; + } +} diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache index 0c85a67a2b39..81c1fbdba39c 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache @@ -18,13 +18,13 @@ // Functions for enum {{enumName}} for {{{classname}}}_{{{operationId}}} static char* {{{operationId}}}_{{enumName}}_ToString({{projectName}}_{{operationId}}_{{baseName}}_e {{enumName}}){ - char *{{enumName}}Array[] = { "NULL"{{#allowableValues}}{{#enumVars}}, "{{{value}}}"{{/enumVars}}{{/allowableValues}} }; + char *{{enumName}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; return {{enumName}}Array[{{enumName}}]; } static {{projectName}}_{{operationId}}_{{baseName}}_e {{{operationId}}}_{{enumName}}_FromString(char* {{enumName}}){ int stringToReturn = 0; - char *{{enumName}}Array[] = { "NULL"{{#allowableValues}}{{#enumVars}}, "{{{value}}}"{{/enumVars}}{{/allowableValues}} }; + char *{{enumName}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; size_t sizeofArray = sizeof({{enumName}}Array) / sizeof({{enumName}}Array[0]); while(stringToReturn < sizeofArray) { if(strcmp({{enumName}}, {{enumName}}Array[stringToReturn]) == 0) { diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache index e487cb0f4746..6f4259a6f183 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache @@ -8,13 +8,13 @@ {{#isEnum}} char* {{classFilename}}_{{classname}}_ToString({{projectName}}_{{classVarName}}_{{enumName}}_e {{classname}}) { - char *{{classname}}Array[] = { "NULL"{{#allowableValues}}{{#enumVars}}, "{{{value}}}"{{/enumVars}}{{/allowableValues}} }; + char *{{classname}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; return {{classname}}Array[{{classname}}]; } {{projectName}}_{{classVarName}}_{{enumName}}_e {{classFilename}}_{{classname}}_FromString(char* {{classname}}) { int stringToReturn = 0; - char *{{classname}}Array[] = { "NULL"{{#allowableValues}}{{#enumVars}}, "{{{value}}}"{{/enumVars}}{{/allowableValues}} }; + char *{{classname}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; size_t sizeofArray = sizeof({{classname}}Array) / sizeof({{classname}}Array[0]); while(stringToReturn < sizeofArray) { if(strcmp({{classname}}, {{classname}}Array[stringToReturn]) == 0) { @@ -78,13 +78,13 @@ end: {{^isModel}} {{#isEnum}} char* {{name}}{{classname}}_ToString({{projectName}}_{{classVarName}}_{{enumName}}_e {{name}}) { - char* {{name}}Array[] = { "NULL"{{#allowableValues}}{{#enumVars}}, "{{{value}}}"{{/enumVars}}{{/allowableValues}} }; + char* {{name}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; return {{name}}Array[{{name}}]; } {{projectName}}_{{classVarName}}_{{enumName}}_e {{name}}{{classname}}_FromString(char* {{name}}){ int stringToReturn = 0; - char *{{name}}Array[] = { "NULL"{{#allowableValues}}{{#enumVars}}, "{{{value}}}"{{/enumVars}}{{/allowableValues}} }; + char *{{name}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; size_t sizeofArray = sizeof({{name}}Array) / sizeof({{name}}Array[0]); while(stringToReturn < sizeofArray) { if(strcmp({{name}}, {{name}}Array[stringToReturn]) == 0) { @@ -102,13 +102,13 @@ char* {{name}}{{classname}}_ToString({{projectName}}_{{classVarName}}_{{enumName {{^isModel}} {{#isEnum}} char* {{name}}{{classname}}_ToString({{projectName}}_{{classVarName}}_{{enumName}}_e {{name}}) { - char *{{name}}Array[] = { "NULL"{{#allowableValues}}{{#enumVars}}, "{{{value}}}"{{/enumVars}}{{/allowableValues}} }; + char *{{name}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; return {{name}}Array[{{name}} - 1]; } {{projectName}}_{{classVarName}}_{{enumName}}_e {{name}}{{classname}}_FromString(char* {{name}}) { int stringToReturn = 0; - char *{{name}}Array[] = { "NULL"{{#allowableValues}}{{#enumVars}}, "{{{value}}}"{{/enumVars}}{{/allowableValues}} }; + char *{{name}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; size_t sizeofArray = sizeof({{name}}Array) / sizeof({{name}}Array[0]); while(stringToReturn < sizeofArray) { if(strcmp({{name}}, {{name}}Array[stringToReturn]) == 0) { diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/AbstractOpenApiSchema.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/AbstractOpenApiSchema.mustache index 6eb87a90b9bc..734ef553e30e 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/AbstractOpenApiSchema.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/AbstractOpenApiSchema.mustache @@ -1,6 +1,6 @@ {{>licenseInfo}} -package {{invokerPackage}}.model; +package {{modelPackage}}; import {{invokerPackage}}.ApiException; import java.util.Objects; diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/ApiClient.mustache index 095a71939a7a..ea46db7331d2 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/native/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/ApiClient.mustache @@ -170,7 +170,7 @@ public class ApiClient { public ApiClient(HttpClient.Builder builder, ObjectMapper mapper, String baseUri) { this.builder = builder; this.mapper = mapper; - updateBaseUri(baseUri); + updateBaseUri(baseUri != null ? baseUri : getDefaultBaseUri()); interceptor = null; readTimeout = null; responseInterceptor = null; diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/api.mustache index 2adef3a6b0e9..e91e72f97b98 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/native/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/api.mustache @@ -65,6 +65,14 @@ public class {{classname}} { } {{/asyncNative}} + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + {{#operation}} {{#vendorExtensions.x-group-parameters}} {{#hasParams}} @@ -207,10 +215,7 @@ public class {{classname}} { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "{{operationId}} call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "{{operationId}} call received non-success response"); } return new ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>( localVarResponse.statusCode(), diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache index c027064edd43..7e3d97298ea9 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache @@ -40,14 +40,8 @@ if(hasProperty('target') && target == 'android') { targetSdkVersion 25 } compileOptions { - {{#java8}} sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 - {{/java8}} - {{^java8}} - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 - {{/java8}} } // Rename the aar correctly @@ -92,14 +86,8 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - {{#java8}} sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 - {{/java8}} - {{^java8}} - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 - {{/java8}} install { repositories.mavenInstaller { @@ -116,8 +104,8 @@ if(hasProperty('target') && target == 'android') { dependencies { implementation 'io.swagger:swagger-annotations:1.5.24' implementation "com.google.code.findbugs:jsr305:3.0.2" - implementation 'com.squareup.okhttp3:okhttp:3.14.7' - implementation 'com.squareup.okhttp3:logging-interceptor:3.14.7' + implementation 'com.squareup.okhttp3:okhttp:4.9.1' + implementation 'com.squareup.okhttp3:logging-interceptor:4.9.1' implementation 'com.google.code.gson:gson:2.8.6' implementation 'io.gsonfire:gson-fire:1.8.4' {{#hasOAuthMethods}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache index a14047e79984..8979b10a7f8c 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache @@ -10,8 +10,8 @@ lazy val root = (project in file(".")). resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( "io.swagger" % "swagger-annotations" % "1.5.24", - "com.squareup.okhttp3" % "okhttp" % "3.14.7", - "com.squareup.okhttp3" % "logging-interceptor" % "3.14.7", + "com.squareup.okhttp3" % "okhttp" % "4.9.1", + "com.squareup.okhttp3" % "logging-interceptor" % "4.9.1", "com.google.code.gson" % "gson" % "2.8.6", "org.apache.commons" % "commons-lang3" % "3.10", {{#hasOAuthMethods}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache index 150f3d3ebbbc..032d398f6cd2 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache @@ -39,10 +39,11 @@ import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter; import com.fasterxml.jackson.databind.ObjectMapper; +{{/threetenbp}} {{#openApiNullable}} import org.openapitools.jackson.nullable.JsonNullableModule; {{/openApiNullable}} -{{/threetenbp}} + import java.io.BufferedReader; import java.io.IOException; diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/api.mustache index 006e6cf8f931..e0c75bdc0daa 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/api.mustache @@ -139,12 +139,12 @@ public class {{classname}} { final String[] contentTypes = { {{#hasConsumes}} {{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}} {{/hasConsumes}} }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{^-last}}, {{/-last}}{{/authMethods}} }; {{#returnType}}ParameterizedTypeReference<{{{returnType}}}> returnType = new ParameterizedTypeReference<{{{returnType}}}>() {};{{/returnType}}{{^returnType}}ParameterizedTypeReference returnType = new ParameterizedTypeReference() {};{{/returnType}} - return apiClient.invokeAPI(path, HttpMethod.{{httpMethod}}, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.{{httpMethod}}, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } {{/operation}} } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache index 0fe89ccb026c..6491013f5a84 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache @@ -59,6 +59,9 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TimeZone; + +import javax.annotation.Nullable; + {{#jsr310}} {{#threetenbp}} import org.threeten.bp.OffsetDateTime; @@ -98,45 +101,58 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { private final WebClient webClient; private final DateFormat dateFormat; + private final ObjectMapper objectMapper; private Map authentications; public ApiClient() { this.dateFormat = createDefaultDateFormat(); - ObjectMapper mapper = new ObjectMapper(); - mapper.setDateFormat(dateFormat); - mapper.registerModule(new JavaTimeModule()); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - {{#openApiNullable}} - JsonNullableModule jnm = new JsonNullableModule(); - mapper.registerModule(jnm); - {{/openApiNullable}} - - this.webClient = buildWebClient(mapper); + this.objectMapper = createDefaultObjectMapper(this.dateFormat); + this.webClient = buildWebClient(this.objectMapper); this.init(); } + public ApiClient(WebClient webClient) { + this(Optional.ofNullable(webClient).orElseGet(() -> buildWebClient()), createDefaultDateFormat()); + } + public ApiClient(ObjectMapper mapper, DateFormat format) { this(buildWebClient(mapper.copy()), format); } public ApiClient(WebClient webClient, ObjectMapper mapper, DateFormat format) { - this(Optional.ofNullable(webClient).orElseGet(() ->buildWebClient(mapper.copy())), format); + this(Optional.ofNullable(webClient).orElseGet(() -> buildWebClient(mapper.copy())), format); } private ApiClient(WebClient webClient, DateFormat format) { this.webClient = webClient; this.dateFormat = format; + this.objectMapper = createDefaultObjectMapper(format); this.init(); } - public DateFormat createDefaultDateFormat() { + public static DateFormat createDefaultDateFormat() { DateFormat dateFormat = new RFC3339DateFormat(); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return dateFormat; } + public static ObjectMapper createDefaultObjectMapper(@Nullable DateFormat dateFormat) { + if (null == dateFormat) { + dateFormat = createDefaultDateFormat(); + } + ObjectMapper mapper = new ObjectMapper(); + mapper.setDateFormat(dateFormat); + mapper.registerModule(new JavaTimeModule()); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + {{#openApiNullable}} + JsonNullableModule jnm = new JsonNullableModule(); + mapper.registerModule(jnm); + {{/openApiNullable}} + return mapper; + } + protected void init() { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap();{{#authMethods}}{{#isBasic}}{{#isBasicBasic}} @@ -149,20 +165,45 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { } /** - * Build the WebClient used to make HTTP requests. + * Build the WebClientBuilder used to make WebClient. + * @param mapper ObjectMapper used for serialize/deserialize * @return WebClient */ - public static WebClient buildWebClient(ObjectMapper mapper) { + public static WebClient.Builder buildWebClientBuilder(ObjectMapper mapper) { ExchangeStrategies strategies = ExchangeStrategies .builder() .codecs(clientDefaultCodecsConfigurer -> { clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(mapper, MediaType.APPLICATION_JSON)); clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(mapper, MediaType.APPLICATION_JSON)); }).build(); - WebClient.Builder webClient = WebClient.builder().exchangeStrategies(strategies); - return webClient.build(); + WebClient.Builder webClientBuilder = WebClient.builder().exchangeStrategies(strategies); + return webClientBuilder; + } + + /** + * Build the WebClientBuilder used to make WebClient. + * @return WebClient + */ + public static WebClient.Builder buildWebClientBuilder() { + return buildWebClientBuilder(createDefaultObjectMapper(null)); + } + + /** + * Build the WebClient used to make HTTP requests. + * @param mapper ObjectMapper used for serialize/deserialize + * @return WebClient + */ + public static WebClient buildWebClient(ObjectMapper mapper) { + return buildWebClientBuilder(mapper).build(); } + /** + * Build the WebClient used to make HTTP requests. + * @return WebClient + */ + public static WebClient buildWebClient() { + return buildWebClientBuilder(createDefaultObjectMapper(null)).build(); + } /** * Get the current base path @@ -352,6 +393,22 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { return dateFormat.format(date); } + /** + * Get the ObjectMapper used to make HTTP requests. + * @return ObjectMapper objectMapper + */ + public ObjectMapper getObjectMapper() { + return objectMapper; + } + + /** + * Get the WebClient used to make HTTP requests. + * @return WebClient webClient + */ + public WebClient getWebClient() { + return webClient; + } + /** * Format the given parameter object into string. * @param param the object to convert @@ -655,10 +712,10 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { } // collectionFormat is assumed to be "csv" by default - if(collectionFormat == null) { - collectionFormat = CollectionFormat.CSV; - } + if(collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } - return collectionFormat.collectionToString(values); + return collectionFormat.collectionToString(values); } } diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/pojo.mustache index 6bde84c3fdd9..637add30c23b 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/pojo.mustache @@ -87,7 +87,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali {{{vendorExtensions.x-extra-annotation}}} {{/vendorExtensions.x-extra-annotation}} {{#jackson}} - @JsonProperty("{{baseName}}") + @JsonProperty(value = "{{baseName}}"{{#isReadOnly}}, access = JsonProperty.Access.READ_ONLY{{/isReadOnly}}{{#isWriteOnly}}, access = JsonProperty.Access.WRITE_ONLY{{/isWriteOnly}}) {{/jackson}} @ApiModelProperty({{#example}}example = "{{{example}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") {{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationQueryParams.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationQueryParams.mustache index 9cca8cb88748..a2f19f77468c 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationQueryParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationQueryParams.mustache @@ -1 +1 @@ -{{#required}}@NotNull {{/required}}{{>beanValidationCore}} \ No newline at end of file +{{#required}}@NotNull {{/required}}{{^useOptional}}{{>beanValidationCore}}{{/useOptional}}{{#useOptional}}{{#required}}{{>beanValidationCore}}{{/required}}{{/useOptional}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/application.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/application.mustache index b7fea3f62620..6eb4ae242983 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/application.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/application.mustache @@ -5,8 +5,8 @@ server.port={{serverPort}} spring.jackson.date-format={{basePackage}}.RFC3339DateFormat spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false {{#virtualService}} -virtual.datasource.driver-class-name=org.hsqldb.jdbcDriver -virtual.datasource.jdbcurl=jdbc:hsqldb:mem:dataSource -virtual.datasource.username=sa -virtual.datasource.password= -{{/virtualService}} \ No newline at end of file +virtualan.datasource.driver-class-name=org.hsqldb.jdbcDriver +virtualan.datasource.jdbcurl=jdbc:hsqldb:mem:dataSource +virtualan.datasource.username=sa +virtualan.datasource.password= +{{/virtualService}} diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/pom.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/pom.mustache index e2733633e359..d5ae34ff8a55 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/pom.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/pom.mustache @@ -176,18 +176,13 @@ io.virtualan virtualan-plugin - 2.1.7 + 2.2.1 org.hsqldb hsqldb - 2.3.2 - - - org.springframework.boot - spring-boot-starter-data-jpa - 1.5.9.RELEASE + 2.5.0 {{/virtualService}} diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/optionalDataType.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/optionalDataType.mustache index 976950e27e88..84505f8fc299 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/optionalDataType.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/optionalDataType.mustache @@ -1 +1 @@ -{{#useOptional}}{{#required}}{{{dataType}}}{{/required}}{{^required}}Optional<{{{dataType}}}>{{/required}}{{/useOptional}}{{^useOptional}}{{{dataType}}}{{/useOptional}} \ No newline at end of file +{{#useOptional}}{{#required}}{{{dataType}}}{{/required}}{{^required}}Optional<{{#useBeanValidation}}{{>beanValidationCore}}{{/useBeanValidation}}{{{dataType}}}>{{/required}}{{/useOptional}}{{^useOptional}}{{{dataType}}}{{/useOptional}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/Javascript-Flowtyped/api.mustache b/modules/openapi-generator/src/main/resources/Javascript-Flowtyped/api.mustache index 35bff5b9687e..ccfed6298ec5 100644 --- a/modules/openapi-generator/src/main/resources/Javascript-Flowtyped/api.mustache +++ b/modules/openapi-generator/src/main/resources/Javascript-Flowtyped/api.mustache @@ -36,7 +36,6 @@ export type FetchArgs = { options: {}; } - /** * * @export @@ -79,12 +78,12 @@ export const {{classname}}FetchParamCreator = function (configuration?: Configur {{/summary}} * @throws {RequiredError} */ - {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options: RequestOptions): FetchArgs { + {{operationId}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options: RequestOptions): FetchArgs { {{#allParams}} {{#required}} // verify required parameter '{{paramName}}' is not null or undefined if ({{paramName}} === null || {{paramName}} === undefined) { - throw new RequiredError('{{paramName}}','Required parameter {{paramName}} was null or undefined when calling {{nickname}}.'); + throw new RequiredError('{{paramName}}','Required parameter {{paramName}} was null or undefined when calling {{operationId}}.'); } {{/required}} {{/allParams}} @@ -104,16 +103,16 @@ export const {{classname}}FetchParamCreator = function (configuration?: Configur {{#isKeyInHeader}} if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("{{keyParamName}}") - : configuration.apiKey; + ? configuration.apiKey("{{keyParamName}}") + : configuration.apiKey; localVarHeaderParameter["{{keyParamName}}"] = localVarApiKeyValue; } {{/isKeyInHeader}} {{#isKeyInQuery}} if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("{{keyParamName}}") - : configuration.apiKey; + ? configuration.apiKey("{{keyParamName}}") + : configuration.apiKey; localVarQueryParameter["{{keyParamName}}"] = localVarApiKeyValue; } {{/isKeyInQuery}} @@ -127,9 +126,9 @@ export const {{classname}}FetchParamCreator = function (configuration?: Configur {{#isOAuth}} // oauth required if (configuration && configuration.accessToken) { - const localVarAccessTokenValue = typeof configuration.accessToken === 'function' - ? configuration.accessToken("{{name}}", [{{#scopes}}"{{{scope}}}"{{^-last}}, {{/-last}}{{/scopes}}]) - : configuration.accessToken; + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("{{name}}", [{{#scopes}}"{{{scope}}}"{{^-last}}, {{/-last}}{{/scopes}}]) + : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } {{/isOAuth}} @@ -142,7 +141,7 @@ export const {{classname}}FetchParamCreator = function (configuration?: Configur localVarQueryParameter['{{baseName}}'] = {{paramName}}; {{/isCollectionFormatMulti}} {{^isCollectionFormatMulti}} - localVarQueryParameter['{{baseName}}'] = {{paramName}}.join(COLLECTION_FORMATS["{{collectionFormat}}"]); + localVarQueryParameter['{{baseName}}'] = {{#uniqueItems}}Array.from({{/uniqueItems}}{{paramName}}{{#uniqueItems}}){{/uniqueItems}}.join(COLLECTION_FORMATS["{{collectionFormat}}"]); {{/isCollectionFormatMulti}} } {{/isArray}} @@ -166,7 +165,7 @@ export const {{classname}}FetchParamCreator = function (configuration?: Configur {{#headerParams}} {{#isArray}} if ({{paramName}}) { - localVarHeaderParameter['{{baseName}}'] = {{paramName}}.join(COLLECTION_FORMATS["{{collectionFormat}}"]); + localVarHeaderParameter['{{baseName}}'] = {{#uniqueItems}}Array.from({{/uniqueItems}}{{paramName}}{{#uniqueItems}}){{/uniqueItems}}.join(COLLECTION_FORMATS["{{collectionFormat}}"]); } {{/isArray}} {{^isArray}} @@ -185,7 +184,7 @@ export const {{classname}}FetchParamCreator = function (configuration?: Configur }) {{/isCollectionFormatMulti}} {{^isCollectionFormatMulti}} - localVarFormParams.set('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS["{{collectionFormat}}"])); + localVarFormParams.set('{{baseName}}', {{#uniqueItems}}Array.from({{/uniqueItems}}{{paramName}}{{#uniqueItems}}){{/uniqueItems}}.join(COLLECTION_FORMATS["{{collectionFormat}}"])); {{/isCollectionFormatMulti}} } {{/isArray}} @@ -227,7 +226,7 @@ export const {{classname}}FetchParamCreator = function (configuration?: Configur }; export type {{classname}}Type = { {{#operation}} - {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: RequestOptions): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Response{{/returnType}}>, + {{operationId}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: RequestOptions): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Response{{/returnType}}>, {{/operation}} } @@ -247,8 +246,8 @@ export const {{classname}} = function(configuration?: Configuration, fetch: Fetc {{/summary}} * @throws {RequiredError} */ - {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: RequestOptions = {}): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Response{{/returnType}}> { - const localVarFetchArgs = {{classname}}FetchParamCreator(configuration).{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}options); + {{operationId}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: RequestOptions = {}): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Response{{/returnType}}> { + const localVarFetchArgs = {{classname}}FetchParamCreator(configuration).{{operationId}}({{#allParams}}{{paramName}}, {{/allParams}}options); return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { return response{{#returnType}}.json(){{/returnType}}; @@ -260,6 +259,7 @@ export const {{classname}} = function(configuration?: Configuration, fetch: Fetc {{/operation}} } }; + {{/operations}}{{/apis}}{{/apiInfo}} export type ApiTypes = { {{#apiInfo}}{{#apis}}{{#operations}} {{classname}}: {{classname}}Type, diff --git a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig index 886c41c7f4e2..a213327b3f7a 100644 --- a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig +++ b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig @@ -11,11 +11,12 @@ org.openapitools.codegen.languages.CrystalClientCodegen org.openapitools.codegen.languages.CLibcurlClientCodegen org.openapitools.codegen.languages.ClojureClientCodegen org.openapitools.codegen.languages.ConfluenceWikiCodegen -org.openapitools.codegen.languages.CppQt5ClientCodegen -org.openapitools.codegen.languages.CppQt5QHttpEngineServerCodegen +org.openapitools.codegen.languages.CppQtClientCodegen +org.openapitools.codegen.languages.CppQtQHttpEngineServerCodegen org.openapitools.codegen.languages.CppPistacheServerCodegen org.openapitools.codegen.languages.CppRestbedServerCodegen org.openapitools.codegen.languages.CppRestSdkClientCodegen +org.openapitools.codegen.languages.CppTinyClientCodegen org.openapitools.codegen.languages.CppTizenClientCodegen org.openapitools.codegen.languages.CppUE4ClientCodegen org.openapitools.codegen.languages.CSharpClientCodegen @@ -37,6 +38,7 @@ org.openapitools.codegen.languages.FsharpFunctionsServerCodegen org.openapitools.codegen.languages.FsharpGiraffeServerCodegen org.openapitools.codegen.languages.GoClientCodegen org.openapitools.codegen.languages.GoDeprecatedClientCodegen +org.openapitools.codegen.languages.GoEchoServerCodegen org.openapitools.codegen.languages.GoServerCodegen org.openapitools.codegen.languages.GoGinServerCodegen org.openapitools.codegen.languages.GraphQLSchemaCodegen @@ -44,6 +46,7 @@ org.openapitools.codegen.languages.GraphQLNodeJSExpressServerCodegen org.openapitools.codegen.languages.GroovyClientCodegen org.openapitools.codegen.languages.KotlinClientCodegen org.openapitools.codegen.languages.KotlinServerCodegen +org.openapitools.codegen.languages.KotlinServerDeprecatedCodegen org.openapitools.codegen.languages.KotlinSpringServerCodegen org.openapitools.codegen.languages.KotlinVertxServerCodegen org.openapitools.codegen.languages.KtormSchemaCodegen @@ -94,6 +97,7 @@ org.openapitools.codegen.languages.PowerShellClientCodegen org.openapitools.codegen.languages.ProtobufSchemaCodegen org.openapitools.codegen.languages.PythonLegacyClientCodegen org.openapitools.codegen.languages.PythonClientCodegen +org.openapitools.codegen.languages.PythonFastAPIServerCodegen org.openapitools.codegen.languages.PythonFlaskConnexionServerCodegen org.openapitools.codegen.languages.PythonAiohttpConnexionServerCodegen org.openapitools.codegen.languages.PythonBluePlanetServerCodegen @@ -131,3 +135,4 @@ org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen org.openapitools.codegen.languages.TypeScriptNodeClientCodegen org.openapitools.codegen.languages.TypeScriptReduxQueryClientCodegen org.openapitools.codegen.languages.TypeScriptRxjsClientCodegen +org.openapitools.codegen.languages.WsdlSchemaCodegen diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Project.csproj.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Project.csproj.mustache index 70f7388a9884..ee3ced7ba192 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Project.csproj.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Project.csproj.mustache @@ -7,6 +7,9 @@ true true {{packageVersion}} +{{#nullableReferenceTypes}} + annotations +{{/nullableReferenceTypes}} {{#isLibrary}} Library {{/isLibrary}} diff --git a/modules/openapi-generator/src/main/resources/bash/Dockerfile.mustache b/modules/openapi-generator/src/main/resources/bash/Dockerfile.mustache index b59e5a3665ac..d5d8a907a310 100644 --- a/modules/openapi-generator/src/main/resources/bash/Dockerfile.mustache +++ b/modules/openapi-generator/src/main/resources/bash/Dockerfile.mustache @@ -1,7 +1,6 @@ -FROM ubuntu:16.10 +FROM alpine:3.12.0 -RUN apt-get update -y && apt-get full-upgrade -y -RUN apt-get install -y bash-completion zsh curl cowsay git vim bsdmainutils +RUN apk add --update --no-cache curl ca-certificates bash bash-completion zsh curl git vim ncurses util-linux ADD {{scriptName}} /usr/bin/{{scriptName}} ADD _{{scriptName}} /usr/local/share/zsh/site-functions/_{{scriptName}} @@ -30,7 +29,7 @@ RUN echo 'export PROMPT="[{{appName}}] \$ "' >> ~/.zshrc # # Setup a welcome message with basic instruction # -RUN echo 'cat << EOF\n\ +RUN echo -e 'echo "\ \n\ This Docker provides preconfigured environment for running the command\n\ line REST client for $(tput setaf 6){{appName}}$(tput sgr0).\n\ @@ -63,7 +62,14 @@ $ {{scriptName}} -h\n\ By default you are logged into Zsh with full autocompletion for your REST API,\n\ but you can switch to Bash, where basic autocompletion is also supported.\n\ \n\ -EOF\n\ +"\ ' | tee -a ~/.bashrc ~/.zshrc -ENTRYPOINT ["zsh"] +# +# Poormans chsh & cleanup to make image as compact as possible +# + +RUN sed -i 's/root:x:0:0:root:\/root:\/bin\/ash/root:x:0:0:root:\/root:\/bin\/zsh/' /etc/passwd +RUN apk del git vim && rm -f /var/cache/apk/* + +ENTRYPOINT ["/bin/zsh"] diff --git a/modules/openapi-generator/src/main/resources/bash/client.mustache b/modules/openapi-generator/src/main/resources/bash/client.mustache index ff63a39c6004..3f5dcc0e2918 100644 --- a/modules/openapi-generator/src/main/resources/bash/client.mustache +++ b/modules/openapi-generator/src/main/resources/bash/client.mustache @@ -979,7 +979,7 @@ case $key in body_parameters[${body_key}]=${body_value} fi ;; - +\([^=]\):*) + +([^=]):*) # Parse header arguments and convert them into curl # only after the operation argument if [[ "$operation" ]]; then diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-header.mustache index 7beb0990a960..f614d478e96c 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-header.mustache @@ -14,24 +14,21 @@ #include #include {{^hasModelImport}}#include {{/hasModelImport}} +#include {{#imports}}{{{import}}} {{/imports}} -{{#apiNamespaceDeclarations}} -namespace {{this}} { -{{/apiNamespaceDeclarations}} - -{{#hasModelImport}} -using namespace {{modelNamespace}};{{/hasModelImport}} +namespace {{apiNamespace}} +{ class {{declspec}} {{classname}} { public: - {{classname}}(std::shared_ptr); - virtual ~{{classname}}() {} + explicit {{classname}}(const std::shared_ptr& rtr); + virtual ~{{classname}}() = default; void init(); - const std::string base = "{{basePathWithoutHost}}"; + static const std::string base; private: void setupRoutes(); @@ -41,9 +38,21 @@ private: {{/operation}} void {{classnameSnakeLowerCase}}_default_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response); - std::shared_ptr router; - {{#operation}} + const std::shared_ptr router; + + /// + /// Helper function to handle unexpected Exceptions during Parameter parsing and validation. + /// May be overriden to return custom error formats. + /// + virtual std::pair handleParsingException(const std::exception& ex) const noexcept; + /// + /// Helper function to handle unexpected Exceptions during processing of the request in handler functions. + /// May be overriden to return custom error formats. + /// + virtual std::pair handleOperationException(const std::exception& ex) const noexcept; + + {{#operation}} /// /// {{summary}} /// @@ -54,7 +63,7 @@ private: {{#allParams}} /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} {{/allParams}} - virtual void {{operationIdSnakeCase}}({{#allParams}}const {{{dataType}}} &{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}Pistache::Http::ResponseWriter &response) = 0; + virtual void {{operationIdSnakeCase}}({{#allParams}}const {{#isModel}}{{modelNamespace}}::{{/isModel}}{{{dataType}}} &{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}Pistache::Http::ResponseWriter &response) = 0; {{/vendorExtensions.x-codegen-pistache-is-parsing-supported}} {{^vendorExtensions.x-codegen-pistache-is-parsing-supported}} virtual void {{operationIdSnakeCase}}(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter &response) = 0; @@ -63,9 +72,7 @@ private: }; -{{#apiNamespaceDeclarations}} -} -{{/apiNamespaceDeclarations}} +} // namespace {{apiNamespace}} #endif /* {{classname}}_H_ */ diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-impl-header.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-impl-header.mustache index 18ff119ae208..bd20c1bdf5ab 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-impl-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-impl-header.mustache @@ -22,17 +22,16 @@ {{#imports}}{{{import}}} {{/imports}} -{{#apiNamespaceDeclarations}} -namespace {{this}} { -{{/apiNamespaceDeclarations}} +namespace {{apiNamespace}} +{ {{#hasModelImport}} using namespace {{modelNamespace}};{{/hasModelImport}} class {{classname}}Impl : public {{apiNamespace}}::{{classname}} { public: - {{classname}}Impl(std::shared_ptr); - ~{{classname}}Impl() {} + explicit {{classname}}Impl(const std::shared_ptr& rtr); + ~{{classname}}Impl() override = default; {{#operation}} {{#vendorExtensions.x-codegen-pistache-is-parsing-supported}} @@ -45,11 +44,9 @@ public: }; -{{#apiNamespaceDeclarations}} -} -{{/apiNamespaceDeclarations}} +} // namespace {{apiNamespace}} {{/operations}} -#endif \ No newline at end of file +#endif diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-impl-source.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-impl-source.mustache index e5517bb487c1..2e25a8034b30 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-impl-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-impl-source.mustache @@ -10,9 +10,10 @@ namespace {{this}} { {{#hasModelImport}} using namespace {{modelNamespace}};{{/hasModelImport}} -{{classname}}Impl::{{classname}}Impl(std::shared_ptr rtr) +{{classname}}Impl::{{classname}}Impl(const std::shared_ptr& rtr) : {{classname}}(rtr) - { } +{ +} {{#operation}} {{#vendorExtensions.x-codegen-pistache-is-parsing-supported}} @@ -31,4 +32,4 @@ void {{classname}}Impl::{{operationIdSnakeCase}}(const Pistache::Rest::Request & } {{/apiNamespaceDeclarations}} -{{/operations}} \ No newline at end of file +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-source.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-source.mustache index 9225a5610c70..9814ba0cd626 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-source.mustache @@ -4,16 +4,18 @@ #include "{{classname}}.h" #include "{{prefix}}Helpers.h" -{{#apiNamespaceDeclarations}} -namespace {{this}} { -{{/apiNamespaceDeclarations}} +namespace {{apiNamespace}} +{ using namespace {{helpersNamespace}}; {{#hasModelImport}} using namespace {{modelNamespace}};{{/hasModelImport}} -{{classname}}::{{classname}}(std::shared_ptr rtr) { - router = rtr; +const std::string {{classname}}::base = "{{basePathWithoutHost}}"; + +{{classname}}::{{classname}}(const std::shared_ptr& rtr) + : router(rtr) +{ } void {{classname}}::init() { @@ -31,8 +33,26 @@ void {{classname}}::setupRoutes() { router->addCustomHandler(Routes::bind(&{{classname}}::{{classnameSnakeLowerCase}}_default_handler, this)); } +std::pair {{classname}}::handleParsingException(const std::exception& ex) const noexcept +{ + try { + throw ex; + } catch (nlohmann::detail::exception &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } catch ({{helpersNamespace}}::ValidationException &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } +} + +std::pair {{classname}}::handleOperationException(const std::exception& ex) const noexcept +{ + return std::make_pair(Pistache::Http::Code::Internal_Server_Error, ex.what()); +} + {{#operation}} void {{classname}}::{{operationIdSnakeCase}}_handler(const Pistache::Rest::Request &{{#hasParams}}request{{/hasParams}}, Pistache::Http::ResponseWriter response) { + try { + {{#vendorExtensions.x-codegen-pistache-is-parsing-supported}} {{#hasPathParams}} // Getting the path params @@ -71,32 +91,40 @@ void {{classname}}::{{operationIdSnakeCase}}_handler(const Pistache::Rest::Reque {{#hasBodyParam}} {{#bodyParam}} {{^isPrimitiveType}} - nlohmann::json::parse(request.body()).get_to({{paramName}}); + nlohmann::json::parse(request.body()).get_to({{paramName}}); + {{paramName}}.validate(); {{/isPrimitiveType}} {{#isPrimitiveType}} - {{paramName}} = request.body(); + {{paramName}} = request.body(); {{/isPrimitiveType}} + } catch (std::exception &e) { + const std::pair errorInfo = this->handleParsingException(e); + response.send(errorInfo.first, errorInfo.second); + return; + } + + try { {{/bodyParam}} {{/hasBodyParam}} - this->{{operationIdSnakeCase}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}response); + this->{{operationIdSnakeCase}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}response); {{/vendorExtensions.x-codegen-pistache-is-parsing-supported}} {{^vendorExtensions.x-codegen-pistache-is-parsing-supported}} try { this->{{operationIdSnakeCase}}(request, response); {{/vendorExtensions.x-codegen-pistache-is-parsing-supported}} - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } {{/operation}} @@ -104,8 +132,6 @@ void {{classname}}::{{classnameSnakeLowerCase}}_default_handler(const Pistache:: response.send(Pistache::Http::Code::Not_Found, "The requested method does not exist"); } -{{#apiNamespaceDeclarations}} -} -{{/apiNamespaceDeclarations}} +} // namespace {{apiNamespace}} {{/operations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/helpers-header.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/helpers-header.mustache index c39cca04fe10..d3489fad4026 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/helpers-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/helpers-header.mustache @@ -14,16 +14,80 @@ #include #include -{{#helpersNamespaceDeclarations}} -namespace {{this}} { -{{/helpersNamespaceDeclarations}} +namespace {{helpersNamespace}} +{ + + class ValidationException : public std::runtime_error + { + public: + explicit ValidationException(const std::string& what) + : std::runtime_error(what) + { } + ~ValidationException() override = default; + }; + + /// + /// Validate a string against the full-date definition of RFC 3339, section 5.6. + /// + bool validateRfc3339_date(const std::string& str); + + /// + /// Validate a string against the date-time definition of RFC 3339, section 5.6. + /// + bool validateRfc3339_date_time(const std::string& str); + + namespace sfinae_helpers + { + struct NoType {}; + template NoType operator==(const T1&, const T2&); + + template class EqualsOperatorAvailable + { + public: + enum + { + value = !std::is_same< decltype(std::declval() == std::declval()), NoType >::value + }; + }; + } // namespace sfinae_helpers + + + /// + /// Determine if the given vector only has unique elements. T must provide the == operator. + /// + template + bool hasOnlyUniqueItems(const std::vector& vec) + { + static_assert(sfinae_helpers::EqualsOperatorAvailable::value, + "hasOnlyUniqueItems cannot be called, passed template type does not provide == operator."); + if (vec.size() <= 1) + { + return true; + } + // Compare every element of vec to every other element of vec. + // This isn't an elegant way to do this, since it's O(n^2), + // but it's the best solution working only with the == operator. + // This could be greatly improved if our models provided a valid hash + // and/or the < operator + for (size_t i = 0; i < vec.size() - 1; i++) + { + for (size_t j = i + 1; j < vec.size(); j++) + { + if (vec[i] == vec[j]) + { + return false; + } + } + } + return true; + } std::string toStringValue(const std::string &value); - std::string toStringValue(const int32_t &value); - std::string toStringValue(const int64_t &value); - std::string toStringValue(const bool &value); - std::string toStringValue(const float &value); - std::string toStringValue(const double &value); + std::string toStringValue(const int32_t value); + std::string toStringValue(const int64_t value); + std::string toStringValue(const bool value); + std::string toStringValue(const float value); + std::string toStringValue(const double value); bool fromStringValue(const std::string &inStr, std::string &value); bool fromStringValue(const std::string &inStr, int32_t &value); @@ -57,8 +121,6 @@ namespace {{this}} { return fromStringValue(inStrings, value); } -{{#helpersNamespaceDeclarations}} -} -{{/helpersNamespaceDeclarations}} +} // namespace {{helpersNamespace}} -#endif // {{prefix}}Helpers_H_ \ No newline at end of file +#endif // {{prefix}}Helpers_H_ diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/helpers-source.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/helpers-source.mustache index 82b4e2d81ef6..214086354d51 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/helpers-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/helpers-source.mustache @@ -1,32 +1,74 @@ {{>licenseInfo}} #include "{{prefix}}Helpers.h" +#include -{{#helpersNamespaceDeclarations}} -namespace {{this}} { -{{/helpersNamespaceDeclarations}} +namespace {{helpersNamespace}} +{ +const std::regex regexRfc3339_date(R"(^(\d{4})\-(\d{2})\-(\d{2})$)"); +const std::regex regexRfc3339_date_time( + R"(^(\d{4})\-(\d{2})\-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(\.\d+)?([Zz]|([\+\-])(\d{2}):(\d{2}))$)" +); + + +namespace +{ + // Determine if given year is a leap year + // See RFC 3339, Appendix C https://tools.ietf.org/html/rfc3339#appendix-C + bool isLeapYear(const uint16_t year) { + return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)); + } + + bool validateDateValues(const uint16_t year, const uint16_t month, const uint16_t day) { + return !( + (month == 0 || month > 12) + || (day == 0) + || (month == 2 && day > (28 + (isLeapYear(year) ? 1 : 0))) + || (month <= 7 && day > (30 + month % 2)) + || (month >= 8 && day > (31 - month % 2)) + ); + } + + bool validateTimeValues(const uint16_t hours, const uint16_t minutes, const uint16_t seconds) { + return (hours <= 23) && (minutes <= 59) && (seconds <= 60); + } +} + +bool validateRfc3339_date(const std::string& str) { + std::smatch match; + const bool found = std::regex_search(str, match, regexRfc3339_date); + return found && validateDateValues(std::stoi(match[1]), std::stoi(match[2]), std::stoi(match[3])); +} + +bool validateRfc3339_date_time(const std::string& str) { + std::smatch match; + const bool found = std::regex_search(str, match, regexRfc3339_date_time); + return found + && validateDateValues(std::stoi(match[1]), std::stoi(match[2]), std::stoi(match[3])) + && validateTimeValues(std::stoi(match[4]), std::stoi(match[5]), std::stoi(match[6])); +} std::string toStringValue(const std::string &value){ return std::string(value); } -std::string toStringValue(const int32_t &value){ +std::string toStringValue(const int32_t value){ return std::to_string(value); } -std::string toStringValue(const int64_t &value){ +std::string toStringValue(const int64_t value){ return std::to_string(value); } -std::string toStringValue(const bool &value){ - return value?std::string("true"):std::string("false"); +std::string toStringValue(const bool value){ + return value ? std::string("true") : std::string("false"); } -std::string toStringValue(const float &value){ +std::string toStringValue(const float value){ return std::to_string(value); } -std::string toStringValue(const double &value){ +std::string toStringValue(const double value){ return std::to_string(value); } @@ -56,9 +98,15 @@ bool fromStringValue(const std::string &inStr, int64_t &value){ } bool fromStringValue(const std::string &inStr, bool &value){ - bool result = true; - inStr == "true"?value = true: inStr == "false"?value = false: result = false; - return result; + if (inStr == "true") { + value = true; + return true; + } + if (inStr == "false") { + value = false; + return true; + } + return false; } bool fromStringValue(const std::string &inStr, float &value){ @@ -81,6 +129,4 @@ bool fromStringValue(const std::string &inStr, double &value){ return true; } -{{#helpersNamespaceDeclarations}} -} -{{/helpersNamespaceDeclarations}} \ No newline at end of file +} // namespace {{helpersNamespace}} diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-header.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-header.mustache index c16fdbb09467..cb6d8d98ee06 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-header.mustache @@ -13,9 +13,8 @@ {{/imports}} #include -{{#modelNamespaceDeclarations}} -namespace {{this}} { -{{/modelNamespaceDeclarations}} +namespace {{modelNamespace}} +{ /// /// {{description}} @@ -24,7 +23,7 @@ class {{declspec}} {{classname}} { public: {{classname}}(); - virtual ~{{classname}}(); + virtual ~{{classname}}() = default; {{#isEnum}}{{#allowableValues}} enum class e{{classname}} { // To have a valid default value. @@ -35,7 +34,20 @@ public: {{{name}}}{{^-last}}, {{/-last}} {{/enumVars}} };{{/allowableValues}}{{/isEnum}} - void validate(); + + /// + /// Validate the current data in the model. Throws a ValidationException on failure. + /// + void validate() const; + + /// + /// Validate the current data in the model. Returns false on error and writes an error + /// message into the given stringstream. + /// + bool validate(std::stringstream& msg) const; + + bool operator==(const {{classname}}& rhs) const; + bool operator!=(const {{classname}}& rhs) const; ///////////////////////////////////////////// /// {{classname}} members @@ -44,7 +56,7 @@ public: /// /// {{description}} /// - {{{dataType}}}{{#isContainer}}&{{/isContainer}} {{getter}}(){{^isContainer}} const{{/isContainer}}; + {{{dataType}}} {{getter}}() const; void {{setter}}({{{dataType}}} const{{^isPrimitiveType}}&{{/isPrimitiveType}} value);{{^required}} bool {{nameInCamelCase}}IsSet() const; void unset{{name}}();{{/required}} @@ -65,11 +77,12 @@ protected: {{#isEnum}} {{classname}}::e{{classname}} m_value = {{classname}}::e{{classname}}::INVALID_VALUE_OPENAPI_GENERATED; {{/isEnum}} + + // Helper overload for validate. Used when one model stores another model and calls it's validate. + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; }; -{{#modelNamespaceDeclarations}} -} -{{/modelNamespaceDeclarations}} +} // namespace {{modelNamespace}} #endif /* {{classname}}_H_ */ {{/model}} diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-source.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-source.mustache index d603dc2186e0..8ef6abf0e4c5 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-source.mustache @@ -2,12 +2,12 @@ {{#models}}{{#model}} #include "{{classname}}.h" -{{#isEnum}}#include -#include {{/isEnum}} +#include "{{prefix}}Helpers.h" +{{#isEnum}}#include {{/isEnum}} +#include -{{#modelNamespaceDeclarations}} -namespace {{this}} { -{{/modelNamespaceDeclarations}} +namespace {{modelNamespace}} +{ {{classname}}::{{classname}}() { @@ -18,13 +18,69 @@ namespace {{this}} { {{/required}}{{/vars}} } -{{classname}}::~{{classname}}() +void {{classname}}::validate() const { + std::stringstream msg; + if (!validate(msg)) + { + throw {{helpersNamespace}}::ValidationException(msg.str()); + } } -void {{classname}}::validate() +bool {{classname}}::validate(std::stringstream& msg) const { - // TODO: implement validation + return validate(msg, ""); +} + +bool {{classname}}::validate(std::stringstream& msg, const std::string& pathPrefix) const +{ + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "{{classname}}" : pathPrefix; + + {{#isEnum}}{{! Special case for enum types }} + if (m_value == {{classname}}::e{{classname}}::INVALID_VALUE_OPENAPI_GENERATED) + { + success = false; + msg << _pathPrefix << ": has no value;"; + } + {{/isEnum}} + {{^isEnum}} + {{#vars}} + {{#isArray}} {{! Always generate validation body for array types }} + {{^required}}if ({{nameInCamelCase}}IsSet()){{/required}} + {{#required}}/* {{name}} */ {{/required}}{ + const {{{dataType}}}& value = m_{{name}}; + const std::string currentValuePath = _pathPrefix + ".{{nameInCamelCase}}"; + {{> model-validation-body }} + } + {{/isArray}}{{^isArray}}{{#hasValidation}} {{! Only generate validation if necessary }} + {{^required}}if ({{nameInCamelCase}}IsSet()){{/required}} + {{#required}}/* {{name}} */ {{/required}}{ + const {{{dataType}}}& value = m_{{name}}; + const std::string currentValuePath = _pathPrefix + ".{{nameInCamelCase}}"; + {{> model-validation-body }} + } + {{/hasValidation}}{{/isArray}} + {{/vars}} + {{/isEnum}} + + return success; +} + +bool {{classname}}::operator==(const {{classname}}& rhs) const +{ + return + {{#isEnum}}getValue() == rhs.getValue(){{/isEnum}} + {{^isEnum}}{{#vars}} + {{#required}}({{getter}}() == rhs.{{getter}}()){{/required}} + {{^required}}((!{{nameInCamelCase}}IsSet() && !rhs.{{nameInCamelCase}}IsSet()) || ({{nameInCamelCase}}IsSet() && rhs.{{nameInCamelCase}}IsSet() && {{getter}}() == rhs.{{getter}}())){{/required}}{{^-last}} &&{{/-last}} + {{/vars}}{{/isEnum}} + ; +} + +bool {{classname}}::operator!=(const {{classname}}& rhs) const +{ + return !(*this == rhs); } void to_json(nlohmann::json& j, const {{classname}}& o) @@ -74,7 +130,7 @@ void from_json(const nlohmann::json& j, {{classname}}& o) {{/enumVars}}{{/allowableValues}}{{/isEnum}} } -{{#vars}}{{{dataType}}}{{#isContainer}}&{{/isContainer}} {{classname}}::{{getter}}(){{^isContainer}} const{{/isContainer}} +{{#vars}}{{{dataType}}} {{classname}}::{{getter}}() const { return m_{{name}}; } @@ -102,9 +158,7 @@ void {{classname}}::setValue({{classname}}::e{{classname}} value) m_value = value; }{{/isEnum}} -{{#modelNamespaceDeclarations}} -} -{{/modelNamespaceDeclarations}} +} // namespace {{modelNamespace}} {{/model}} {{/models}} diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-header.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-header.mustache index bcc64257e409..be0ea874da8e 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-header.mustache @@ -14,9 +14,8 @@ #include {{#hasOptional}}#include {{/hasOptional}} -{{#modelNamespaceDeclarations}} -namespace {{this}} { -{{/modelNamespaceDeclarations}} +namespace {{modelNamespace}} +{ struct {{classname}} { @@ -34,9 +33,9 @@ struct {{classname}} void to_json(nlohmann::json& j, const {{classname}}& o); void from_json(const nlohmann::json& j, {{classname}}& o); -{{#modelNamespaceDeclarations}} -} // {{this}} -{{/modelNamespaceDeclarations}} + +} // namespace {{modelNamespace}} + #endif /* {{classname}}_H_ */ {{/model}} diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-source.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-source.mustache index 52d3526e867a..987926b7c4eb 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-struct-source.mustache @@ -3,9 +3,8 @@ #include "{{classname}}.h" -{{#modelNamespaceDeclarations}} -namespace {{this}} { -{{/modelNamespaceDeclarations}} +namespace {{modelNamespace}} +{ nlohmann::json {{classname}}::to_json() const { @@ -51,9 +50,7 @@ void from_json(const nlohmann::json& j, {{classname}}& o) {{/vars}} } -{{#modelNamespaceDeclarations}} -} // {{this}} -{{/modelNamespaceDeclarations}} +} // namespace {{modelNamespace}} {{/model}} {{/models}} diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-validation-body.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-validation-body.mustache new file mode 100644 index 000000000000..ef92f2c3fbd4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-validation-body.mustache @@ -0,0 +1,124 @@ +{{! +This template generates the validation logic for a model. +This template file calls itself recursively for arrays. +}} +{{! Check for eunm properties that are their own schema }} +{{! These are in their own class with a validate function, the way to check for this is quite a hack +since isEnum, isString and isModel are all false. }} + {{^isString}}{{#allowableValues.enumVars.0.value}} + success = value.validate(msg, currentValuePath) && success; + {{/allowableValues.enumVars.0.value}}{{/isString}} + {{#isModel}}success = value.validate(msg, currentValuePath + ".{{nameInCamelCase}}") && success;{{/isModel}} +{{! Date validation }} + {{#isDate}} + if (!{{helpersNamespace}}::validateRfc3339_date(value)) + { + success = false; + msg << currentValuePath << ": must be a valid RFC 3339 date-full string;"; + } + {{/isDate}} +{{! Date-Time validation }} + {{#isDateTime}} + if (!{{helpersNamespace}}::validateRfc3339_date_time(value)) + { + success = false; + msg << currentValuePath << ": must be a valid RFC 3339 date-time string;"; + } + {{/isDateTime}} +{{! string validation }} + {{#isString}} + {{#minLength}} + if (value.length() < {{minLength}}) + { + success = false; + msg << currentValuePath << ": must be at least {{minLength}} characters long;"; + } + {{/minLength}} + {{#maxLength}} + if (value.length() > {{maxLength}}) + { + success = false; + msg << currentValuePath << ": must be at most {{maxLength}} characters long;"; + } + {{/maxLength}} +{{! +TODO validate regex of string using pattern variable. This has two challenges + - Is compatibility with the given regex pattern guaranteed? + - Creating the std::regex on every validation would be rather slow. Ideally one would + initialize them for the class once as a static const and use them. +}} +{{! string encoded enum validation }} + {{#isEnum}} + {{#allowableValues}} + if ({{#enumVars}} + value != "{{value}}"{{^-last}} &&{{/-last}}{{/enumVars}} + ) { + success = false; + msg << currentValuePath << ": has invalid value \"" << value << "\";"; + } + {{/allowableValues}} + {{/isEnum}} + {{/isString}} +{{! numeric validation }} + {{#isNumeric}} + {{#minimum}} + if (value <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{#isFloat}}static_cast({{/isFloat}}{{minimum}}{{#isFloat}}){{/isFloat}}{{#isLong}}ll{{/isLong}}) + { + success = false; + msg << currentValuePath << ": must be greater than{{^exclusiveMinimum}} or equal to{{/exclusiveMinimum}} {{minimum}};"; + } + {{/minimum}} + {{#maximum}} + if (value >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{#isFloat}}static_cast({{/isFloat}}{{maximum}}{{#isFloat}}){{/isFloat}}{{#isLong}}ll{{/isLong}}) + { + success = false; + msg << currentValuePath << ": must be less than{{^exclusiveMaximum}} or equal to{{/exclusiveMaximum}} {{maximum}};"; + } + {{/maximum}} + {{#multipleOf}} + {{#isInteger}}if (value % {{multipleOf}}{{#isLong}}ll{{/isLong}} != 0){{/isInteger}} + {{#isFloat}}if (std::fmod(value, static_cast({{multipleOf}})) != 0){{/isFloat}} + {{#isDouble}}if (std::fmod(value, {{multipleOf}}) != 0){{/isDouble}} + { + success = false; + msg << currentValuePath << ": must be a multiple of {{multipleOf}};"; + } + {{/multipleOf}} + {{/isNumeric}} +{{! Array validation }} + {{#isArray}} + {{#minItems}} + if (value.size() < {{minItems}}) + { + success = false; + msg << currentValuePath << ": must have at least {{minItems}} elements;"; + } + {{/minItems}} + {{#maxItems}} + if (value.size() > {{maxItems}}) + { + success = false; + msg << currentValuePath << ": must have at most {{maxItems}} elements;"; + } + {{/maxItems}} + {{#uniqueItems}} + if (!{{helpersNamespace}}::hasOnlyUniqueItems(value)) + { + success = false; + msg << currentValuePath << ": may not contain the same item more than once;"; + } + {{/uniqueItems}} + { // Recursive validation of array elements + const std::string oldValuePath = currentValuePath; + int i = 0; + {{! the element var has the same name as the vector, so that the recursive template works - what a wonderful hack }} + for (const {{{items.dataType}}}& value : value) + { {{! and I do a similar hack with currentValuePath... }} + const std::string currentValuePath = oldValuePath + "[" + std::to_string(i) + "]"; + {{#items}} + {{> model-validation-body }} {{! Recursively apply template to array - this is where things will probbaly go wrong }} + {{/items}} + i++; + } + } + {{/isArray}} diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/CMakeLists.txt.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/CMakeLists.txt.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/CMakeLists.txt.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/CMakeLists.txt.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpFileElement.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpFileElement.cpp.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpFileElement.cpp.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/HttpFileElement.cpp.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpFileElement.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpFileElement.h.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpFileElement.h.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/HttpFileElement.h.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.cpp.mustache similarity index 99% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.cpp.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.cpp.mustache index 5eca0f0f0a4b..bf88363b51cf 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.cpp.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.cpp.mustache @@ -328,7 +328,7 @@ void {{prefix}}HttpRequestWorker::execute({{prefix}}HttpRequestInput *input) { if ({{prefix}}HttpRequestWorker::sslDefaultConfiguration != nullptr) { request.setSslConfiguration(*{{prefix}}HttpRequestWorker::sslDefaultConfiguration); } - request.setRawHeader("User-Agent", "{{#httpUserAgent}}{{.}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{apiVersion}}/cpp-qt5{{/httpUserAgent}}"); + request.setRawHeader("User-Agent", "{{#httpUserAgent}}{{.}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{apiVersion}}/cpp-qt{{/httpUserAgent}}"); foreach (QString key, input->headers.keys()) { request.setRawHeader(key.toStdString().c_str(), input->headers.value(key).toStdString().c_str()); } if (request_content.size() > 0 && !isFormData && (input->var_layout != MULTIPART)) { diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.h.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.h.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.h.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/Project.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/Project.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/Project.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/Project.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/README.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/README.mustache similarity index 98% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/README.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/README.mustache index 5f3194575328..9692bf79152c 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/README.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-client/README.mustache @@ -53,10 +53,10 @@ At first generate the JAR by executing: mvn clean package ``` -Use the Jar file to generate the Qt5 Client: +Use the Jar file to generate the Qt Client: ```shell -java -jar target/openapi-generator-cli.jar generate -i -g cpp-qt5-client -o +java -jar target/openapi-generator-cli.jar generate -i -g cpp-qt-client -o ``` ## Getting Started diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/ServerConfiguration.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/ServerConfiguration.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/ServerConfiguration.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/ServerConfiguration.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/ServerVariable.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/ServerVariable.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/ServerVariable.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/ServerVariable.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/api-body.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/api-body.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/api-body.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/api-body.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/api-header.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/api-header.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/api-header.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/enum.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/enum.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/enum.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/enum.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/helpers-body.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/helpers-body.mustache similarity index 69% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/helpers-body.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/helpers-body.mustache index a4c04a8951c0..0661117b0abf 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/helpers-body.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-client/helpers-body.mustache @@ -9,47 +9,83 @@ namespace {{this}} { class {{prefix}}SerializerSettings { public: - static void setDateTimeFormat(const QString & dtFormat){ - getInstance()->dateTimeFormat = dtFormat; + struct CustomDateTimeFormat{ + bool isStringSet = false; + QString formatString; + bool isEnumSet = false; + Qt::DateFormat formatEnum; + }; + + static CustomDateTimeFormat getCustomDateTimeFormat() { + return getInstance()->customDateTimeFormat; } - static QString getDateTimeFormat() { - return getInstance()->dateTimeFormat; + + static void setDateTimeFormatString(const QString &dtFormat){ + getInstance()->customDateTimeFormat.isStringSet = true; + getInstance()->customDateTimeFormat.isEnumSet = false; + getInstance()->customDateTimeFormat.formatString = dtFormat; + } + + static void setDateTimeFormatEnum(const Qt::DateFormat &dtFormat){ + getInstance()->customDateTimeFormat.isEnumSet = true; + getInstance()->customDateTimeFormat.isStringSet = false; + getInstance()->customDateTimeFormat.formatEnum = dtFormat; } + static {{prefix}}SerializerSettings *getInstance(){ if(instance == nullptr){ instance = new {{prefix}}SerializerSettings(); } return instance; } + private: explicit {{prefix}}SerializerSettings(){ instance = this; - dateTimeFormat.clear(); + customDateTimeFormat.isStringSet = false; + customDateTimeFormat.isEnumSet = false; } static {{prefix}}SerializerSettings *instance; - QString dateTimeFormat; + CustomDateTimeFormat customDateTimeFormat; }; {{prefix}}SerializerSettings * {{prefix}}SerializerSettings::instance = nullptr; -bool setDateTimeFormat(const QString& dateTimeFormat){ +bool setDateTimeFormat(const QString &dateTimeFormat){ bool success = false; auto dt = QDateTime::fromString(QDateTime::currentDateTime().toString(dateTimeFormat), dateTimeFormat); - if(dt.isValid()){ + if (dt.isValid()) { success = true; - {{prefix}}SerializerSettings::setDateTimeFormat(dateTimeFormat); + {{prefix}}SerializerSettings::setDateTimeFormatString(dateTimeFormat); } return success; } +bool setDateTimeFormat(const Qt::DateFormat &dateTimeFormat){ + bool success = false; + auto dt = QDateTime::fromString(QDateTime::currentDateTime().toString(dateTimeFormat), dateTimeFormat); + if (dt.isValid()) { + success = true; + {{prefix}}SerializerSettings::setDateTimeFormatEnum(dateTimeFormat); + } + return success; +} QString toStringValue(const QString &value) { return value; } QString toStringValue(const QDateTime &value) { + if ({{prefix}}SerializerSettings::getInstance()->getCustomDateTimeFormat().isStringSet) { + return value.toString({{prefix}}SerializerSettings::getInstance()->getCustomDateTimeFormat().formatString); + } + + if ({{prefix}}SerializerSettings::getInstance()->getCustomDateTimeFormat().isEnumSet) { + return value.toString({{prefix}}SerializerSettings::getInstance()->getCustomDateTimeFormat().formatEnum); + } + // ISO 8601 - return {{prefix}}SerializerSettings::getInstance()->getDateTimeFormat().isEmpty()? value.toString(Qt::ISODate):value.toString({{prefix}}SerializerSettings::getInstance()->getDateTimeFormat()); + return value.toString(Qt::ISODate); } QString toStringValue(const QByteArray &value) { @@ -98,7 +134,16 @@ QJsonValue toJsonValue(const QString &value) { } QJsonValue toJsonValue(const QDateTime &value) { - return QJsonValue(value.toString({{prefix}}SerializerSettings::getInstance()->getDateTimeFormat().isEmpty()?value.toString(Qt::ISODate):value.toString({{prefix}}SerializerSettings::getInstance()->getDateTimeFormat()))); + if ({{prefix}}SerializerSettings::getInstance()->getCustomDateTimeFormat().isStringSet) { + return QJsonValue(value.toString({{prefix}}SerializerSettings::getInstance()->getCustomDateTimeFormat().formatString)); + } + + if ({{prefix}}SerializerSettings::getInstance()->getCustomDateTimeFormat().isEnumSet) { + return QJsonValue(value.toString({{prefix}}SerializerSettings::getInstance()->getCustomDateTimeFormat().formatEnum)); + } + + // ISO 8601 + return QJsonValue(value.toString(Qt::ISODate)); } QJsonValue toJsonValue(const QByteArray &value) { @@ -151,7 +196,15 @@ bool fromStringValue(const QString &inStr, QDateTime &value) { if (inStr.isEmpty()) { return false; } else { - auto dateTime = {{prefix}}SerializerSettings::getInstance()->getDateTimeFormat().isEmpty()?QDateTime::fromString(inStr, Qt::ISODate) :QDateTime::fromString(inStr, {{prefix}}SerializerSettings::getInstance()->getDateTimeFormat()); + QDateTime dateTime; + if ({{prefix}}SerializerSettings::getInstance()->getCustomDateTimeFormat().isStringSet) { + dateTime = QDateTime::fromString(inStr, {{prefix}}SerializerSettings::getInstance()->getCustomDateTimeFormat().formatString); + } else if ({{prefix}}SerializerSettings::getInstance()->getCustomDateTimeFormat().isEnumSet) { + dateTime = QDateTime::fromString(inStr, {{prefix}}SerializerSettings::getInstance()->getCustomDateTimeFormat().formatEnum); + } else { + dateTime = QDateTime::fromString(inStr, Qt::ISODate); + } + if (dateTime.isValid()) { value.setDate(dateTime.date()); value.setTime(dateTime.time()); @@ -256,7 +309,13 @@ bool fromJsonValue(QString &value, const QJsonValue &jval) { bool fromJsonValue(QDateTime &value, const QJsonValue &jval) { bool ok = true; if (!jval.isUndefined() && !jval.isNull() && jval.isString()) { - value = {{prefix}}SerializerSettings::getInstance()->getDateTimeFormat().isEmpty()?QDateTime::fromString(jval.toString(), Qt::ISODate): QDateTime::fromString(jval.toString(), {{prefix}}SerializerSettings::getInstance()->getDateTimeFormat()); + if ({{prefix}}SerializerSettings::getInstance()->getCustomDateTimeFormat().isStringSet) { + value = QDateTime::fromString(jval.toString(), {{prefix}}SerializerSettings::getInstance()->getCustomDateTimeFormat().formatString); + } else if ({{prefix}}SerializerSettings::getInstance()->getCustomDateTimeFormat().isEnumSet) { + value = QDateTime::fromString(jval.toString(), {{prefix}}SerializerSettings::getInstance()->getCustomDateTimeFormat().formatEnum); + } else { + value = QDateTime::fromString(jval.toString(), Qt::ISODate); + } ok = value.isValid(); } else { ok = false; diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-header.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/helpers-header.mustache similarity index 98% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-header.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/helpers-header.mustache index 96e3349fa475..6b0ad489b1cb 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-client/helpers-header.mustache @@ -42,7 +42,8 @@ public: } }; -bool setDateTimeFormat(const QString&); +bool setDateTimeFormat(const QString &format); +bool setDateTimeFormat(const Qt::DateFormat &format); template QString toStringValue(const QList &val); diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/licenseInfo.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/licenseInfo.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/licenseInfo.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/model-body.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/model-body.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/model-body.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/model-body.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/model-header.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/model-header.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/model-header.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/model-header.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/object.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/object.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/object.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/object.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/CMakeLists.txt.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/CMakeLists.txt.mustache similarity index 93% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/CMakeLists.txt.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/CMakeLists.txt.mustache index 54e6d36d73fe..71b8bdb45f41 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/CMakeLists.txt.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/CMakeLists.txt.mustache @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.2 FATAL_ERROR) -project(cpp-qt5-qhttpengine-server) +project(cpp-qt-qhttpengine-server) include(ExternalProject) diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/Dockerfile.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/Dockerfile.mustache similarity index 78% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/Dockerfile.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/Dockerfile.mustache index b0c591d10f65..9dfdd9ab4785 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/Dockerfile.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/Dockerfile.mustache @@ -23,7 +23,7 @@ RUN apk add --update \ openssl WORKDIR /usr/server -COPY --from=build /usr/server/build/src/cpp-qt5-qhttpengine-server ./build/src/ +COPY --from=build /usr/server/build/src/cpp-qt-qhttpengine-server ./build/src/ COPY --from=build /usr/server/external/ ./external EXPOSE 8080/tcp -ENTRYPOINT ["/usr/server/build/src/cpp-qt5-qhttpengine-server"] \ No newline at end of file +ENTRYPOINT ["/usr/server/build/src/cpp-qt-qhttpengine-server"] diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/HttpFileElement.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/HttpFileElement.cpp.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/HttpFileElement.cpp.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/HttpFileElement.cpp.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/HttpFileElement.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/HttpFileElement.h.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/HttpFileElement.h.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/HttpFileElement.h.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/LICENSE.txt.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/LICENSE.txt.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/LICENSE.txt.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/LICENSE.txt.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/Makefile.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/Makefile.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/Makefile.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/Makefile.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/README.md.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/README.md.mustache similarity index 89% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/README.md.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/README.md.mustache index e5439dcae3b9..68ec6bf4369a 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/README.md.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/README.md.mustache @@ -1,6 +1,6 @@ -# C++ Qt5 Server +# C++ Qt Server -## Qt5 HTTP Server based on the Qhttpengine +## Qt HTTP Server based on the Qhttpengine This server was generated by the [openapi-generator](https://openapi-generator.tech) project. By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. @@ -50,18 +50,18 @@ make To run the server ```shell -./build/src/cpp-qt5-qhttpengine-server & +./build/src/cpp-qt-qhttpengine-server & ``` To override the default port via the command line, provide the parameters `port` and `address` like below ```shell -cpp-qt5-qhttpengine-server --port 9080 --address 127.17.0.1 +cpp-qt-qhttpengine-server --port 9080 --address 127.17.0.1 ``` or ```shell -cpp-qt5-qhttpengine-server -p 9080 -a 127.17.0.1 +cpp-qt-qhttpengine-server -p 9080 -a 127.17.0.1 ``` #### Invoke an API @@ -80,13 +80,13 @@ If you dont have docker install [here](https://docs.docker.com/install) Add yourself to the docker group ```shell -docker build --network=host -t cpp-qt5-qhttpengine-server . +docker build --network=host -t cpp-qt-qhttpengine-server . ``` Running with docker ```shell -docker run --rm -it --name=server-container cpp-qt5-qhttpengine-server +docker run --rm -it --name=server-container cpp-qt-qhttpengine-server ``` #### Invoking an API diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apihandler.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apihandler.cpp.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apihandler.cpp.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apihandler.cpp.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apihandler.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apihandler.h.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apihandler.h.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apihandler.h.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirequest.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirequest.cpp.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirequest.cpp.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirequest.cpp.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirequest.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirequest.h.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirequest.h.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirequest.h.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirouter.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirouter.cpp.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirouter.cpp.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirouter.cpp.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirouter.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirouter.h.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirouter.h.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirouter.h.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/enum.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/enum.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/enum.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/enum.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-body.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/helpers-body.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-body.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/helpers-body.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/helpers-header.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/helpers-header.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/helpers-header.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/helpers-header.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/licenseInfo.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/licenseInfo.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/licenseInfo.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/main.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/main.cpp.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/main.cpp.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/main.cpp.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/model-body.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/model-body.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/model-body.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/model-body.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/model-header.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/model-header.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/model-header.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/model-header.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/object.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/object.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/object.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/object.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/src-CMakeLists.txt.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/src-CMakeLists.txt.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/src-CMakeLists.txt.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/src-CMakeLists.txt.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/modelbase-source.mustache b/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/modelbase-source.mustache index cfe9c44feccc..faa2333603a4 100644 --- a/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/modelbase-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/modelbase-source.mustache @@ -249,13 +249,13 @@ bool ModelBase::fromJson( const web::json::value& val, bool & outVal ) } bool ModelBase::fromJson( const web::json::value& val, float & outVal ) { - outVal = !val.is_double() ? std::numeric_limits::quiet_NaN(): static_cast(val.as_double()); - return val.is_double(); + outVal = (!val.is_double() && !val.is_integer()) ? std::numeric_limits::quiet_NaN(): static_cast(val.as_double()); + return val.is_double() || val.is_integer(); } bool ModelBase::fromJson( const web::json::value& val, double & outVal ) { - outVal = !val.is_double() ? std::numeric_limits::quiet_NaN(): val.as_double(); - return val.is_double() ; + outVal = (!val.is_double() && !val.is_integer()) ? std::numeric_limits::quiet_NaN(): val.as_double(); + return val.is_double() || val.is_integer(); } bool ModelBase::fromJson( const web::json::value& val, int32_t & outVal ) { diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/README.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/README.mustache new file mode 100644 index 000000000000..e749562a0aa3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/README.mustache @@ -0,0 +1,43 @@ +# Documentation for OpenAPI Petstore +This is a client generator for microcontrollers on the Espressif32 platform and the Arduino framework +After the client have been generated, you have to change these following variablies: +- root.cert | Provide your service root certificate. +- src/main.cpp | Change wifi name +- src/main.cpp | Change wifi password +- lib/service/AbstractService.h | Change to your url + +# Documentation for {{#openAPI}}{{#info}}{{title}} {{version}} Tiny client cpp (Arduino) {{/info}}{{/openAPI}} + +The project is structured like this: +``` +samples/client/petstore/tiny/cpp/ +├── lib +│ ├── Models +│ ├── service +│ └── TestFiles +├── platformio.ini +├── pre_compiling_bourne.py +├── README.md +├── root.cert +├── src +│ └── main.cpp +└── test + └── RunTests.cpp +``` + +All URIs are relative to {{{scheme}}}://{{{host}}}{{{basePath}}} +{{#apiInfo}}{{#apis}}{{#operations}} +### {{classname}} +|Method | HTTP request | Description| +|------------- | ------------- | -------------| + {{#operation}} +|*{{operationId}}* | *{{httpMethod}}* {{{path}}} | {{{summary}}}.| + {{/operation}} +{{/operations}}{{/apis}}{{/apiInfo}} + +## What are the Model files for the data structures/objects? +|Class | Description| +|------------- | -------------| +{{#models}}{{#model}}|*{{classname}}* | {{{description}}}| +{{/model}}{{/models}} + diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/helpers-body.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/helpers-body.mustache new file mode 100644 index 000000000000..c3935b37cde9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/helpers-body.mustache @@ -0,0 +1,102 @@ +#include "Helpers.h" +#include +#include + +bool isprimitive(std::string type){ + if(type == "std::string" || + type == "int" || + type == "float" || + type == "long" || + type == "double" || + type == "bool" || + type == "std::map" || + type == "std::list") + { + return true; + } + return false; +} + + +void +jsonToValue(void* target, bourne::json value, std::string type) +{ + if (target == NULL || value.is_null()) { + return; + } + + else if (type.compare("bool") == 0) + { + bool* val = static_cast (target); + *val = value.to_bool(); + } + + else if (type.compare("int") == 0) + { + int* val = static_cast (target); + *val = value.to_int(); + } + + else if (type.compare("float") == 0) + { + float* val = static_cast (target); + *val = (float)(value.to_float()); + } + + else if (type.compare("long") == 0) + { + long* val = static_cast (target); + *val = (long)(value.to_int()); + } + + else if (type.compare("double") == 0) + { + double* val = static_cast (target); + *val = value.to_float(); + } + + else if (type.compare("std::string") == 0) + { + std::string* val = static_cast (target); + *val = value.to_string(); + } + else { + return; + } +} + +std::string +stringify(long input){ + std::stringstream stream; + stream << input; + return stream.str(); + +}; + +std::string +stringify(int input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(double input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(float input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(std::string input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/helpers-header.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/helpers-header.mustache new file mode 100644 index 000000000000..5ef7d9afdf77 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/helpers-header.mustache @@ -0,0 +1,22 @@ +#ifndef TINY_CPP_CLIENT_HELPERS_H_ +#define TINY_CPP_CLIENT_HELPERS_H_ + +#include +#include "bourne/json.hpp" + +bool isprimitive(std::string type); + +void jsonToValue(void* target, bourne::json value, std::string type); + +std::string stringify(long input); + +std::string stringify(int input); + +std::string stringify(double input); + +std::string stringify(float input); + +std::string stringify(std::string input); + +#endif /* TINY_CPP_CLIENT_HELPERS_H_ */ + diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/main.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/main.mustache new file mode 100644 index 000000000000..56170a91e0fc --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/main.mustache @@ -0,0 +1,40 @@ +#include "PetApi.h" +{{#isESP8266}} +#include "ESP8266WiFi.h" +{{/isESP8266}} + +const char* ssid = "your wifi name"; // TODO Change wifi name +const char* password = "Your wifi password"; //TODO Change wifi password + + +void setup(){ + //Initialize serial and wait for port to open: + Serial.begin(9600); + delay(100); + + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + WiFi.begin(ssid, password); + + // attempt to connect to Wifi network: + while (WiFi.status() != WL_CONNECTED) { + Serial.print("."); + // wait 1 second for re-trying + delay(1000); + } + + Serial.print("Connected to "); + Serial.println(ssid); + + //Print LAN IP. + Serial.print("IP address set: "); + Serial.println(WiFi.localIP()); + + Tiny::PetApi petapi; + auto resp = petapi.getPetById(10); + Serial.println(resp.code); + Tiny::Pet pet = resp.obj; + Serial.println(pet.toJson().dump().c_str()); +} + +void loop(){} diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/model-body.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/model-body.mustache new file mode 100644 index 000000000000..b2f2ee66fd9d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/model-body.mustache @@ -0,0 +1,160 @@ + +{{#models}}{{#model}} +#include "{{classname}}.h" + +using namespace Tiny; + +{{classname}}::{{classname}}() +{ + {{#vars}} + {{#isContainer}} + {{name}} = {{defaultValue}}<{{#items}}{{baseType}}{{/items}}>(); + {{/isContainer}} + {{^isContainer}} + {{name}} = {{defaultValue}}; + {{/isContainer}} + {{/vars}} +} + +{{classname}}::{{classname}}(std::string jsonString) +{ + this->fromJson(jsonString); +} + +{{classname}}::~{{classname}}() +{ + +} + +void +{{classname}}::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + {{#vars}} + const char *{{name}}Key = "{{baseName}}"; + + if(object.has_key({{name}}Key)) + { + bourne::json value = object[{{name}}Key]; + + {{#isContainer}} + {{#isArray}} + + std::list<{{#items}}{{dataType}}{{/items}}> {{name}}_list; + {{#items}}{{dataType}}{{/items}} element; + for(auto& var : value.array_range()) + { + {{#items}} + + {{#isPrimitiveType}} + jsonToValue(&element, var, "{{dataType}}"); + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + element.fromJson(var.dump()); + {{/isPrimitiveType}} + + {{/items}} + {{name}}_list.push_back(element); + } + {{name}} = {{name}}_list; + + {{/isArray}} + {{/isContainer}} + + {{^isContainer}} + + {{#isPrimitiveType}} + jsonToValue(&{{name}}, value, "{{baseType}}"); + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + {{baseType}}* obj = &{{name}}; + obj->fromJson(value.dump()); + {{/isPrimitiveType}} + + {{/isContainer}} + } + + {{/vars}} + +} + +bourne::json +{{classname}}::toJson() +{ + bourne::json object = bourne::json::object(); + + {{#vars}} + + {{#isContainer}} + {{#isArray}} + + {{#items}} + {{#isPrimitiveType}} + + std::list<{{dataType}}> {{name}}_list = {{getter}}(); + bourne::json {{name}}_arr = bourne::json::array(); + + for(auto& var : {{name}}_list) + { + {{name}}_arr.append(var); + } + object["{{name}}"] = {{name}}_arr; + + + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + std::list<{{dataType}}> {{name}}_list = {{getter}}(); + bourne::json {{name}}_arr = bourne::json::array(); + + for(auto& var : {{name}}_list) + { + {{dataType}} obj = var; + {{name}}_arr.append(obj.toJson()); + } + object["{{name}}"] = {{name}}_arr; + + {{/isPrimitiveType}} + {{/items}} + {{/isArray}} + {{/isContainer}} + + + {{^isContainer}} + + {{#isPrimitiveType}} + object["{{name}}"] = {{getter}}(); + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + object["{{name}}"] = {{getter}}().toJson(); + {{/isPrimitiveType}} + + {{/isContainer}} + {{/vars}} + + return object; + +} + +{{#vars}} +{{dataType}}{{#isContainer}}{{#isMap}}{{/isMap}}{{^isMap}}<{{#items}}{{dataType}}{{/items}}>{{/isMap}}{{/isContainer}} +{{classname}}::{{getter}}() +{ + return {{name}}; +} + +void +{{classname}}::{{setter}}({{dataType}} {{#isContainer}}{{#isMap}}{{/isMap}}{{^isMap}}<{{#items}}{{dataType}}{{/items}}>{{/isMap}}{{/isContainer}} {{name}}) +{ + this->{{name}} = {{name}}; +} + +{{/vars}} + + +{{/model}} +{{/models}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/model-header.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/model-header.mustache new file mode 100644 index 000000000000..a71ba0677c12 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/model-header.mustache @@ -0,0 +1,81 @@ + +{{#models}}{{#model}}/* + * {{classname}}.h + * + * {{description}} + */ + +#ifndef TINY_CPP_CLIENT_{{classname}}_H_ +#define TINY_CPP_CLIENT_{{classname}}_H_ + +{{/model}}{{/models}} +#include +#include "bourne/json.hpp" +#include "Helpers.h" +{{#imports}} +{{{import}}} +{{/imports}} + +namespace Tiny { +{{#models}}{{#model}} + +/*! \brief {{{description}}} + * + * \ingroup Models + * + */ + +class {{classname}}{ +public: + + /*! \brief Constructor. + */ + {{classname}}(); + {{classname}}(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~{{classname}}(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + {{#vars}} + /*! \brief Get {{{description}}} + */ + {{dataType}}{{#isContainer}}{{#isMap}}{{/isMap}}{{^isMap}}<{{#items}}{{dataType}}{{/items}}>{{/isMap}}{{/isContainer}} {{getter}}(); + + /*! \brief Set {{{description}}} + */ + void {{setter}}({{dataType}} {{#isContainer}}{{#isMap}}{{/isMap}}{{^isMap}}<{{#items}}{{dataType}}{{/items}}>{{/isMap}}{{/isContainer}} {{name}}); + {{/vars}} + + + private: + {{#vars}} + {{^isContainer}} + {{#isPrimitiveType}} + {{dataType}} {{name}}{}; + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{dataType}} {{name}}; + {{/isPrimitiveType}} + {{/isContainer}} + {{#isContainer}} + {{dataType}}{{#isMap}}{{/isMap}}{{^isMap}}<{{#items}}{{dataType}}{{/items}}>{{/isMap}} {{name}}; + {{/isContainer}} + {{/vars}} +}; +{{/model}} +{{/models}} +} + +#endif /* TINY_CPP_CLIENT_{{classname}}_H_ */ diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/platformio.ini.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/platformio.ini.mustache new file mode 100644 index 000000000000..1e364ee0ab20 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/platformio.ini.mustache @@ -0,0 +1,19 @@ +{{#isESP32}} +[env:esp32] +platform = espressif32 +board = nodemcu-32s +framework = arduino +lib_deps = https://github.com/steinwurf/bourne.git +extra_scripts = pre_compiling_bourne.py +{{/isESP32}} + +{{#isESP8266}} +[env:esp8266] +platform = espressif8266 +board = d1_mini +framework = arduino +lib_deps = https://github.com/steinwurf/bourne.git +build_flags = -fexceptions +build_unflags = -fno-exceptions +extra_scripts = pre_compiling_bourne.py +{{/isESP8266}} diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/pre_compiling_bourne.py.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/pre_compiling_bourne.py.mustache new file mode 100644 index 000000000000..96356dcdf158 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/pre_compiling_bourne.py.mustache @@ -0,0 +1,25 @@ +Import("env") + +## Compatibility for bourne to work on microcontrollers +# We insert '#define _GLIBCXX_USE_C99' in files that use std::stoll or std::to_string +def insert_c99_into(file): + import fileinput + + path = env['PROJECT_LIBDEPS_DIR'] + "/" + env['PIOENV'] + "/bourne/src/bourne/" + file + value = '#define _GLIBCXX_USE_C99 1\n' + + for line in fileinput.FileInput(path,inplace=1): + if line.startswith('#define _GLIBCXX_USE_C99'): + continue + elif line.startswith('// D'): + line=line.replace(line,line+value) + print(line, end='') + +def fix_parser(): + insert_c99_into('detail/parser.cpp') + +def fix_json(): + insert_c99_into('json.cpp') + +fix_parser() +fix_json() \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/root.cert.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/root.cert.mustache new file mode 100644 index 000000000000..bad9c08efad1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/root.cert.mustache @@ -0,0 +1,53 @@ +// TODO: Provide your service root certificate. +// Below is two examples of root certificates. + +// Let's encrypt root certificate +/** +"-----BEGIN CERTIFICATE-----\n" \ +"MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n" \ +"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" \ +"d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n" \ +"QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n" \ +"MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n" \ +"b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n" \ +"9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n" \ +"CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n" \ +"nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n" \ +"43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n" \ +"T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n" \ +"gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n" \ +"BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n" \ +"TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n" \ +"DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n" \ +"hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n" \ +"06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n" \ +"PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n" \ +"YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n" \ +"CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n" \ +"-----END CERTIFICATE-----\n" +*/ + +// Amazon_Root_CA_1.pem +/** +"-----BEGIN CERTIFICATE-----\n" \ +"MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\n" \ +"ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n" \ +"b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\n" \ +"MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\n" \ +"b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\n" \ +"ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\n" \ +"9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\n" \ +"IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\n" \ +"VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L\n" \ +"93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm\n" \ +"jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n" \ +"AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\n" \ +"A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\n" \ +"U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\n" \ +"N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv\n" \ +"o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\n" \ +"5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\n" \ +"rqXRfboQnoZsG4q5WTP468SQvvG5\n" \ +"-----END CERTIFICATE-----\n" \ +*/ + diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/run-tests.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/run-tests.mustache new file mode 100644 index 000000000000..54bf326c43a3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/run-tests.mustache @@ -0,0 +1,44 @@ +{{#models}}{{#model}} +#include "{{classname}}Test.cpp" +{{/model}}{{/models}} + + +void setUp(){} + +void tearDown(){} + +void runTests(){ + {{#models}}{{#model}} + {{#vars}} + {{#isPrimitiveType}}{{^isArray}} + RUN_TEST(test_{{classname}}_{{name}}_is_assigned_from_json); + {{/isArray}}{{/isPrimitiveType}} + {{/vars}} + {{/model}}{{/models}} + + {{#models}}{{#model}} + {{#vars}} + {{#isPrimitiveType}}{{^isArray}} + RUN_TEST(test_{{classname}}_{{name}}_is_converted_to_json); + {{/isArray}}{{/isPrimitiveType}} + {{/vars}} + {{/model}}{{/models}} + + +} + +int main(void) { + UNITY_BEGIN(); + runTests(); + return UNITY_END(); +} + +void setup() { + UNITY_BEGIN(); + runTests(); + UNITY_END(); +} + +void loop() { + +} diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/service/AbstractService.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/service/AbstractService.cpp.mustache new file mode 100644 index 000000000000..0c056c85ae35 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/service/AbstractService.cpp.mustache @@ -0,0 +1,15 @@ +#include "AbstractService.h" +#include "Arduino.h" + +{{#isESP8266}} +void Tiny::AbstractService::begin(std::string url){ + http.begin(client, String(url.c_str())); +} +{{/isESP8266}} + + +{{#isESP32}} +void Tiny::AbstractService::begin(std::string url){ + http.begin(String(url.c_str()), test_root_ca); //HTTPS connection +} +{{/isESP32}} diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/service/AbstractService.h.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/service/AbstractService.h.mustache new file mode 100644 index 000000000000..7dc46b5b20f0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/service/AbstractService.h.mustache @@ -0,0 +1,39 @@ +#ifndef TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ +#define TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ +{{#isESP8266}} +#include +#include +{{/isESP8266}} + +{{#isESP32}} +#include "HTTPClient.h" +{{/isESP32}} +#include "Response.h" +namespace Tiny { + +/** +* Class +* Generated with openapi::tiny-cpp-client +*/ +class AbstractService { +public: +HTTPClient http; +{{#isESP8266}} +WiFiClient client; +{{/isESP8266}} +std::string basepath = "https://petstore3.swagger.io/api/v3"; // TODO: change to your url + +void begin(std::string url); + +{{#isESP32}} +// Go and comment out a certificate in root.cert, if you get an error here +// Certificate from file +const char* test_root_ca = +#include "../../root.cert" +; +{{/isESP32}} + +}; // end class +}// namespace Tinyclient + +#endif /* TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ */ diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/service/Response.h.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/service/Response.h.mustache new file mode 100644 index 000000000000..9b7b616b8f1b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/service/Response.h.mustache @@ -0,0 +1,25 @@ +#ifndef TINY_CPP_CLIENT_RESPONSE_H_ +#define TINY_CPP_CLIENT_RESPONSE_H_ +#include + +namespace Tiny { + +/** +* Class +* Generated with openapi::tiny-cpp-client +*/ +template + class Response { + public: + + Response(T _obj, int _code){ + obj = _obj; + code = _code; + } + + int code; + T obj; + }; + } // namespace Tinyclient + +#endif /* TINY_CPP_CLIENT_RESPONSE_H_ */ diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/service/api-body.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/service/api-body.mustache new file mode 100644 index 000000000000..dc1298688372 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/service/api-body.mustache @@ -0,0 +1,219 @@ +#include "{{classname}}.h" + +using namespace Tiny; + +{{#operations}} + + {{! Method }} + {{#operation}} + + Response< + {{#returnType}} + {{#returnContainer}} + {{#isArray}} + {{returnType}}<{{returnBaseType}}> + {{/isArray}} + {{#isMap}} + String + {{/isMap}} + {{/returnContainer}} + {{^returnContainer}} + {{returnType}} + {{/returnContainer}} + {{/returnType}} + {{^returnType}} + String + {{/returnType}} + > + {{classname}}:: + {{! Method name }} + {{nickname}}( + {{! Params }} + {{#allParams}} + {{! Arrays }} + {{#isContainer}}{{{dataType}}}<{{baseType}}> {{paramName}}{{/isContainer}}{{#isMap}}// TODO: Implement Maps{{/isMap}} + {{! Normal types/objects }} + {{^isContainer}}{{{dataType}}} {{paramName}}{{/isContainer}} + {{^-last}}, {{/-last}} + {{/allParams}} + ) + {{! Method start}} + { + std::string url = basepath + "{{{path}}}"; //{{#pathParams}}{{{paramName}}} {{/pathParams}} + // Query | {{#queryParams}}{{paramName}} {{/queryParams}} + // Headers | {{#headerParams}}{{paramName}} {{/headerParams}} + // Form | {{#formParams}}{{paramName}} {{/formParams}} + // Body | {{#bodyParam}}{{paramName}}{{/bodyParam}} + + {{#pathParams}} + std::string s_{{paramName}}("{"); + s_{{paramName}}.append("{{{baseName}}}"); + s_{{paramName}}.append("}"); + + int pos = url.find(s_{{paramName}}); + + url.erase(pos, s_{{paramName}}.length()); + url.insert(pos, stringify({{paramName}})); + {{/pathParams}} + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | {{httpMethod}} + {{#bodyParam}} + http.addHeader("Content-Type", "application/json"); + + {{#isContainer}} + {{#isArray}} + {{#items}} + {{#isPrimitiveType}} + bourne::json tmp_arr = bourne::json::array(); + for(auto& var : {{paramName}}) + { + tmp_arr.append(var); + } + payload = tmp_arr.dump(); + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + bourne::json tmp_arr = bourne::json::array(); + for(auto& var : {{paramName}}) + { + auto tmp = var.toJson(); + tmp_arr.append(tmp); + + } + payload = tmp_arr.dump(); + {{/isPrimitiveType}} + {{/items}} + {{/isArray}} + {{/isContainer}} + + {{^isContainer}} + {{#isPrimitiveType}} + payload = stringify({{paramName}}); + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + payload = {{paramName}}.toJson().dump(); + {{/isPrimitiveType}} + {{/isContainer}} + + {{/bodyParam}} + int httpCode = http.sendRequest("{{httpMethod}}", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + {{#returnType}} + + {{#returnContainer}} + {{#isArray}} + + std::list<{{returnBaseType}}> obj = std::list<{{returnBaseType}}>(); + bourne::json jsonPayload(output_string); + + {{#returnBaseType}} + + {{#isBool}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp = var.to_bool(); + obj.push_back(tmp); + } + {{/isBool}} + + {{#isInteger}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp = var.to_int(); + obj.push_back(tmp); + } + {{/isInteger}} + + {{#isLong}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp = (long)(var.to_int()); + obj.push_back(tmp); + } + {{/isLong}} + + {{#isFloat}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp = (float)(var.to_float()); + obj.push_back(tmp); + } + {{/isFloat}} + + {{#isString}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp = var.to_string(); + obj.push_back(tmp); + } + {{/isString}} + + + {{^isBool}}{{^isInteger}}{{^isLong}}{{^isString}}{{^isFloat}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp(var.dump()); + obj.push_back(tmp); + } + {{/isFloat}}{{/isString}}{{/isLong}}{{/isInteger}}{{/isBool}} + + {{/returnBaseType}} + + {{/isArray}} + + {{#isMap}} + //TODO: Implement map logic here + {{/isMap}} + + {{/returnContainer}} + + {{^returnContainer}} + {{#returnTypeIsPrimitive}} + bourne::json jsonPayload(output_string); + {{returnType}} obj; + jsonToValue(&obj, jsonPayload, "{{returnType}}"); + {{/returnTypeIsPrimitive}} + + {{^returnTypeIsPrimitive}} + {{returnType}} obj(output_string); + {{/returnTypeIsPrimitive}} + {{/returnContainer}} + + {{/returnType}} + + {{#returnType}} + {{#returnContainer}} + {{#isArray}} + Response<{{returnType}}<{{returnBaseType}}>> response(obj, httpCode); + {{/isArray}} + {{#isMap}} + //TODO: No support for maps. + Response response(output, httpCode); + {{/isMap}} + {{/returnContainer}} + {{^returnContainer}} + Response<{{returnType}}> response(obj, httpCode); + {{/returnContainer}} + {{/returnType}} + {{^returnType}} + Response response(output, httpCode); + {{/returnType}} + return response; + } + {{/operation}} + + + +{{/operations}} + diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/service/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/service/api-header.mustache new file mode 100644 index 000000000000..416369dcf31a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/service/api-header.mustache @@ -0,0 +1,74 @@ +#ifndef TINY_CPP_CLIENT_{{classname}}_H_ +#define TINY_CPP_CLIENT_{{classname}}_H_ + +{{{defaultInclude}}} +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +{{#imports}} +{{{import}}} +{{/imports}} + +namespace Tiny { + +{{#operations}} +/** + * Class {{basename}} + * Generated with openapi::tiny-cpp-client + */ + +class {{classname}} : public AbstractService { +public: + {{! Constructor }} + {{classname}}() = default; + + {{! Destructor }} + virtual ~{{classname}}() = default; + + {{! Service endpoint }} + {{#operation}} + /** + * {{{summary}}}. + * + * {{{notes}}}{{#allParams}} + * \param {{paramName}} {{{description}}}{{#required}} *Required*{{/required}}{{/allParams}} + */ + Response< + {{#returnType}} + {{#returnContainer}} + {{#isArray}} + {{returnType}}<{{returnBaseType}}> + {{/isArray}} + {{#isMap}} + String + {{/isMap}} + {{/returnContainer}} + {{^returnContainer}} + {{returnType}} + {{/returnContainer}} + {{/returnType}} + {{^returnType}} + String + {{/returnType}} + > + {{! Method name }} + {{nickname}}( + {{! Params }} + {{#allParams}} + {{! Arrays }} + {{#isContainer}}{{{dataType}}}<{{baseType}}> {{paramName}}{{/isContainer}} + {{! Normal types/objects }} + {{^isContainer}}{{{dataType}}} {{paramName}}{{/isContainer}} + {{^-last}}, {{/-last}} + {{/allParams}} + ); + {{/operation}} +}; {{! Service endpoint end }} +{{/operations}} + +} {{! namespace end }} + +#endif /* TINY_CPP_CLIENT_{{classname}}_H_ */ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/unit-test-model.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/unit-test-model.mustache new file mode 100644 index 000000000000..14894973b81f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/unit-test-model.mustache @@ -0,0 +1,161 @@ +{{#models}}{{#model}} +#include "{{classname}}.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + +{{#vars}} +{{#isPrimitiveType}}{{^isArray}} +void test_{{classname}}_{{name}}_is_assigned_from_json() +{ + {{#isInteger}} + bourne::json input = + { + "{{name}}", 1 + }; + + {{classname}} obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.{{getter}}()); + {{/isInteger}} + + + {{#isString}} + bourne::json input = + { + "{{name}}", "hello" + }; + + {{classname}} obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.{{getter}}().c_str()); + {{/isString}} + + + {{#isBoolean}} + bourne::json input = + { + "{{name}}", true + }; + + {{classname}} obj(input.dump()); + + TEST_ASSERT(true == obj.{{getter}}()); + {{/isBoolean}} + + + {{#isLong}} + bourne::json input = + { + "{{name}}", 1 + }; + + {{classname}} obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.{{getter}}()); + {{/isLong}} + + + {{#isFloat}} + bourne::json input = + { + "{{name}}", 1.0 + }; + + {{classname}} obj(input.dump()); + + TEST_ASSERT_EQUAL_FLOAT(1.0, obj.{{getter}}()); + {{/isFloat}} +} +{{/isArray}}{{/isPrimitiveType}} +{{/vars}} + +{{#vars}} +{{#isPrimitiveType}}{{^isArray}} +void test_{{classname}}_{{name}}_is_converted_to_json() +{ + {{#isInteger}} + bourne::json input = + { + "{{name}}", 1 + }; + + {{classname}} obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["{{name}}"] == output["{{name}}"]); + {{/isInteger}} + + {{#isString}} + bourne::json input = + { + "{{name}}", "hello" + }; + + {{classname}} obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["{{name}}"] == output["{{name}}"]); + {{/isString}} + + {{#isBoolean}} + bourne::json input = + { + "{{name}}", true + }; + + {{classname}} obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["{{name}}"] == output["{{name}}"]); + {{/isBoolean}} + + {{#isLong}} + bourne::json input = + { + "{{name}}", 1 + }; + + {{classname}} obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["{{name}}"] == output["{{name}}"]); + {{/isLong}} + + {{#isFloat}} + bourne::json input = + { + "{{name}}", 1.0 + }; + + {{classname}} obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["{{name}}"] == output["{{name}}"]); + {{/isFloat}} +} +{{/isArray}}{{/isPrimitiveType}} +{{/vars}} + +{{/model}} +{{/models}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/unittest.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/unittest.mustache new file mode 100644 index 000000000000..c6a1f23a6e39 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/unittest.mustache @@ -0,0 +1,132 @@ +#include "Pet.h" +#include +#include +#include +#include "bourne/json.hpp" + +void setUp(){ +} + + +void tearDown(){ +} + +void test_id_is_assigned(){ + bourne::json petJSON = + { + "id", 1 + }; + + Tiny::Pet pet(petJSON.dump()); + + + TEST_ASSERT_EQUAL_INT(1, pet.getId()); +} + +void test_name_is_assigned(){ + bourne::json petJSON = + { + "name", "Shiba" + }; + + Tiny::Pet pet(petJSON.dump()); + + TEST_ASSERT_EQUAL_STRING("Shiba", pet.getName().c_str()); + +} + +void test_status_is_assigned(){ + bourne::json petJSON = + { + "status", "Sold" + }; + + Tiny::Pet pet(petJSON.dump()); + + TEST_ASSERT_EQUAL_STRING("Sold", pet.getStatus().c_str()); +} + +void test_category_object_is_assigned(){ + + bourne::json catJSON = + { + "id", 3, + "name", "Small dog" + }; + + bourne::json petJSON = + { + "category", catJSON, + }; + + Tiny::Pet pet(petJSON.dump()); + + TEST_ASSERT_EQUAL_STRING("Small dog", pet.getCategory().getName().c_str()); + TEST_ASSERT_EQUAL_INT(3, pet.getCategory().getId()); + +} + + +void test_photo_string_list_is_assigned(){ + + std::list photoList = {"url1", "url2", "url3", "url4"}; + + bourne::json photoARR = bourne::json::array("url1", "url2", "url3", "url4"); + + bourne::json petJSON = + { + "photoUrls", photoARR, + }; + + Tiny::Pet pet(petJSON.dump()); + + TEST_ASSERT(photoList == pet.getPhotoUrls()); +} + +void test_tags_object_list_is_assigned(){ + bourne::json aTag = + { + "id", 2, + "name", "Hello" + }; + + bourne::json tagsARR = bourne::json::array(aTag); + bourne::json petJSON = + { + "tags", tagsARR, + }; + + Tiny::Pet pet(petJSON.dump()); + + TEST_ASSERT_EQUAL_INT(2, pet.getTags().front().getId()); + TEST_ASSERT_EQUAL_STRING("Hello", pet.getTags().front().getName().c_str()); +} + + + +void runTests(){ + RUN_TEST(test_id_is_assigned); + RUN_TEST(test_category_object_is_assigned); + RUN_TEST(test_name_is_assigned); + RUN_TEST(test_status_is_assigned); + RUN_TEST(test_photo_string_list_is_assigned); + RUN_TEST(test_tags_object_list_is_assigned); +} + +int main(void) { + UNITY_BEGIN(); + runTests(); + return UNITY_END(); +} + +void setup() { + UNITY_BEGIN(); + runTests(); + UNITY_END(); +} + +void loop() { + +} + + diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/api-header.mustache index c6ee2f08eb44..17b42e942ea7 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/api-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/api-header.mustache @@ -15,9 +15,19 @@ public: {{classname}}(); ~{{classname}}(); + /* Sets the URL Endpoint. + * Note: several fallback endpoints can be configured in request retry policies, see Request::SetShouldRetry */ void SetURL(const FString& Url); + + /* Adds global header params to all requests */ void AddHeaderParam(const FString& Key, const FString& Value); void ClearHeaderParams(); + + /* Sets the retry manager to the user-defined retry manager. User must manage the lifetime of the retry manager. + * If no retry manager is specified and a request needs retries, a default retry manager will be used. + * See also: Request::SetShouldRetry */ + void SetHttpRetryManager(FHttpRetrySystem::FManager& RetryManager); + FHttpRetrySystem::FManager& GetHttpRetryManager(); {{#operations}}{{#operation}}class {{operationIdCamelCase}}Request; class {{operationIdCamelCase}}Response; @@ -27,15 +37,17 @@ public: {{#operations}}{{#operation}}{{#description}}/* {{{description}}} */ {{/description}}bool {{operationIdCamelCase}}(const {{operationIdCamelCase}}Request& Request, const F{{operationIdCamelCase}}Delegate& Delegate = F{{operationIdCamelCase}}Delegate()) const; {{/operation}}{{/operations}} - private: - {{#operations}}{{#operation}}void On{{operationIdCamelCase}}Response(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, F{{operationIdCamelCase}}Delegate Delegate, int AutoRetryCount) const; + {{#operations}}{{#operation}}void On{{operationIdCamelCase}}Response(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, F{{operationIdCamelCase}}Delegate Delegate) const; {{/operation}}{{/operations}} + FHttpRequestRef CreateHttpRequest(const Request& Request) const; bool IsValid() const; void HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const; FString Url; TMap AdditionalHeaderParams; + mutable FHttpRetrySystem::FManager* RetryManager = nullptr; + mutable TUniquePtr DefaultRetryManager; }; {{#cppNamespaceDeclarations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/api-operations-header.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/api-operations-header.mustache index 2319c59b3fa1..f4810ba58888 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/api-operations-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/api-operations-header.mustache @@ -35,6 +35,9 @@ public: {{/enumVars}} }; {{/allowableValues}} + + static FString EnumToString(const {{{enumName}}}& EnumValue); + static bool EnumFromString(const FString& EnumAsString, {{{enumName}}}& EnumValue); {{#description}}/* {{{description}}} */ {{/description}}{{^required}}TOptional<{{/required}}{{{datatypeWithEnum}}}{{^required}}>{{/required}} {{paramName}}{{#required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/required}}; {{/isEnum}} diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/api-operations-source.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/api-operations-source.mustache index 07b557157ea2..4d262483e1f3 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/api-operations-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/api-operations-source.mustache @@ -32,6 +32,28 @@ inline FString ToString(const {{classname}}::{{operationIdCamelCase}}Request::{{ return TEXT(""); } +FString {{classname}}::{{operationIdCamelCase}}Request::EnumToString(const {{classname}}::{{operationIdCamelCase}}Request::{{{enumName}}}& EnumValue) +{ + return ToString(EnumValue); +} + +inline bool FromString(const FString& EnumAsString, {{classname}}::{{operationIdCamelCase}}Request::{{{enumName}}}& Value) +{ + static TMap StringToEnum = { {{#allowableValues}}{{#enumVars}} + { TEXT("{{{value}}}"), {{classname}}::{{operationIdCamelCase}}Request::{{{enumName}}}::{{name}} },{{/enumVars}}{{/allowableValues}} }; + + const auto Found = StringToEnum.Find(EnumAsString); + if(Found) + Value = *Found; + + return Found != nullptr; +} + +bool {{classname}}::{{operationIdCamelCase}}Request::EnumFromString(const FString& EnumAsString, {{classname}}::{{operationIdCamelCase}}Request::{{{enumName}}}& EnumValue) +{ + return FromString(EnumAsString, EnumValue); +} + inline FStringFormatArg ToStringFormatArg(const {{classname}}::{{operationIdCamelCase}}Request::{{{enumName}}}& Value) { return FStringFormatArg(ToString(Value)); @@ -48,15 +70,8 @@ inline bool TryGetJsonValue(const TSharedPtr& JsonValue, {{classname FString TmpValue; if (JsonValue->TryGetString(TmpValue)) { - static TMap StringToEnum = { {{#enumVars}} - { TEXT("{{{value}}}"), {{classname}}::{{operationIdCamelCase}}Request::{{{enumName}}}::{{name}} },{{/enumVars}} }; - - const auto Found = StringToEnum.Find(TmpValue); - if(Found) - { - Value = *Found; + if(FromString(TmpValue, Value)) return true; - } } {{/allowableValues}} return false; diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/api-source.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/api-source.mustache index 8a9b38545444..9bd9f3b87bde 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/api-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/api-source.mustache @@ -45,6 +45,40 @@ bool {{classname}}::IsValid() const return true; } +void {{classname}}::SetHttpRetryManager(FHttpRetrySystem::FManager& InRetryManager) +{ + if(RetryManager != &GetHttpRetryManager()) + { + DefaultRetryManager.Reset(); + RetryManager = &InRetryManager; + } +} + +FHttpRetrySystem::FManager& {{classname}}::GetHttpRetryManager() +{ + return *RetryManager; +} + +FHttpRequestRef {{classname}}::CreateHttpRequest(const Request& Request) const +{ + if (!Request.GetRetryParams().IsSet()) + { + return FHttpModule::Get().CreateRequest(); + } + else + { + if (!RetryManager) + { + // Create default retry manager if none was specified + DefaultRetryManager = MakeUnique(6, 60); + RetryManager = DefaultRetryManager.Get(); + } + + const HttpRetryParams& Params = Request.GetRetryParams().GetValue(); + return RetryManager->CreateRequest(Params.RetryLimitCountOverride, Params.RetryTimeoutRelativeSecondsOverride, Params.RetryResponseCodes, Params.RetryVerbs, Params.RetryDomains); + } +} + void {{classname}}::HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const { InOutResponse.SetHttpResponse(HttpResponse); @@ -96,7 +130,7 @@ bool {{classname}}::{{operationIdCamelCase}}(const {{operationIdCamelCase}}Reque if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -106,26 +140,15 @@ bool {{classname}}::{{operationIdCamelCase}}(const {{operationIdCamelCase}}Reque Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &{{classname}}::On{{operationIdCamelCase}}Response, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &{{classname}}::On{{operationIdCamelCase}}Response, Delegate); return HttpRequest->ProcessRequest(); } -void {{classname}}::On{{operationIdCamelCase}}Response(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, F{{operationIdCamelCase}}Delegate Delegate, int AutoRetryCount) const +void {{classname}}::On{{operationIdCamelCase}}Response(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, F{{operationIdCamelCase}}Delegate Delegate) const { {{operationIdCamelCase}}Response Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &{{classname}}::On{{operationIdCamelCase}}Response, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } {{/operation}} diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/helpers-header.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/helpers-header.mustache index eb178e890af6..67d605359874 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/helpers-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/helpers-header.mustache @@ -105,6 +105,11 @@ inline FStringFormatArg ToStringFormatArg(const FDateTime& Value) return FStringFormatArg(Value.ToIso8601()); } +inline FStringFormatArg ToStringFormatArg(const FGuid& Value) +{ + return FStringFormatArg(Value.ToString(EGuidFormats::DigitsWithHyphens)); +} + inline FStringFormatArg ToStringFormatArg(const TArray& Value) { return FStringFormatArg(Base64UrlEncode(Value)); @@ -220,6 +225,11 @@ inline void WriteJsonValue(JsonWriter& Writer, const FDateTime& Value) Writer->WriteValue(Value.ToIso8601()); } +inline void WriteJsonValue(JsonWriter& Writer, const FGuid& Value) +{ + Writer->WriteValue(Value.ToString(EGuidFormats::DigitsWithHyphens)); +} + inline void WriteJsonValue(JsonWriter& Writer, const Model& Value) { Value.WriteJson(Writer); @@ -281,6 +291,17 @@ inline bool TryGetJsonValue(const TSharedPtr& JsonValue, FDateTime& return false; } +inline bool TryGetJsonValue(const TSharedPtr& JsonValue, FGuid& Value) +{ + FString TmpValue; + if (JsonValue->TryGetString(TmpValue)) + { + return FGuid::Parse(TmpValue, Value); + } + else + return false; +} + inline bool TryGetJsonValue(const TSharedPtr& JsonValue, bool& Value) { bool TmpValue; diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-header.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-header.mustache index 31b0bdabd260..2f5b6255f54a 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-header.mustache @@ -5,6 +5,8 @@ #include "Interfaces/IHttpResponse.h" #include "Serialization/JsonWriter.h" #include "Dom/JsonObject.h" +#include "HttpRetrySystem.h" +#include "Containers/Ticker.h" {{#cppNamespaceDeclarations}} namespace {{this}} @@ -12,6 +14,31 @@ namespace {{this}} {{/cppNamespaceDeclarations}} typedef TSharedRef> JsonWriter; +using namespace FHttpRetrySystem; + +struct {{dllapi}} HttpRetryManager : public FManager, public FTickerObjectBase +{ + using FManager::FManager; + + bool Tick(float DeltaTime) final; +}; + +struct {{dllapi}} HttpRetryParams +{ + HttpRetryParams( + const FRetryLimitCountSetting& InRetryLimitCountOverride = FRetryLimitCountSetting(), + const FRetryTimeoutRelativeSecondsSetting& InRetryTimeoutRelativeSecondsOverride = FRetryTimeoutRelativeSecondsSetting(), + const FRetryResponseCodes& InRetryResponseCodes = FRetryResponseCodes(), + const FRetryVerbs& InRetryVerbs = FRetryVerbs(), + const FRetryDomainsPtr& InRetryDomains = FRetryDomainsPtr() + ); + + FRetryLimitCountSetting RetryLimitCountOverride; + FRetryTimeoutRelativeSecondsSetting RetryTimeoutRelativeSecondsOverride; + FRetryResponseCodes RetryResponseCodes; + FRetryVerbs RetryVerbs; + FRetryDomainsPtr RetryDomains; +}; class {{dllapi}} Model { @@ -28,11 +55,12 @@ public: virtual void SetupHttpRequest(const FHttpRequestRef& HttpRequest) const = 0; virtual FString ComputePath() const = 0; - void SetAutoRetryCount(int InCount) { AutoRetryCount = InCount; } - int GetAutoRetryCount() const { return AutoRetryCount; } + /* Enables retry and optionally sets a retry policy for this request */ + void SetShouldRetry(const HttpRetryParams& Params = HttpRetryParams()) { RetryParams = Params; } + const TOptional& GetRetryParams() const { return RetryParams; } private: - int AutoRetryCount = 0; + TOptional RetryParams; }; class {{dllapi}} Response @@ -44,8 +72,6 @@ public: void SetSuccessful(bool InSuccessful) { Successful = InSuccessful; } bool IsSuccessful() const { return Successful; } - void AsyncRetry() const; - virtual void SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode); EHttpResponseCodes::Type GetHttpResponseCode() const { return ResponseCode; } @@ -55,15 +81,11 @@ public: void SetHttpResponse(const FHttpResponsePtr& InHttpResponse) { HttpResponse = InHttpResponse; } const FHttpResponsePtr& GetHttpResponse() const { return HttpResponse; } - void SetHttpRequest(const FHttpRequestPtr& InHttpRequest) { HttpRequest = InHttpRequest; } - const FHttpRequestPtr& GetHttpRequest() const { return HttpRequest; } - private: bool Successful; EHttpResponseCodes::Type ResponseCode; FString ResponseString; FHttpResponsePtr HttpResponse; - FHttpRequestPtr HttpRequest; }; {{#cppNamespaceDeclarations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-source.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-source.mustache index a5ab70a432f7..57dc4fb4151c 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/model-base-source.mustache @@ -1,13 +1,30 @@ {{>licenseInfo}} #include "{{modelNamePrefix}}BaseModel.h" -#include "Async/Async.h" - {{#cppNamespaceDeclarations}} namespace {{this}} { {{/cppNamespaceDeclarations}} +bool HttpRetryManager::Tick(float DeltaTime) +{ + FManager::Update(); + return true; +} + +HttpRetryParams::HttpRetryParams(const FRetryLimitCountSetting& InRetryLimitCountOverride /*= FRetryLimitCountSetting()*/, + const FRetryTimeoutRelativeSecondsSetting& InRetryTimeoutRelativeSecondsOverride /*= FRetryTimeoutRelativeSecondsSetting()*/, + const FRetryResponseCodes& InRetryResponseCodes /*= FRetryResponseCodes()*/, + const FRetryVerbs& InRetryVerbs /*= FRetryVerbs()*/, + const FRetryDomainsPtr& InRetryDomains /*= FRetryDomainsPtr() */) + : RetryLimitCountOverride(InRetryLimitCountOverride) + , RetryTimeoutRelativeSecondsOverride(InRetryTimeoutRelativeSecondsOverride) + , RetryResponseCodes(InRetryResponseCodes) + , RetryVerbs(InRetryVerbs) + , RetryDomains(InRetryDomains) +{ +} + void Response::SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode) { ResponseCode = InHttpResponseCode; @@ -18,15 +35,6 @@ void Response::SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode) } } -void Response::AsyncRetry() const -{ - // Unfortunately, it is currently usafe to call ProcessRequest() directly here. - // This is because the HttpManager will remove all references to this HttpRequest in FHttpManager::Tick including the new request we just added, instead of removing just one. - // This will lead to the request's destruction and eventually a crash. - // The only solution is therefore to ensure we are taking an extra reference to the request, and that the request is added after the queue is flushed. - Async(EAsyncExecution::TaskGraph, [AddRef = FHttpRequestPtr(GetHttpRequest())](){ AddRef->ProcessRequest(); }); -} - {{#cppNamespaceDeclarations}} } {{/cppNamespaceDeclarations}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/model-header.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/model-header.mustache index 900dcf7f3189..8742ad7a85f5 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/model-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/model-header.mustache @@ -36,6 +36,9 @@ public: Values Value{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}; {{/allowableValues}} + + static FString EnumToString(const Values& EnumValue); + static bool EnumFromString(const FString& EnumAsString, Values& EnumValue); {{/isEnum}} {{^isEnum}} FString Value{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}; @@ -51,6 +54,9 @@ public: {{/enumVars}} }; {{/allowableValues}} + + static FString EnumToString(const {{{enumName}}}& EnumValue); + static bool EnumFromString(const FString& EnumAsString, {{{enumName}}}& EnumValue); {{#description}}/* {{{description}}} */ {{/description}}{{^required}}TOptional<{{/required}}{{{datatypeWithEnum}}}{{^required}}>{{/required}} {{name}}{{#required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/required}}; {{/isEnum}} diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/model-source.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/model-source.mustache index d084f8a80339..3022a7a935d7 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/model-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/model-source.mustache @@ -28,6 +28,28 @@ inline FString ToString(const {{classname}}::Values& Value) return TEXT(""); } +FString {{classname}}::EnumToString(const {{classname}}::Values& EnumValue) +{ + return ToString(EnumValue); +} + +inline bool FromString(const FString& EnumAsString, {{classname}}::Values& Value) +{ + static TMap StringToEnum = { {{#allowableValues}}{{#enumVars}} + { TEXT("{{{value}}}"), {{classname}}::Values::{{name}} },{{/enumVars}}{{/allowableValues}} }; + + const auto Found = StringToEnum.Find(EnumAsString); + if(Found) + Value = *Found; + + return Found != nullptr; +} + +bool {{classname}}::EnumFromString(const FString& EnumAsString, {{classname}}::Values& EnumValue) +{ + return FromString(EnumAsString, EnumValue); +} + inline FStringFormatArg ToStringFormatArg(const {{classname}}::Values& Value) { return FStringFormatArg(ToString(Value)); @@ -44,15 +66,8 @@ inline bool TryGetJsonValue(const TSharedPtr& JsonValue, {{classname FString TmpValue; if (JsonValue->TryGetString(TmpValue)) { - static TMap StringToEnum = { {{#enumVars}} - { TEXT("{{{value}}}"), {{classname}}::Values::{{name}} },{{/enumVars}} }; - - const auto Found = StringToEnum.Find(TmpValue); - if(Found) - { - Value = *Found; + if(FromString(TmpValue, Value)) return true; - } } {{/allowableValues}} return false; @@ -78,6 +93,28 @@ inline FString ToString(const {{classname}}::{{{enumName}}}& Value) return TEXT(""); } +FString {{classname}}::EnumToString(const {{classname}}::{{{enumName}}}& EnumValue) +{ + return ToString(EnumValue); +} + +inline bool FromString(const FString& EnumAsString, {{classname}}::{{{enumName}}}& Value) +{ + static TMap StringToEnum = { {{#allowableValues}}{{#enumVars}} + { TEXT("{{{value}}}"), {{classname}}::{{{enumName}}}::{{name}} },{{/enumVars}}{{/allowableValues}} }; + + const auto Found = StringToEnum.Find(EnumAsString); + if(Found) + Value = *Found; + + return Found != nullptr; +} + +bool {{classname}}::EnumFromString(const FString& EnumAsString, {{classname}}::{{{enumName}}}& EnumValue) +{ + return FromString(EnumAsString, EnumValue); +} + inline FStringFormatArg ToStringFormatArg(const {{classname}}::{{{enumName}}}& Value) { return FStringFormatArg(ToString(Value)); @@ -94,15 +131,8 @@ inline bool TryGetJsonValue(const TSharedPtr& JsonValue, {{classname FString TmpValue; if (JsonValue->TryGetString(TmpValue)) { - static TMap StringToEnum = { {{#enumVars}} - { TEXT("{{{value}}}"), {{classname}}::{{{enumName}}}::{{name}} },{{/enumVars}} }; - - const auto Found = StringToEnum.Find(TmpValue); - if(Found) - { - Value = *Found; + if(FromString(TmpValue, Value)) return true; - } } {{/allowableValues}} return false; diff --git a/modules/openapi-generator/src/main/resources/crystal/api.mustache b/modules/openapi-generator/src/main/resources/crystal/api.mustache index 8b8daabb5f38..787189be8544 100644 --- a/modules/openapi-generator/src/main/resources/crystal/api.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/api.mustache @@ -128,9 +128,9 @@ module {{moduleName}} local_var_path = "{{{path}}}"{{#pathParams}}.sub("{" + "{{baseName}}" + "}", URI.encode({{paramName}}.to_s){{^strictSpecBehavior}}.gsub("%2F", "/"){{/strictSpecBehavior}}){{/pathParams}} # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new {{#queryParams}} - query_params[:"{{{baseName}}}"] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}} + query_params["{{{baseName}}}"] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}} {{/queryParams}} # header parameters diff --git a/modules/openapi-generator/src/main/resources/crystal/api_client.mustache b/modules/openapi-generator/src/main/resources/crystal/api_client.mustache index 6831e51bae0c..9852faa90f9c 100644 --- a/modules/openapi-generator/src/main/resources/crystal/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/api_client.mustache @@ -163,7 +163,7 @@ module {{moduleName}} # @param [Hash] query_params Query parameters # @param [String] auth_names Authentication scheme name def update_params_for_auth!(header_params, query_params, auth_names) - Array{auth_names}.each do |auth_name| + auth_names.each do |auth_name| auth_setting = @config.auth_settings[auth_name] next unless auth_setting case auth_setting[:in] @@ -256,7 +256,7 @@ module {{moduleName}} # # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: # the data deserialized from response body (could be nil), response status code and response headers. - def call_api(http_method : Symbol, path : String, operation : Symbol, return_type : String, post_body : String?, auth_names = [] of String, header_params = {} of String => String, query_params = {} of Symbol => String, form_params = {} of Symbol => String) + def call_api(http_method : Symbol, path : String, operation : Symbol, return_type : String, post_body : String?, auth_names = [] of String, header_params = {} of String => String, query_params = {} of String => String, form_params = {} of Symbol => String) #ssl_options = { # :ca_file => @config.ssl_ca_file, # :verify => @config.ssl_verify, @@ -274,6 +274,8 @@ module {{moduleName}} # conn.adapter(Faraday.default_adapter) #end + update_params_for_auth! header_params, query_params, auth_names + if !post_body.nil? && !post_body.empty? # use JSON string in the payload form_or_body = post_body diff --git a/modules/openapi-generator/src/main/resources/crystal/configuration.mustache b/modules/openapi-generator/src/main/resources/crystal/configuration.mustache index 7111ba75e75c..103cf1820b28 100644 --- a/modules/openapi-generator/src/main/resources/crystal/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/configuration.mustache @@ -30,7 +30,7 @@ module {{moduleName}} # @return [Hash] key: parameter name, value: parameter value (API key) # # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) - # config.api_key[:"api_key"] = "xxx" + # config.api_key[:api_key] = "xxx" property api_key : Hash(Symbol, String) # Defines API key prefixes used with API Key authentications. @@ -38,7 +38,7 @@ module {{moduleName}} # @return [Hash] key: parameter name, value: API key prefix # # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) - # config.api_key_prefix[:"api_key"] = "Token" + # config.api_key_prefix[:api_key] = "Token" property api_key_prefix : Hash(Symbol, String) # Defines the username used with HTTP basic authentication. @@ -119,6 +119,7 @@ module {{moduleName}} # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 #property params_encoding : String? + # Create a new `Configuration`. def initialize @scheme = "{{scheme}}" @host = "{{host}}{{#port}}:{{{.}}}{{/port}}" @@ -141,9 +142,19 @@ module {{moduleName}} @password = nil @access_token = nil @temp_folder_path = nil + end - # TODO revise below to support block - #yield(self) if block_given? + # Create a new `Configuration` with block. + # + # ``` + # config = Petstore::Configuration.new do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # ``` + def initialize + initialize + yield self end # The default Configuration object. @@ -151,8 +162,9 @@ module {{moduleName}} @@default ||= Configuration.new end + # Configure object with block. def configure - yield(self) if block_given? + yield self end def scheme=(scheme) @@ -183,10 +195,10 @@ module {{moduleName}} # Gets API key (with prefix if set). # @param [String] param_name the parameter name of API key auth def api_key_with_prefix(param_name) - if @api_key_prefix[param_name] - "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + if prefix = @api_key_prefix[param_name]? + "#{prefix} #{@api_key[param_name]}" else - @api_key[param_name] + @api_key[param_name]? || "" end end @@ -197,44 +209,44 @@ module {{moduleName}} # Returns Auth Settings hash for api client. def auth_settings - Hash{ {{#authMethods}}{{#isApiKey}}"{{name}}" => { - type: "api_key", - in: {{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}, - key: "{{keyParamName}}", - value: api_key_with_prefix("{{keyParamName}}") - }, + Hash{ +{{#authMethods}} +{{#isApiKey}} + "{{name}}" => { + type: "api_key", + in: {{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}, + key: "{{keyParamName}}", + value: api_key_with_prefix(:{{keyParamName}}) + }, {{/isApiKey}} {{#isBasic}} {{#isBasicBasic}} - "{{name}}" => - { - type: "basic", - in: "header", - key: "Authorization", - value: basic_auth_token - }, + "{{name}}" => { + type: "basic", + in: "header", + key: "Authorization", + value: basic_auth_token + }, {{/isBasicBasic}} {{#isBasicBearer}} - "{{name}}" => - { - type: "bearer", - in: "header", - {{#bearerFormat}} - format: "{{{.}}}", - {{/bearerFormat}} - key: "Authorization", - value: "Bearer #{access_token}" - }, + "{{name}}" => { + type: "bearer", + in: "header", + {{#bearerFormat}} + format: "{{{.}}}", + {{/bearerFormat}} + key: "Authorization", + value: "Bearer #{access_token}" + }, {{/isBasicBearer}} {{/isBasic}} {{#isOAuth}} - "{{name}}" => - { - type: "oauth2", - in: "header", - key: "Authorization", - value: "Bearer #{access_token}" - }, + "{{name}}" => { + type: "oauth2", + in: "header", + key: "Authorization", + value: "Bearer #{access_token}" + }, {{/isOAuth}} {{/authMethods}} } diff --git a/modules/openapi-generator/src/main/resources/crystal/model.mustache b/modules/openapi-generator/src/main/resources/crystal/model.mustache index a19cc5f3f6a6..021857ee40e8 100644 --- a/modules/openapi-generator/src/main/resources/crystal/model.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/model.mustache @@ -1,5 +1,6 @@ # {{#lambdaPrefixWithHash}}{{> api_info}}{{/lambdaPrefixWithHash}} +require "json" require "time" module {{moduleName}} diff --git a/modules/openapi-generator/src/main/resources/crystal/partial_model_generic.mustache b/modules/openapi-generator/src/main/resources/crystal/partial_model_generic.mustache index c36181c48dc4..eaf47753fbad 100644 --- a/modules/openapi-generator/src/main/resources/crystal/partial_model_generic.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/partial_model_generic.mustache @@ -1,8 +1,10 @@ {{#description}} # {{{description}}} {{/description}} - class {{classname}}{{#parent}} < {{{.}}}{{/parent}} include JSON::Serializable - include JSON::Serializable {{#vars}} + class {{classname}}{{#parent}} < {{{.}}}{{/parent}} + include JSON::Serializable + + {{#vars}} {{#description}} # {{{description}}} {{/description}} diff --git a/modules/openapi-generator/src/main/resources/crystal/shard.mustache b/modules/openapi-generator/src/main/resources/crystal/shard.mustache index 89376ca4593b..11b012865385 100644 --- a/modules/openapi-generator/src/main/resources/crystal/shard.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/shard.mustache @@ -1,4 +1,4 @@ -name: {{{moduleName}}} +name: {{{shardName}}} version: {{{shardVersion}}} authors: - {{{shardAuthors}}} diff --git a/modules/openapi-generator/src/main/resources/crystal/shard_name.mustache b/modules/openapi-generator/src/main/resources/crystal/shard_name.mustache index 7e3e9b162d4b..6d2de8333a37 100644 --- a/modules/openapi-generator/src/main/resources/crystal/shard_name.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/shard_name.mustache @@ -9,18 +9,21 @@ module {{moduleName}} VERSION = {{ `shards version #{__DIR__}`.chomp.stringify }} + # Return the default `Configuration` object. + def self.configure + Configuration.default + end + # Customize default settings for the SDK using block. - # {{moduleName}}.configure do |config| - # config.username = "xxx" - # config.password = "xxx" - # end - # If no block given, return the default Configuration object. - def configure - if block_given? - yield(Configuration.default) - else - Configuration.default - end + # + # ``` + # {{moduleName}}.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # ``` + def self.configure + yield Configuration.default end end diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/README.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/README.mustache index c5f3c0eadfa9..b15d2a25bf19 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/README.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/README.mustache @@ -137,6 +137,9 @@ services.AddHttpClient(httpClient => ```csharp using System.Collections.Generic; using System.Diagnostics; +{{#useHttpClient}} +using System.Net.Http; +{{/useHttpClient}} using {{packageName}}.{{apiPackage}}; using {{packageName}}.Client; using {{packageName}}.{{modelPackage}}; @@ -174,7 +177,15 @@ namespace Example {{/authMethods}} {{/hasAuthMethods}} + {{#useHttpClient}} + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new {{classname}}(httpClient, config, httpClientHandler); + {{/useHttpClient}} + {{^useHttpClient}} var apiInstance = new {{classname}}(config); + {{/useHttpClient}} {{#allParams}} {{#isPrimitiveType}} var {{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/api_doc.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/api_doc.mustache index 0fd9f8790611..d12ee22ea388 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/api_doc.mustache @@ -22,6 +22,9 @@ Method | HTTP request | Description ```csharp using System.Collections.Generic; using System.Diagnostics; +{{#useHttpClient}} +using System.Net.Http; +{{/useHttpClient}} using {{packageName}}.{{apiPackage}}; using {{packageName}}.Client; using {{packageName}}.{{modelPackage}}; @@ -58,7 +61,15 @@ namespace Example {{/authMethods}} {{/hasAuthMethods}} + {{#useHttpClient}} + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new {{classname}}(httpClient, config, httpClientHandler); + {{/useHttpClient}} + {{^useHttpClient}} var apiInstance = new {{classname}}(config); + {{/useHttpClient}} {{#allParams}} {{#isPrimitiveType}} var {{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache index bdc24c21a172..e48722f8fa75 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache @@ -80,9 +80,9 @@ namespace {{packageName}}.Client } } - public T Deserialize(HttpResponseMessage response) + public async Task Deserialize(HttpResponseMessage response) { - var result = (T)Deserialize(response, typeof(T)); + var result = (T) await Deserialize(response, typeof(T)); return result; } @@ -92,19 +92,19 @@ namespace {{packageName}}.Client /// The HTTP response. /// Object type. /// Object representation of the JSON string. - internal object Deserialize(HttpResponseMessage response, Type type) + internal async Task Deserialize(HttpResponseMessage response, Type type) { IList headers = response.Headers.Select(x => x.Key + "=" + x.Value).ToList(); if (type == typeof(byte[])) // return byte array { - return response.Content.ReadAsByteArrayAsync().Result; + return await response.Content.ReadAsByteArrayAsync(); } // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) if (type == typeof(Stream)) { - var bytes = response.Content.ReadAsByteArrayAsync().Result; + var bytes = await response.Content.ReadAsByteArrayAsync(); if (headers != null) { var filePath = String.IsNullOrEmpty(_configuration.TempFolderPath) @@ -128,18 +128,18 @@ namespace {{packageName}}.Client if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content.ReadAsStringAsync().Result, null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(await response.Content.ReadAsStringAsync(), null, System.Globalization.DateTimeStyles.RoundtripKind); } if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type { - return Convert.ChangeType(response.Content.ReadAsStringAsync().Result, type); + return Convert.ChangeType(await response.Content.ReadAsStringAsync(), type); } // at this point, it must be a model (json) try { - return JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result, type, _serializerSettings); + return JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync(), type, _serializerSettings); } catch (Exception e) { @@ -168,9 +168,9 @@ namespace {{packageName}}.Client { private readonly String _baseUrl; - private readonly HttpClientHandler _httpClientHandler; - private readonly HttpClient _httpClient; - private readonly bool _disposeClient; + private readonly HttpClientHandler _httpClientHandler; + private readonly HttpClient _httpClient; + private readonly bool _disposeClient; /// /// Specifies the settings on a object. @@ -191,89 +191,66 @@ namespace {{packageName}}.Client /// /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// public ApiClient() : this({{packageName}}.Client.GlobalConfiguration.Instance.BasePath) - { + { } - + /// /// Initializes a new instance of the . + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. /// public ApiClient(String basePath) - { - if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); + { + if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); - _httpClientHandler = new HttpClientHandler(); - _httpClient = new HttpClient(_httpClientHandler, true); + _httpClientHandler = new HttpClientHandler(); + _httpClient = new HttpClient(_httpClientHandler, true); _disposeClient = true; - _baseUrl = basePath; + _baseUrl = basePath; } - + /// /// Initializes a new instance of the , defaulting to the global configurations' base url. /// /// An instance of HttpClient. - /// - /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. - /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. - /// - public ApiClient(HttpClient client) : - this(client, {{packageName}}.Client.GlobalConfiguration.Instance.BasePath) - { - } - - /// - /// Initializes a new instance of the - /// - /// An instance of HttpClient. - /// The target service's base path in URL format. - /// - /// - /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. - /// - public ApiClient(HttpClient client, String basePath) - { - if (client == null) throw new ArgumentNullException("client cannot be null"); - if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); - - _httpClient = client; - _baseUrl = basePath; + /// + public ApiClient(HttpClient client, HttpClientHandler handler = null) : + this(client, {{packageName}}.Client.GlobalConfiguration.Instance.BasePath, handler) + { } - - /// - /// Initializes a new instance of the , defaulting to the global configurations' base url. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// - public ApiClient(HttpClient client, HttpClientHandler handler) : - this(client, handler, {{packageName}}.Client.GlobalConfiguration.Instance.BasePath) - { - } - - /// + + /// /// Initializes a new instance of the . /// /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// The target service's base path in URL format. - /// - /// - public ApiClient(HttpClient client, HttpClientHandler handler, String basePath) - { - if (client == null) throw new ArgumentNullException("client cannot be null"); - if (handler == null) throw new ArgumentNullException("handler cannot be null"); - if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); - - _httpClientHandler = handler; - _httpClient = client; - _baseUrl = basePath; + /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public ApiClient(HttpClient client, String basePath, HttpClientHandler handler = null) + { + if (client == null) throw new ArgumentNullException("client cannot be null"); + if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); + + _httpClientHandler = handler; + _httpClient = client; + _baseUrl = basePath; } /// @@ -301,12 +278,10 @@ namespace {{packageName}}.Client { foreach (var fileParam in options.FileParameters) { - var fileStream = fileParam.Value as FileStream; - var fileStreamName = fileStream != null ? System.IO.Path.GetFileName(fileStream.Name) : null; - var content = new StreamContent(fileParam.Value); + var content = new StreamContent(fileParam.Value.Content); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); multipartContent.Add(content, fileParam.Key, - fileStreamName ?? "no_file_name_provided"); + fileParam.Value.Name); } } return multipartContent; @@ -338,11 +313,7 @@ namespace {{packageName}}.Client builder.AddPathParameters(options.PathParameters); - // In case of POST or PUT pass query parameters in request body - if (method != HttpMethod.Post && method != HttpMethod.Put) - { - builder.AddQueryParameters(options.QueryParameters); - } + builder.AddQueryParameters(options.QueryParameters); HttpRequestMessage request = new HttpRequestMessage(method, builder.GetFullUri()); @@ -393,11 +364,11 @@ namespace {{packageName}}.Client { if (options.Data != null) { - if (options.Data is Stream s) + if (options.Data is FileParameter fp) { contentType = contentType ?? "application/octet-stream"; - var streamContent = new StreamContent(s); + var streamContent = new StreamContent(fp.Content); streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Content = streamContent; } @@ -424,10 +395,10 @@ namespace {{packageName}}.Client partial void InterceptRequest(HttpRequestMessage req); partial void InterceptResponse(HttpRequestMessage req, HttpResponseMessage response); - private ApiResponse ToApiResponse(HttpResponseMessage response, object responseData, Uri uri) + private async Task> ToApiResponse(HttpResponseMessage response, object responseData, Uri uri) { T result = (T) responseData; - string rawContent = response.Content.ToString(); + string rawContent = await response.Content.ReadAsStringAsync(); var transformed = new ApiResponse(response.StatusCode, new Multimap({{#caseInsensitiveResponseHeaders}}StringComparer.OrdinalIgnoreCase{{/caseInsensitiveResponseHeaders}}), result, rawContent) { @@ -469,7 +440,7 @@ namespace {{packageName}}.Client private ApiResponse Exec(HttpRequestMessage req, IReadableConfiguration configuration) { - return ExecAsync(req, configuration).Result; + return ExecAsync(req, configuration).GetAwaiter().GetResult(); } private async Task> ExecAsync(HttpRequestMessage req, @@ -534,7 +505,12 @@ namespace {{packageName}}.Client } {{/supportsRetry}} - object responseData = deserializer.Deserialize(response); + if (!response.IsSuccessStatusCode) + { + return await ToApiResponse(response, default(T), req.RequestUri); + } + + object responseData = await deserializer.Deserialize(response); // if the response type is oneOf/anyOf, call FromJSON to deserialize the data if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) @@ -548,9 +524,7 @@ namespace {{packageName}}.Client InterceptResponse(req, response); - var result = ToApiResponse(response, responseData, req.RequestUri); - - return result; + return await ToApiResponse(response, responseData, req.RequestUri); } {{#supportsAsync}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/FileParameter.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/FileParameter.mustache new file mode 100644 index 000000000000..3fa243ed54fc --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/FileParameter.mustache @@ -0,0 +1,54 @@ +{{>partial_header}} + +using System.IO; + +namespace {{packageName}}.Client +{ + + /// + /// Represents a File passed to the API as a Parameter, allows using different backends for files + /// + public class FileParameter + { + /// + /// The filename + /// + public string Name { get; set; } = "no_name_provided"; + + /// + /// The content of the file + /// + public Stream Content { get; set; } + + /// + /// Construct a FileParameter just from the contents, will extract the filename from a filestream + /// + /// The file content + public FileParameter(Stream content) + { + if (content is FileStream fs) + { + Name = fs.Name; + } + Content = content; + } + + /// + /// Construct a FileParameter from name and content + /// + /// The filename + /// The file content + public FileParameter(string filename, Stream content) + { + Name = filename; + Content = content; + } + + /// + /// Implicit conversion of stream to file parameter. Useful for backwards compatibility. + /// + /// Stream to convert + /// FileParameter + public static implicit operator FileParameter(Stream s) => new FileParameter(s); + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/RequestOptions.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/RequestOptions.mustache new file mode 100644 index 000000000000..b0137d979976 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/RequestOptions.mustache @@ -0,0 +1,66 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; + +namespace {{packageName}}.Client +{ + /// + /// A container for generalized request inputs. This type allows consumers to extend the request functionality + /// by abstracting away from the default (built-in) request framework (e.g. RestSharp). + /// + public class RequestOptions + { + /// + /// Parameters to be bound to path parts of the Request's URL + /// + public Dictionary PathParameters { get; set; } + + /// + /// Query parameters to be applied to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap QueryParameters { get; set; } + + /// + /// Header parameters to be applied to to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap HeaderParameters { get; set; } + + /// + /// Form parameters to be sent along with the request. + /// + public Dictionary FormParameters { get; set; } + + /// + /// File parameters to be sent along with the request. + /// + public Dictionary FileParameters { get; set; } + + /// + /// Cookies to be sent along with the request. + /// + public List Cookies { get; set; } + + /// + /// Any data associated with a request body. + /// + public Object Data { get; set; } + + /// + /// Constructs a new instance of + /// + public RequestOptions() + { + PathParameters = new Dictionary(); + QueryParameters = new Multimap(); + HeaderParameters = new Multimap(); + FormParameters = new Dictionary(); + FileParameters = new Dictionary(); + Cookies = new List(); + } + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/api.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/api.mustache index b71ebee0f81e..0a3389d0a450 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/api.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/api.mustache @@ -106,6 +106,8 @@ namespace {{packageName}}.{{apiPackage}} /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// public {{classname}}() : this((string)null) @@ -114,9 +116,11 @@ namespace {{packageName}}.{{apiPackage}} /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. - /// + /// /// public {{classname}}(String basePath) { @@ -134,6 +138,8 @@ namespace {{packageName}}.{{apiPackage}} /// /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// An instance of Configuration. /// @@ -158,13 +164,14 @@ namespace {{packageName}}.{{apiPackage}} /// Initializes a new instance of the class. /// /// An instance of HttpClient. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// /// /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public {{classname}}(HttpClient client) : this(client, (string)null) + public {{classname}}(HttpClient client, HttpClientHandler handler = null) : this(client, (string)null, handler) { } @@ -173,14 +180,15 @@ namespace {{packageName}}.{{apiPackage}} /// /// An instance of HttpClient. /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// - /// + /// /// - /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public {{classname}}(HttpClient client, String basePath) + public {{classname}}(HttpClient client, String basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client"); @@ -188,7 +196,7 @@ namespace {{packageName}}.{{apiPackage}} {{packageName}}.Client.GlobalConfiguration.Instance, new {{packageName}}.Client.Configuration { BasePath = basePath } ); - this.ApiClient = new {{packageName}}.Client.ApiClient(client, this.Configuration.BasePath); + this.ApiClient = new {{packageName}}.Client.ApiClient(client, this.Configuration.BasePath, handler); this.Client = this.ApiClient; {{#supportsAsync}} this.AsynchronousClient = this.ApiClient; @@ -201,85 +209,23 @@ namespace {{packageName}}.{{apiPackage}} /// /// An instance of HttpClient. /// An instance of Configuration. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// /// /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public {{classname}}(HttpClient client, {{packageName}}.Client.Configuration configuration) + public {{classname}}(HttpClient client, {{packageName}}.Client.Configuration configuration, HttpClientHandler handler = null) { if (configuration == null) throw new ArgumentNullException("configuration"); - if (client == null) throw new ArgumentNullException("client"); - - this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( - {{packageName}}.Client.GlobalConfiguration.Instance, - configuration - ); - this.ApiClient = new {{packageName}}.Client.ApiClient(client, this.Configuration.BasePath); - this.Client = this.ApiClient; - {{#supportsAsync}} - this.AsynchronousClient = this.ApiClient; - {{/supportsAsync}} - ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; - } - - /// - /// Initializes a new instance of the class. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// - /// - public {{classname}}(HttpClient client, HttpClientHandler handler) : this(client, handler, (string)null) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// The target service's base path in URL format. - /// - /// - /// - public {{classname}}(HttpClient client, HttpClientHandler handler, String basePath) - { if (client == null) throw new ArgumentNullException("client"); - if (handler == null) throw new ArgumentNullException("handler"); - - this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( - {{packageName}}.Client.GlobalConfiguration.Instance, - new {{packageName}}.Client.Configuration { BasePath = basePath } - ); - this.ApiClient = new {{packageName}}.Client.ApiClient(client, handler, this.Configuration.BasePath); - this.Client = this.ApiClient; - {{#supportsAsync}} - this.AsynchronousClient = this.ApiClient; - {{/supportsAsync}} - this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; - } - - /// - /// Initializes a new instance of the class using Configuration object. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// An instance of Configuration. - /// - /// - public {{classname}}(HttpClient client, HttpClientHandler handler, {{packageName}}.Client.Configuration configuration) - { - if (configuration == null) throw new ArgumentNullException("configuration"); - if (client == null) throw new ArgumentNullException("client"); - if (handler == null) throw new ArgumentNullException("handler"); this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( {{packageName}}.Client.GlobalConfiguration.Instance, configuration ); - this.ApiClient = new {{packageName}}.Client.ApiClient(client, handler, this.Configuration.BasePath); + this.ApiClient = new {{packageName}}.Client.ApiClient(client, this.Configuration.BasePath, handler); this.Client = this.ApiClient; {{#supportsAsync}} this.AsynchronousClient = this.ApiClient; diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/model.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/model.mustache new file mode 100644 index 000000000000..0de1e05e5140 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/model.mustache @@ -0,0 +1,48 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +{{#models}} +{{#model}} +{{#discriminator}} +using JsonSubTypes; +{{/discriminator}} +{{/model}} +{{/models}} +{{#validatable}} +using System.ComponentModel.DataAnnotations; +{{/validatable}} +using FileParameter = {{packageName}}.Client.FileParameter; +using OpenAPIDateConverter = {{packageName}}.Client.OpenAPIDateConverter; +{{#useCompareNetObjects}} +using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils; +{{/useCompareNetObjects}} +{{#models}} +{{#model}} +{{#oneOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/oneOf}} +{{#aneOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/aneOf}} + +namespace {{packageName}}.{{modelPackage}} +{ +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>modelOneOf}}{{/-first}}{{/oneOf}}{{#anyOf}}{{#-first}}{{>modelAnyOf}}{{/-first}}{{/anyOf}}{{^oneOf}}{{^anyOf}}{{>modelGeneric}}{{/anyOf}}{{/oneOf}}{{/isEnum}} +{{/model}} +{{/models}} +} diff --git a/modules/openapi-generator/src/main/resources/dart-dio/api.mustache b/modules/openapi-generator/src/main/resources/dart-dio/api.mustache index dff1dcd42354..522815498c5c 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/api.mustache @@ -63,10 +63,7 @@ class {{classname}} { ...?extra, }, validateStatus: validateStatus, - contentType: [{{^hasConsumes}} - 'application/json',{{/hasConsumes}}{{#hasConsumes}}{{#consumes}} - '{{{mediaType}}}',{{/consumes}}{{/hasConsumes}} - ].first, + contentType: '{{^hasConsumes}}application/json{{/hasConsumes}}{{#hasConsumes}}{{#prioritizedContentTypes}}{{#-first}}{{{mediaType}}}{{/-first}}{{/prioritizedContentTypes}}{{/hasConsumes}}', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/modules/openapi-generator/src/main/resources/dart-dio/gitignore.mustache b/modules/openapi-generator/src/main/resources/dart-dio/gitignore.mustache index 8092a49d5152..6d2ac22c0b41 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/gitignore.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/gitignore.mustache @@ -30,8 +30,12 @@ pubspec.lock # Don’t commit files and directories created by other development environments. # For example, if your development environment creates any of the following files, # consider putting them in a global ignore file: -*.iml // IntelliJ -*.ipr // IntelliJ -*.iws // IntelliJ -.idea/ // IntelliJ -.DS_Store // Mac + +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ + +# Mac +.DS_Store diff --git a/modules/openapi-generator/src/main/resources/dart-dio/pubspec.mustache b/modules/openapi-generator/src/main/resources/dart-dio/pubspec.mustache index 1d1a328affe5..2484e50837a5 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/pubspec.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/pubspec.mustache @@ -1,16 +1,20 @@ name: {{pubName}} version: {{pubVersion}} description: {{pubDescription}} +homepage: {{pubHomepage}} + environment: - sdk: '>=2.7.0 <3.0.0' + sdk: '>=2.7.0 <3.0.0' + dependencies: - dio: '^3.0.9' - built_value: '>=7.1.0 <8.0.0' - built_collection: '>=4.3.2 <5.0.0' + dio: '^3.0.9' + built_value: '>=7.1.0 <8.0.0' + built_collection: '>=4.3.2 <5.0.0' {{#timeMachine}} - time_machine: '^0.9.12' + time_machine: '^0.9.12' {{/timeMachine}} + dev_dependencies: - built_value_generator: '>=7.1.0 <8.0.0' - build_runner: any - test: '>=1.3.0 <1.16.0' + built_value_generator: '>=7.1.0 <8.0.0' + build_runner: any + test: '>=1.3.0 <1.16.0' diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/README.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/README.mustache index 454bd6ccdb97..69591ce24a3c 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/README.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/README.mustache @@ -21,25 +21,32 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) * Dart 2.12.0 or later OR Flutter 1.26.0 or later * Dio 4.0.0+ +{{#useDateLibTimeMachine}} * timemachine option currently **DOES NOT** support sound null-safety and may not work +{{/useDateLibTimeMachine}} ## Installation & Usage +### pub.dev +To use the package from [pub.dev](https://pub.dev), please include the following in pubspec.yaml +```yaml +dependencies: + {{pubName}}: {{pubVersion}} +``` + ### Github If this Dart package is published to Github, please include the following in pubspec.yaml -``` -name: {{pubName}} -version: {{pubVersion}} -description: {{pubDescription}} +```yaml dependencies: {{pubName}}: - git: https://github.com/{{gitUserId}}/{{gitRepoId}}.git - version: 'any' + git: + url: https://github.com/{{gitUserId}}/{{gitRepoId}}.git + #ref: main ``` -### Local -To use the package in your local drive, please include the following in pubspec.yaml -``` +### Local development +To use the package from your local drive, please include the following in pubspec.yaml +```yaml dependencies: {{pubName}}: path: /path/to/{{pubName}} @@ -53,9 +60,9 @@ Please follow the [installation procedure](#installation--usage) and then run th import 'package:{{pubName}}/{{pubName}}.dart'; {{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} -final api = {{classname}}(); +final api = {{clientName}}().get{{classname}}(); {{#allParams}} -final {{paramName}} = {{#isArray}}[{{/isArray}}{{#isBodyParam}}{{dataType}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isArray}}]{{/isArray}}; // {{{dataType}}} | {{{description}}} +final {{{dataType}}} {{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}} {{/allParams}} try { @@ -75,7 +82,7 @@ All URIs are relative to *{{basePath}}* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}[*{{classname}}*]({{modelDocPath}}{{{classname}}}.md) | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} ## Documentation For Models diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/api.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/api.mustache index 34cf9554991c..5182266d24b9 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/api.mustache @@ -19,9 +19,29 @@ class {{classname}} { const {{classname}}(this._dio{{#useBuiltValue}}, this._serializers{{/useBuiltValue}}); {{#operation}} - /// {{{summary}}} + /// {{#summary}}{{.}}{{/summary}}{{^summary}}{{nickname}}{{/summary}} + /// {{notes}} /// - /// {{{notes}}} + /// Parameters: + {{#allParams}} + /// * [{{paramName}}] {{#description}}- {{{.}}}{{/description}} + {{/allParams}} + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future]{{#returnType}} containing a [Response] with a [{{{returnType}}}] as data{{/returnType}} + /// Throws [DioError] if API call or serialization fails + {{#externalDocs}} + /// {{description}} + /// Also see [{{summary}} Documentation]({{url}}) + {{/externalDocs}} + {{#isDeprecated}} + @Deprecated('This operation has been deprecated') + {{/isDeprecated}} Future> {{nickname}}({ {{#allParams}}{{#isPathParam}} required {{{dataType}}} {{paramName}},{{/isPathParam}}{{#isQueryParam}} {{#required}}required {{/required}}{{{dataType}}}{{^required}}?{{/required}} {{paramName}},{{/isQueryParam}}{{#isHeaderParam}} @@ -60,11 +80,8 @@ class {{classname}} { },{{/authMethods}} ],{{/hasAuthMethods}} ...?extra, - }, - contentType: [{{^hasConsumes}} - 'application/json',{{/hasConsumes}}{{#hasConsumes}}{{#consumes}} - '{{{mediaType}}}',{{/consumes}}{{/hasConsumes}} - ].first, + },{{#hasConsumes}} + contentType: '{{#prioritizedContentTypes}}{{#-first}}{{{mediaType}}}{{/-first}}{{/prioritizedContentTypes}}',{{/hasConsumes}} validateStatus: validateStatus, ); @@ -79,7 +96,7 @@ class {{classname}} { try { {{#useBuiltValue}}{{>serialization/built_value/serialize}}{{/useBuiltValue}} - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -88,7 +105,7 @@ class {{classname}} { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } {{/hasBodyOrFormParams}} @@ -107,13 +124,13 @@ class {{classname}} { try { {{#useBuiltValue}}{{>serialization/built_value/deserialize}}{{/useBuiltValue}} - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response<{{{returnType}}}>( diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/api_doc.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/api_doc.mustache index 1e28b16012e4..548c8b140ce2 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/api_doc.mustache @@ -45,17 +45,17 @@ import 'package:{{pubName}}/api.dart'; {{/authMethods}} {{/hasAuthMethods}} -var api_instance = new {{classname}}(); +final api = {{clientName}}().get{{classname}}(); {{#allParams}} -var {{paramName}} = {{#isArray}}[{{/isArray}}{{#isBodyParam}}new {{{dataType}}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isArray}}]{{/isArray}}; // {{{dataType}}} | {{{description}}} +final {{{dataType}}} {{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}} {{/allParams}} try { - {{#returnType}}var result = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + {{#returnType}}final response = {{/returnType}}api.{{{operationId}}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); {{#returnType}} - print(result); + print(response); {{/returnType}} -} catch (e) { +} catch on DioError (e) { print('Exception when calling {{classname}}->{{operationId}}: $e\n'); } ``` @@ -64,12 +64,12 @@ try { {{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} Name | Type | Description | Notes ------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} -{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{baseType}}.md){{/isPrimitiveType}}| {{{description}}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{{defaultValue}}}]{{/defaultValue}} +{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}}| {{{description}}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{{defaultValue}}}]{{/defaultValue}} {{/allParams}} ### Return type -{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} +{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} ### Authorization diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/gitignore.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/gitignore.mustache index 8092a49d5152..6d2ac22c0b41 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/gitignore.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/gitignore.mustache @@ -30,8 +30,12 @@ pubspec.lock # Don’t commit files and directories created by other development environments. # For example, if your development environment creates any of the following files, # consider putting them in a global ignore file: -*.iml // IntelliJ -*.ipr // IntelliJ -*.iws // IntelliJ -.idea/ // IntelliJ -.DS_Store // Mac + +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ + +# Mac +.DS_Store diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/lib.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/lib.mustache index ff5436626536..32f6a54b1a64 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/lib.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/lib.mustache @@ -3,7 +3,8 @@ export 'package:{{pubName}}/src/api.dart'; export 'package:{{pubName}}/src/auth/api_key_auth.dart'; export 'package:{{pubName}}/src/auth/basic_auth.dart'; export 'package:{{pubName}}/src/auth/oauth.dart'; -{{#useBuiltValue}}export 'package:{{pubName}}/src/serializers.dart';{{/useBuiltValue}} +{{#useBuiltValue}}export 'package:{{pubName}}/src/serializers.dart'; +{{#useDateLibCore}}export 'package:{{pubName}}/src/model/date.dart';{{/useDateLibCore}}{{/useBuiltValue}} {{#apiInfo}}{{#apis}}export 'package:{{pubName}}/src/api/{{classFilename}}.dart'; {{/apis}}{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/object_doc.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/object_doc.mustache index f2a52db11a4b..84b70087bf48 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/object_doc.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/object_doc.mustache @@ -8,7 +8,7 @@ import 'package:{{pubName}}/api.dart'; ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{complexType}}.md){{/isPrimitiveType}} | {{{description}}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{defaultValue}}}]{{/defaultValue}} +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{{description}}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{defaultValue}}}]{{/defaultValue}} {{/vars}} [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/pubspec.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/pubspec.mustache index 204b4e33bae7..991de1e44b52 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/pubspec.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/pubspec.mustache @@ -1,6 +1,7 @@ name: {{pubName}} version: {{pubVersion}} description: {{pubDescription}} +homepage: {{pubHomepage}} environment: sdk: '>=2.12.0 <3.0.0' diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class.mustache index f359b8d5a91b..9eb53c756c78 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class.mustache @@ -7,8 +7,18 @@ part '{{classFilename}}.g.dart'; Classes with polymorphism or composition may generate unused imports, these need to be ignored for said classes so that there are no lint errors. }} -{{#parentModel}}// ignore_for_file: unused_import{{/parentModel}} +{{#parentModel}} +// ignore_for_file: unused_import +{{/parentModel}} +/// {{#description}}{{{.}}}{{/description}}{{^description}}{{classname}}{{/description}} +{{#hasVars}} +/// +/// Properties: +{{#allVars}} +/// * [{{{name}}}] {{#description}}- {{{.}}}{{/description}} +{{/allVars}} +{{/hasVars}} abstract class {{classname}} implements Built<{{classname}}, {{classname}}Builder> { {{#vars}} {{#description}} diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/date.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/date.mustache new file mode 100644 index 000000000000..c3a87eae259c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/date.mustache @@ -0,0 +1,69 @@ +/// A gregorian calendar date generated by +/// OpenAPI generator to differentiate +/// between [DateTime] and [Date] formats. +class Date implements Comparable { + final int year; + + /// January is 1. + final int month; + + /// First day is 1. + final int day; + + Date(this.year, this.month, this.day); + + /// The current date + static Date now({bool utc = false}) { + var now = DateTime.now(); + if (utc) { + now = now.toUtc(); + } + return now.toDate(); + } + + /// Convert to a [DateTime]. + DateTime toDateTime({bool utc = false}) { + if (utc) { + DateTime.utc(year, month, day); + } + return DateTime(year, month, day); + } + + @override + int compareTo(Date other) { + int d = year.compareTo(other.year); + if (d != 0) { + return d; + } + d = month.compareTo(other.month); + if (d != 0) { + return d; + } + return day.compareTo(other.day); + } + + @override + bool operator ==(Object other) => + identical(this, other) || + other is Date && + runtimeType == other.runtimeType && + year == other.year && + month == other.month && + day == other.day; + + @override + int get hashCode => year.hashCode ^ month.hashCode ^ day.hashCode; + + @override + String toString() { + final yyyy = year.toString(); + final mm = month.toString().padLeft(2, '0'); + final dd = day.toString().padLeft(2, '0'); + + return '$yyyy-$mm-$dd'; + } +} + +extension DateTimeToDate on DateTime { + Date toDate() => Date(year, month, day); +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/date_serializer.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/date_serializer.mustache new file mode 100644 index 000000000000..b5f0ed32c22f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/date_serializer.mustache @@ -0,0 +1,28 @@ +{{>header}} +import 'package:built_collection/built_collection.dart'; +import 'package:built_value/serializer.dart'; +import 'package:{{pubName}}/src/model/date.dart'; + +class DateSerializer implements PrimitiveSerializer { + + const DateSerializer(); + + @override + Iterable get types => BuiltList.of([Date]); + + @override + String get wireName => 'Date'; + + @override + Date deserialize(Serializers serializers, Object serialized, + {FullType specifiedType = FullType.unspecified}) { + final parsed = DateTime.parse(serialized as String); + return Date(parsed.year, parsed.month, parsed.day); + } + + @override + Object serialize(Serializers serializers, Date date, + {FullType specifiedType = FullType.unspecified}) { + return date.toString(); + } +} diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/local_date_serializer.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/offset_date_serializer.mustache similarity index 96% rename from modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/local_date_serializer.mustache rename to modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/offset_date_serializer.mustache index 68cfd5e31c68..2698caf0f493 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/local_date_serializer.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/offset_date_serializer.mustache @@ -8,7 +8,7 @@ class OffsetDateSerializer implements PrimitiveSerializer { const OffsetDateSerializer(); @override - Iterable get types => BuiltList([OffsetDate]); + Iterable get types => BuiltList.of([OffsetDate]); @override String get wireName => 'OffsetDate'; diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serialize.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serialize.mustache index 5794f34ad1ad..03d38c93878d 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serialize.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serialize.mustache @@ -1,13 +1,13 @@ {{#hasFormParams}} _bodyData = {{#isMultipart}}FormData.fromMap({{/isMultipart}}{ {{#formParams}} - {{^required}}{{^isNullable}}if ({{{paramName}}} != null) {{/isNullable}}{{/required}}r'{{{baseName}}}': {{#isFile}}MultipartFile.fromBytes({{{paramName}}}, filename: r'{{{baseName}}}'){{/isFile}}{{^isFile}}encodeFormParameter(_serializers, {{{paramName}}}, const FullType({{^isContainer}}{{{baseType}}}{{/isContainer}}{{#isContainer}}Built{{#isMap}}Map{{/isMap}}{{#isArray}}{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}{{/isArray}}, [{{#isMap}}FullType(String), {{/isMap}}FullType({{{baseType}}})]{{/isContainer}})){{/isFile}}, + {{^required}}{{^isNullable}}if ({{{paramName}}} != null) {{/isNullable}}{{/required}}r'{{{baseName}}}': {{#isFile}}{{{paramName}}}{{/isFile}}{{^isFile}}encodeFormParameter(_serializers, {{{paramName}}}, const FullType({{^isContainer}}{{{baseType}}}{{/isContainer}}{{#isContainer}}Built{{#isMap}}Map{{/isMap}}{{#isArray}}{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}{{/isArray}}, [{{#isMap}}FullType(String), {{/isMap}}FullType({{{baseType}}})]{{/isContainer}})){{/isFile}}, {{/formParams}} }{{#isMultipart}}){{/isMultipart}}; {{/hasFormParams}} {{#bodyParam}} {{#isPrimitiveType}} - _bodyData = {{paramName}}; + _bodyData = {{paramName}}{{#isFile}}.finalize(){{/isFile}}; {{/isPrimitiveType}} {{^isPrimitiveType}} {{#isContainer}} diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache index afca0bc138f9..10925bc11120 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache @@ -1,11 +1,15 @@ {{>header}} +// ignore_for_file: unused_import + import 'package:built_collection/built_collection.dart'; import 'package:built_value/json_object.dart'; import 'package:built_value/serializer.dart'; import 'package:built_value/standard_json_plugin.dart'; -{{#useDateLibCore}}import 'package:built_value/iso_8601_date_time_serializer.dart';{{/useDateLibCore}} +{{#useDateLibCore}}import 'package:built_value/iso_8601_date_time_serializer.dart'; +import 'package:{{pubName}}/src/date_serializer.dart'; +import 'package:{{pubName}}/src/model/date.dart';{{/useDateLibCore}} {{#useDateLibTimeMachine}}import 'package:time_machine/time_machine.dart'; -import 'package:{{pubName}}/src/local_date_serializer.dart';{{/useDateLibTimeMachine}} +import 'package:{{pubName}}/src/offset_date_serializer.dart';{{/useDateLibTimeMachine}} {{#models}}{{#model}}import 'package:{{pubName}}/src/model/{{classFilename}}.dart'; {{/model}}{{/models}} part 'serializers.g.dart'; @@ -25,8 +29,9 @@ Serializers serializers = (_$serializers.toBuilder(){{#apiInfo}}{{#apis}}{{#seri {{/isMap}} ){{/serializers}}{{/apis}}{{/apiInfo}}{{#useDateLibTimeMachine}} ..add(const OffsetDateSerializer()) - ..add(const OffsetDateTimeSerializer()){{/useDateLibTimeMachine}} - ..add(Iso8601DateTimeSerializer())) + ..add(const OffsetDateTimeSerializer()){{/useDateLibTimeMachine}}{{#useDateLibCore}} + ..add(const DateSerializer()) + ..add(Iso8601DateTimeSerializer())){{/useDateLibCore}} .build(); Serializers standardSerializers = diff --git a/modules/openapi-generator/src/main/resources/dart2/api.mustache b/modules/openapi-generator/src/main/resources/dart2/api.mustache index d99ba2b325f6..a7bb92891431 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api.mustache @@ -95,43 +95,41 @@ class {{{classname}}} { {{/headerParams}} {{/hasHeaderParams}} - final contentTypes = [{{#consumes}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/consumes}}]; + final contentTypes = [{{#prioritizedContentTypes}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/prioritizedContentTypes}}]; final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = [{{#authMethods}}'{{{name}}}'{{^-last}}, {{/-last}}{{/authMethods}}]; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - {{#formParams}} - {{^isFile}} - if ({{{paramName}}} != null) { - hasFields = true; - mp.fields[r'{{{baseName}}}'] = parameterToString({{{paramName}}}); - } - {{/isFile}} - {{#isFile}} - if ({{{paramName}}} != null) { - hasFields = true; - mp.fields[r'{{{baseName}}}'] = {{{paramName}}}.field; - mp.files.add({{{paramName}}}); - } - {{/isFile}} - {{/formParams}} - if (hasFields) { - postBody = mp; - } - } else { - {{#formParams}} - {{^isFile}} - if ({{{paramName}}} != null) { - formParams[r'{{{baseName}}}'] = parameterToString({{{paramName}}}); - } - {{/isFile}} - {{/formParams}} + {{#isMultipart}} + bool hasFields = false; + final mp = MultipartRequest('{{{httpMethod}}}', Uri.parse(path)); + {{#formParams}} + {{^isFile}} + if ({{{paramName}}} != null) { + hasFields = true; + mp.fields[r'{{{baseName}}}'] = parameterToString({{{paramName}}}); + } + {{/isFile}} + {{#isFile}} + if ({{{paramName}}} != null) { + hasFields = true; + mp.fields[r'{{{baseName}}}'] = {{{paramName}}}.field; + mp.files.add({{{paramName}}}); + } + {{/isFile}} + {{/formParams}} + if (hasFields) { + postBody = mp; + } + {{/isMultipart}} + {{^isMultipart}} + {{#formParams}} + {{^isFile}} + if ({{{paramName}}} != null) { + formParams[r'{{{baseName}}}'] = parameterToString({{{paramName}}}); } + {{/isFile}} + {{/formParams}} + {{/isMultipart}} return await apiClient.invokeAPI( path, diff --git a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache index 167b6951e018..f3af060d514d 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache @@ -84,7 +84,7 @@ class ApiClient { ? '?${urlEncodedQueryParams.join('&')}' : ''; - final url = '$basePath$path$queryString'; + final Uri uri = Uri.parse('$basePath$path$queryString'); if (nullableContentType != null) { headerParams['Content-Type'] = nullableContentType; @@ -96,7 +96,7 @@ class ApiClient { body is MultipartFile && (nullableContentType == null || !nullableContentType.toLowerCase().startsWith('multipart/form-data')) ) { - final request = StreamedRequest(method, Uri.parse(url)); + final request = StreamedRequest(method, uri); request.headers.addAll(headerParams); request.contentLength = body.length; body.finalize().listen( @@ -110,7 +110,7 @@ class ApiClient { } if (body is MultipartRequest) { - final request = MultipartRequest(method, Uri.parse(url)); + final request = MultipartRequest(method, uri); request.fields.addAll(body.fields); request.files.addAll(body.files); request.headers.addAll(body.headers); @@ -125,12 +125,12 @@ class ApiClient { final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; switch(method) { - case 'POST': return await _client.post(url, headers: nullableHeaderParams, body: msgBody,); - case 'PUT': return await _client.put(url, headers: nullableHeaderParams, body: msgBody,); - case 'DELETE': return await _client.delete(url, headers: nullableHeaderParams,); - case 'PATCH': return await _client.patch(url, headers: nullableHeaderParams, body: msgBody,); - case 'HEAD': return await _client.head(url, headers: nullableHeaderParams,); - case 'GET': return await _client.get(url, headers: nullableHeaderParams,); + case 'POST': return await _client.post(uri, headers: nullableHeaderParams, body: msgBody,); + case 'PUT': return await _client.put(uri, headers: nullableHeaderParams, body: msgBody,); + case 'DELETE': return await _client.delete(uri, headers: nullableHeaderParams,); + case 'PATCH': return await _client.patch(uri, headers: nullableHeaderParams, body: msgBody,); + case 'HEAD': return await _client.head(uri, headers: nullableHeaderParams,); + case 'GET': return await _client.get(uri, headers: nullableHeaderParams,); } } on SocketException catch (e, trace) { throw ApiException.withInner(HttpStatus.badRequest, 'Socket operation failed: $method $path', e, trace,); diff --git a/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache b/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache index 40f4fda731ee..28f734e55879 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache @@ -10,6 +10,7 @@ class ApiException implements Exception { Exception innerException; StackTrace stackTrace; + @override String toString() { if (message == null) { return 'ApiException'; diff --git a/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache b/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache index 92f394176f61..e99fbb0505d5 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache @@ -19,7 +19,7 @@ Iterable _convertParametersForCollectionFormat( final params = []; // preconditions - if (name != null && !name.isEmpty && value != null) { + if (name != null && name.isNotEmpty && value != null) { if (value is List) { // get the collection format, default: csv collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) diff --git a/modules/openapi-generator/src/main/resources/dart2/build.yaml.mustache b/modules/openapi-generator/src/main/resources/dart2/build.yaml.mustache index b5399b955dbc..89a4dd6e1c2e 100644 --- a/modules/openapi-generator/src/main/resources/dart2/build.yaml.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/build.yaml.mustache @@ -16,4 +16,3 @@ targets: field_rename: none ignore_unannotated: false include_if_null: false - nullable: true diff --git a/modules/openapi-generator/src/main/resources/dart2/pubspec.mustache b/modules/openapi-generator/src/main/resources/dart2/pubspec.mustache index 9de3cbd23149..4ce12df9e486 100644 --- a/modules/openapi-generator/src/main/resources/dart2/pubspec.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/pubspec.mustache @@ -5,19 +5,17 @@ name: '{{{pubName}}}' version: '{{{pubVersion}}}' description: '{{{pubDescription}}}' -authors: - - '{{{pubAuthor}}} <{{{pubAuthorEmail}}}>' homepage: '{{{pubHomepage}}}' environment: - sdk: '>=2.0.0 <3.0.0' + sdk: '>=2.12.0 <3.0.0' dependencies: - http: '>=0.12.0 <0.13.0' - intl: '^0.16.1' + http: '>=0.13.0 <0.14.0' + intl: '^0.17.0' meta: '^1.1.8' {{#json_serializable}} json_annotation: '^3.1.1'{{/json_serializable}} dev_dependencies: - test: '>=1.3.0 <1.16.0' + test: '>=1.16.0 <1.18.0' {{#json_serializable}} - build_runner: '^1.0.0' + build_runner: '^1.10.9' json_serializable: '^3.5.1'{{/json_serializable}} diff --git a/modules/openapi-generator/src/main/resources/erlang-server/rebar.config.mustache b/modules/openapi-generator/src/main/resources/erlang-server/rebar.config.mustache index 7ddca0f30279..743b108f384a 100644 --- a/modules/openapi-generator/src/main/resources/erlang-server/rebar.config.mustache +++ b/modules/openapi-generator/src/main/resources/erlang-server/rebar.config.mustache @@ -1,6 +1,6 @@ {deps, [ - {cowboy, {git, "https://github.com/ninenines/cowboy.git", {tag, "2.5.0"}}}, + {cowboy, {git, "https://github.com/ninenines/cowboy.git", {tag, "2.8.0"}}}, {rfc3339, {git, "https://github.com/talentdeficit/rfc3339.git", {tag, "master"}}}, - {jsx, {git, "https://github.com/talentdeficit/jsx.git", {tag, "2.9.0"}}}, - {jesse, {git, "https://github.com/for-GET/jesse.git", {tag, "1.5.2"}}} + {jsx, {git, "https://github.com/talentdeficit/jsx.git", {tag, "v3.1.0"}}}, + {jesse, {git, "https://github.com/for-GET/jesse.git", {tag, "1.5.6"}}} ]}. diff --git a/modules/openapi-generator/src/main/resources/go-echo-server/Dockerfile.mustache b/modules/openapi-generator/src/main/resources/go-echo-server/Dockerfile.mustache new file mode 100644 index 000000000000..bd60366b27fb --- /dev/null +++ b/modules/openapi-generator/src/main/resources/go-echo-server/Dockerfile.mustache @@ -0,0 +1,11 @@ +FROM golang:1.16-alpine3.13 as build-env +RUN apk add --no-cache git gcc +RUN mkdir /app +WORKDIR /app +COPY . . +RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o {{packageName}} +FROM alpine:3.13 +COPY --from=build-env /app/{{packageName}} . +EXPOSE 8080/tcp +USER 1001 +ENTRYPOINT ["./{{packageName}}"] \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/go-echo-server/README.mustache b/modules/openapi-generator/src/main/resources/go-echo-server/README.mustache new file mode 100644 index 000000000000..9ff2b9aeb19f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/go-echo-server/README.mustache @@ -0,0 +1,44 @@ +# Go Echo API Server for {{packageName}} + +{{#appDescriptionWithNewLines}} +{{{appDescriptionWithNewLines}}} +{{/appDescriptionWithNewLines}} + +## Overview +This server was generated by the [openapi-generator] +(https://openapi-generator.tech) project. +By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. +- + +To see how to make this your own, look here: + +[README](https://openapi-generator.tech) + +- API version: {{appVersion}}{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}}{{/hideGenerationTimestamp}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +### Running the server + +To run the server, follow these simple steps: + +``` +go mod download +go build -o app +``` + +To run the server in a docker container +``` +docker build --network=host -t {{{packageName}}} . +``` + +Once the image is built, just run +``` +docker run --rm -it {{{packageName}}} +``` + +### Known Issue + +TBA \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/go-echo-server/api.mustache b/modules/openapi-generator/src/main/resources/go-echo-server/api.mustache new file mode 100644 index 000000000000..9ac9ad29838a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/go-echo-server/api.mustache @@ -0,0 +1,15 @@ +package handlers +{{#operations}} +import ( + "github.com/{{{gitUserId}}}/{{{gitRepoId}}}/models" + "github.com/labstack/echo/v4" + "net/http" +){{#operation}} + +// {{nickname}} - {{{summary}}} +func (c *Container) {{operationId}}(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} +{{/operation}}{{/operations}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/go-echo-server/go-mod.mustache b/modules/openapi-generator/src/main/resources/go-echo-server/go-mod.mustache new file mode 100644 index 000000000000..4b31aa41c83c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/go-echo-server/go-mod.mustache @@ -0,0 +1,5 @@ +module github.com/{{{gitUserId}}}/{{{gitRepoId}}} + +go 1.16 + +require github.com/labstack/echo/v4 v4.2.0 diff --git a/modules/openapi-generator/src/main/resources/go-echo-server/handler-container.mustache b/modules/openapi-generator/src/main/resources/go-echo-server/handler-container.mustache new file mode 100644 index 000000000000..330a32f51534 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/go-echo-server/handler-container.mustache @@ -0,0 +1,11 @@ +package handlers + +// Container will hold all dependencies for your application. +type Container struct { +} + +// NewContainer returns an empty or an initialized container for your handlers. +func NewContainer() (Container, error) { + c := Container{} + return c, nil +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/go-echo-server/hello-world.mustache b/modules/openapi-generator/src/main/resources/go-echo-server/hello-world.mustache new file mode 100644 index 000000000000..98b4d20cb613 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/go-echo-server/hello-world.mustache @@ -0,0 +1,6 @@ +package models + +// HelloWorld is a sample data structure to make sure each endpoint return something. +type HelloWorld struct { + Message string `json:"message"` +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/go-echo-server/main.mustache b/modules/openapi-generator/src/main/resources/go-echo-server/main.mustache new file mode 100644 index 000000000000..ef0421cdd111 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/go-echo-server/main.mustache @@ -0,0 +1,26 @@ +package main + +import ( + "github.com/{{{gitUserId}}}/{{{gitRepoId}}}/handlers" + "github.com/labstack/echo/v4" + "github.com/labstack/echo/v4/middleware" +) + +func main() { + e := echo.New() + + //todo: handle the error! + c, _ := handlers.NewContainer() + + // Middleware + e.Use(middleware.Logger()) + e.Use(middleware.Recover()) + +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} + // {{nickname}} - {{{summary}}} + e.{{httpMethod.toUpperCase}}("{{{basePathWithoutHost}}}{{{path}}}", c.{{operationId}}) +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + + // Start server + e.Logger.Fatal(e.Start(":{{serverPort}}")) +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/go-echo-server/model.mustache b/modules/openapi-generator/src/main/resources/go-echo-server/model.mustache new file mode 100644 index 000000000000..ef59462f11ea --- /dev/null +++ b/modules/openapi-generator/src/main/resources/go-echo-server/model.mustache @@ -0,0 +1,23 @@ +package models +{{#models}}{{#imports}} +{{#-first}}import ( +{{/-first}} "{{import}}"{{#-last}} +) +{{/-last}}{{/imports}}{{#model}}{{#isEnum}}{{#description}}// {{{classname}}} : {{{description}}}{{/description}} +type {{{classname}}} {{^format}}{{dataType}}{{/format}}{{#format}}{{{format}}}{{/format}} + +// List of {{{classname}}} +const ( + {{#allowableValues}} + {{#enumVars}} + {{#enumClassPrefix}}{{{classname.toUpperCase}}}_{{/enumClassPrefix}}{{name}} {{{classname}}} = {{{value}}} + {{/enumVars}} + {{/allowableValues}} +){{/isEnum}}{{^isEnum}}{{#description}} +// {{classname}} - {{{description}}}{{/description}} +type {{classname}} struct { +{{#vars}}{{#description}} + // {{{description}}}{{/description}} + {{name}} {{#isNullable}}*{{/isNullable}}{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}` +{{/vars}} +}{{/isEnum}}{{/model}}{{/models}} diff --git a/modules/openapi-generator/src/main/resources/go-echo-server/openapi.mustache b/modules/openapi-generator/src/main/resources/go-echo-server/openapi.mustache new file mode 100644 index 000000000000..51ebafb0187d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/go-echo-server/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/build.gradle.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/build.gradle.mustache index 415a8c255744..c5d0f13b5e1a 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/build.gradle.mustache @@ -7,18 +7,18 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' {{#jvm-retrofit2}} - ext.retrofitVersion = '2.7.2' + ext.retrofitVersion = '2.9.0' {{/jvm-retrofit2}} {{#useRxJava}} ext.rxJavaVersion = '1.3.8' {{/useRxJava}} {{#useRxJava2}} - ext.rxJava2Version = '2.2.20' + ext.rxJava2Version = '2.2.21' {{/useRxJava2}} {{#useRxJava3}} - ext.rxJava3Version = '3.0.10' + ext.rxJava3Version = '3.0.12' {{/useRxJava3}} repositories { @@ -52,65 +52,73 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" {{#moshi}} {{^moshiCodeGen}} - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" {{/moshiCodeGen}} {{#moshiCodeGen}} - compile "com.squareup.moshi:moshi:1.11.0" - kapt "com.squareup.moshi:moshi-kotlin-codegen:1.11.0" + implementation "com.squareup.moshi:moshi:1.12.0" + kapt "com.squareup.moshi:moshi-kotlin-codegen:1.12.0" {{/moshiCodeGen}} {{/moshi}} {{#gson}} - compile "com.google.code.gson:gson:2.8.6" + implementation "com.google.code.gson:gson:2.8.7" {{/gson}} {{#jackson}} - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.fasterxml.jackson.module:jackson-module-kotlin:2.12.1" - compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.12.1" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.12.3" + implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.12.3" {{/jackson}} {{#kotlinx_serialization}} - compile "org.jetbrains.kotlinx:kotlinx-serialization-json:1.1.0" + implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.1" {{/kotlinx_serialization}} {{#jvm-okhttp3}} - compile "com.squareup.okhttp3:okhttp:3.12.13" + implementation "com.squareup.okhttp3:okhttp:3.12.13" {{/jvm-okhttp3}} {{#jvm-okhttp4}} - compile "com.squareup.okhttp3:okhttp:4.9.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" {{/jvm-okhttp4}} {{#threetenbp}} - compile "org.threeten:threetenbp:1.5.0" + implementation "org.threeten:threetenbp:1.5.1" {{/threetenbp}} {{#jvm-retrofit2}} {{#hasOAuthMethods}} - compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.0" + implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2" {{/hasOAuthMethods}} - compile "com.squareup.okhttp3:logging-interceptor:4.9.0" + implementation "com.squareup.okhttp3:logging-interceptor:4.9.1" {{#useRxJava}} - compile "io.reactivex:rxjava:$rxJavaVersion" - compile "com.squareup.retrofit2:adapter-rxjava:$retrofitVersion" + implementation "io.reactivex:rxjava:$rxJavaVersion" + implementation "com.squareup.retrofit2:adapter-rxjava:$retrofitVersion" {{/useRxJava}} {{#useRxJava2}} - compile "io.reactivex.rxjava2:rxjava:$rxJava2Version" - compile "com.squareup.retrofit2:adapter-rxjava2:$retrofitVersion" + implementation "io.reactivex.rxjava2:rxjava:$rxJava2Version" + implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofitVersion" {{/useRxJava2}} {{#useRxJava3}} - compile "io.reactivex.rxjava3:rxjava:$rxJava3Version" - compile "com.squareup.retrofit2:adapter-rxjava3:2.9.0" + implementation "io.reactivex.rxjava3:rxjava:$rxJava3Version" + implementation "com.squareup.retrofit2:adapter-rxjava3:2.9.0" {{/useRxJava3}} - compile "com.squareup.retrofit2:retrofit:$retrofitVersion" + implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" {{#gson}} - compile "com.squareup.retrofit2:converter-gson:$retrofitVersion" + implementation "com.squareup.retrofit2:converter-gson:$retrofitVersion" {{/gson}} {{#moshi}} - compile "com.squareup.retrofit2:converter-moshi:$retrofitVersion" + implementation "com.squareup.retrofit2:converter-moshi:$retrofitVersion" {{/moshi}} {{#kotlinx_serialization}} - compile "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0" + implementation "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0" {{/kotlinx_serialization}} - compile "com.squareup.retrofit2:converter-scalars:$retrofitVersion" + implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion" {{/jvm-retrofit2}} - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } +{{#kotlinx_serialization}} + +tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach { + kotlinOptions { + freeCompilerArgs += "-Xopt-in=kotlinx.serialization.ExperimentalSerializationApi" + } +} +{{/kotlinx_serialization}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache index b83b7aff9527..f840db6e394e 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache @@ -25,7 +25,6 @@ import kotlinx.serialization.Contextual {{#parcelizeModels}} import android.os.Parcelable import kotlinx.parcelize.Parcelize - {{/parcelizeModels}} {{/multiplatform}} {{#multiplatform}} @@ -70,6 +69,9 @@ import java.io.Serializable * {{{description}}} * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} */ + {{#kotlinx_serialization}} + {{#serializableModel}}@KSerializable{{/serializableModel}}{{^serializableModel}}@Serializable{{/serializableModel}} + {{/kotlinx_serialization}} {{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{{nameInCamelCase}}}(val value: {{^isContainer}}{{dataType}}{{/isContainer}}{{#isContainer}}kotlin.String{{/isContainer}}) { {{#allowableValues}} {{#enumVars}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache index 88d6c278ea2b..2071a6b537a2 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache @@ -22,7 +22,7 @@ import kotlinx.serialization.internal.CommonEnumSerializer * {{{description}}} * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} */ -{{#multiplatform}}@Serializable(with = {{classname}}.Serializer::class){{/multiplatform}}{{#kotlinx_serialization}}@Serializable(with = {{classname}}.Serializer::class){{/kotlinx_serialization}} +{{#multiplatform}}@Serializable(with = {{classname}}.Serializer::class){{/multiplatform}}{{#kotlinx_serialization}}@Serializable{{/kotlinx_serialization}} {{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{classname}}(val value: {{{dataType}}}) { {{#allowableValues}}{{#enumVars}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/infrastructure/RequestConfig.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/infrastructure/RequestConfig.kt.mustache index 61677c22afff..ef1b0517e78d 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/infrastructure/RequestConfig.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/infrastructure/RequestConfig.kt.mustache @@ -8,10 +8,10 @@ package {{packageName}}.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -{{#nonPublicApi}}internal {{/nonPublicApi}}data class RequestConfig( +{{#nonPublicApi}}internal {{/nonPublicApi}}data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/BigDecimalAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/BigDecimalAdapter.kt.mustache index 5efc613a20e5..609d15a34d3c 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/BigDecimalAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/BigDecimalAdapter.kt.mustache @@ -1,5 +1,6 @@ package {{packageName}}.infrastructure +{{#kotlinx_serialization}} import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializer import kotlinx.serialization.encoding.Decoder @@ -7,13 +8,26 @@ import kotlinx.serialization.encoding.Encoder import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.SerialDescriptor +{{/kotlinx_serialization}} +{{#moshi}} +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +{{/moshi}} import java.math.BigDecimal -@Serializer(forClass = BigDecimal::class) +{{#kotlinx_serialization}}@Serializer(forClass = BigDecimal::class) object BigDecimalAdapter : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("BigDecimal", PrimitiveKind.STRING) - override fun deserialize(decoder: Decoder): BigDecimal = BigDecimal(decoder.decodeString()) - override fun serialize(encoder: Encoder, value: BigDecimal) = encoder.encodeString(value.toPlainString()) -} \ No newline at end of file +}{{/kotlinx_serialization}}{{#moshi}}{{#nonPublicApi}}internal {{/nonPublicApi}}class BigDecimalAdapter { + @ToJson + fun toJson(value: BigDecimal): String { + return value.toPlainString() + } + + @FromJson + fun fromJson(value: String): BigDecimal { + return BigDecimal(value) + } +}{{/moshi}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/BigIntegerAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/BigIntegerAdapter.kt.mustache index bd2b4d3c8e9b..2924e8f63a2b 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/BigIntegerAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/BigIntegerAdapter.kt.mustache @@ -1,5 +1,6 @@ package {{packageName}}.infrastructure +{{#kotlinx_serialization}} import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializer import kotlinx.serialization.encoding.Decoder @@ -7,12 +8,16 @@ import kotlinx.serialization.encoding.Encoder import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.SerialDescriptor +{{/kotlinx_serialization}} +{{#moshi}} +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +{{/moshi}} import java.math.BigInteger -@Serializer(forClass = BigInteger::class) +{{#kotlinx_serialization}}@Serializer(forClass = BigInteger::class) object BigIntegerAdapter : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("BigInteger", PrimitiveKind.STRING) - override fun deserialize(decoder: Decoder): BigInteger { return BigInteger(decoder.decodeString()) } @@ -20,4 +25,14 @@ object BigIntegerAdapter : KSerializer { override fun serialize(encoder: Encoder, value: BigInteger) { encoder.encodeString(value.toString()) } -} \ No newline at end of file +}{{/kotlinx_serialization}}{{#moshi}}{{#nonPublicApi}}internal {{/nonPublicApi}}class BigIntegerAdapter { + @ToJson + fun toJson(value: BigInteger): String { + return value.toString() + } + + @FromJson + fun fromJson(value: String): BigInteger { + return BigInteger(value) + } +}{{/moshi}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache index e9ed019095e0..31b83578e7eb 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache @@ -60,9 +60,12 @@ import java.util.concurrent.atomic.AtomicLong .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) {{^moshiCodeGen}} .add(KotlinJsonAdapterFactory()) {{/moshiCodeGen}} + .add(BigDecimalAdapter()) + .add(BigIntegerAdapter()) @JvmStatic val moshi: Moshi by lazy { @@ -102,8 +105,8 @@ import java.util.concurrent.atomic.AtomicLong contextual(AtomicInteger::class, AtomicIntegerAdapter) contextual(AtomicLong::class, AtomicLongAdapter) contextual(AtomicBoolean::class, AtomicBooleanAdapter) - contextual(URI::class, UriAdapter) - contextual(URL::class, UrlAdapter) + contextual(URI::class, URIAdapter) + contextual(URL::class, URLAdapter) contextual(StringBuilder::class, StringBuilderAdapter) } diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URIAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URIAdapter.kt.mustache index 0225ccf549bc..c95829555534 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URIAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URIAdapter.kt.mustache @@ -1,5 +1,6 @@ package {{packageName}}.infrastructure +{{#kotlinx_serialization}} import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializer import kotlinx.serialization.encoding.Decoder @@ -7,10 +8,25 @@ import kotlinx.serialization.encoding.Encoder import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.SerialDescriptor +{{/kotlinx_serialization}} +{{#moshi}} +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +{{/moshi}} import java.net.URI +{{#moshi}} +{{#nonPublicApi}}internal {{/nonPublicApi}}class URIAdapter { + @ToJson + fun toJson(uri: URI) = uri.toString() + + @FromJson + fun fromJson(s: String): URI = URI.create(s) +} +{{/moshi}} +{{#kotlinx_serialization}} @Serializer(forClass = URI::class) -object UriAdapter : KSerializer { +object URIAdapter : KSerializer { override fun serialize(encoder: Encoder, value: URI) { encoder.encodeString(value.toASCIIString()) } @@ -18,4 +34,5 @@ object UriAdapter : KSerializer { override fun deserialize(decoder: Decoder): URI = URI(decoder.decodeString()) override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("URI", PrimitiveKind.STRING) -} \ No newline at end of file +} +{{/kotlinx_serialization}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URLAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URLAdapter.kt.mustache index 7105c43b72b6..eaebad52cc8f 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URLAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URLAdapter.kt.mustache @@ -10,7 +10,7 @@ import kotlinx.serialization.descriptors.SerialDescriptor import java.net.URL @Serializer(forClass = URL::class) -object UrlAdapter : KSerializer { +object URLAdapter : KSerializer { override fun serialize(encoder: Encoder, value: URL) { encoder.encodeString(value.toExternalForm()) } diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache index 9781ff529ccd..ea903c36ca99 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache @@ -21,7 +21,7 @@ import java.util.UUID fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } {{/moshi}} {{#kotlinx_serialization}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache index 8adf1980e420..c31f0c2211b8 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache @@ -43,7 +43,7 @@ import {{packageName}}.infrastructure.toMultiValue {{^doNotUseRxAndCoroutines}}{{#useCoroutines}}suspend {{/useCoroutines}}{{/doNotUseRxAndCoroutines}}fun {{operationId}}({{#allParams}}{{{paramName}}}: {{{dataType}}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) : {{#returnType}}{{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}} { val localVariableConfig = {{operationId}}RequestConfig({{#allParams}}{{{paramName}}} = {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) - val localVarResponse = request<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Any?{{/returnType}}>( + val localVarResponse = request<{{#hasBodyParam}}{{#bodyParams}}{{{dataType}}}{{/bodyParams}}{{/hasBodyParam}}{{^hasBodyParam}}{{^hasFormParams}}Unit{{/hasFormParams}}{{#hasFormParams}}Map{{/hasFormParams}}{{/hasBodyParam}}, {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}>( localVariableConfig ) @@ -71,8 +71,8 @@ import {{packageName}}.infrastructure.toMultiValue {{#isDeprecated}} @Deprecated(message = "This operation is deprecated.") {{/isDeprecated}} - fun {{operationId}}RequestConfig({{#allParams}}{{{paramName}}}: {{{dataType}}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) : RequestConfig { - val localVariableBody: kotlin.Any? = {{#hasBodyParam}}{{#bodyParams}}{{{paramName}}}{{/bodyParams}}{{/hasBodyParam}}{{^hasBodyParam}}{{^hasFormParams}}null{{/hasFormParams}}{{#hasFormParams}}mapOf({{#formParams}}"{{{baseName}}}" to {{{paramName}}}{{^-last}}, {{/-last}}{{/formParams}}){{/hasFormParams}}{{/hasBodyParam}} + fun {{operationId}}RequestConfig({{#allParams}}{{{paramName}}}: {{{dataType}}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) : RequestConfig<{{#hasBodyParam}}{{#bodyParams}}{{{dataType}}}{{/bodyParams}}{{/hasBodyParam}}{{^hasBodyParam}}{{^hasFormParams}}Unit{{/hasFormParams}}{{#hasFormParams}}Map{{/hasFormParams}}{{/hasBodyParam}}> { + val localVariableBody = {{#hasBodyParam}}{{#bodyParams}}{{{paramName}}}{{/bodyParams}}{{/hasBodyParam}}{{^hasBodyParam}}{{^hasFormParams}}null{{/hasFormParams}}{{#hasFormParams}}mapOf({{#formParams}}"{{{baseName}}}" to {{{paramName}}}{{^-last}}, {{/-last}}{{/formParams}}){{/hasFormParams}}{{/hasBodyParam}} val localVariableQuery: MultiValueMap = {{^hasQueryParams}}mutableMapOf() {{/hasQueryParams}}{{#hasQueryParams}}mutableMapOf>() .apply { @@ -97,18 +97,16 @@ import {{packageName}}.infrastructure.toMultiValue {{/hasQueryParams}} val localVariableHeaders: MutableMap = mutableMapOf({{#hasFormParams}}"Content-Type" to {{^consumes}}"multipart/form-data"{{/consumes}}{{#consumes.0}}"{{{mediaType}}}"{{/consumes.0}}{{/hasFormParams}}) {{#headerParams}} - {{{paramName}}}?.apply { localVariableHeaders["{{baseName}}"] = {{#isContainer}}this.joinToString(separator = collectionDelimiter("{{collectionFormat}}")){{/isContainer}}{{^isContainer}}this.toString(){{/isContainer}} } + {{{paramName}}}{{^required}}?{{/required}}.apply { localVariableHeaders["{{baseName}}"] = {{#isContainer}}this.joinToString(separator = collectionDelimiter("{{collectionFormat}}")){{/isContainer}}{{^isContainer}}this.toString(){{/isContainer}} } {{/headerParams}} - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.{{httpMethod}}, path = "{{path}}"{{#pathParams}}.replace("{"+"{{baseName}}"+"}", "${{{paramName}}}"){{/pathParams}}, query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } {{/operation}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache index 0d834b1e55c0..64ab00cf9b6d 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache @@ -1,6 +1,13 @@ package {{packageName}}.infrastructure +{{#supportAndroidApiLevel25AndBelow}} +import android.os.Build +{{/supportAndroidApiLevel25AndBelow}} +{{#hasAuthMethods}} +{{#isBasicBasic}} import okhttp3.Credentials +{{/isBasicBasic}} +{{/hasAuthMethods}} import okhttp3.OkHttpClient import okhttp3.RequestBody {{#jvm-okhttp3}} @@ -24,9 +31,10 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody +import java.io.BufferedWriter import java.io.File +import java.io.FileWriter import java.net.URLConnection -import java.util.Date {{^threetenbp}} import java.time.LocalDate import java.time.LocalDateTime @@ -34,6 +42,12 @@ import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime {{/threetenbp}} +import java.util.Date +import java.util.Locale +{{#kotlinx_serialization}} +import kotlinx.serialization.decodeFromString +import kotlinx.serialization.encodeToString +{{/kotlinx_serialization}} {{#threetenbp}} import org.threeten.bp.LocalDate import org.threeten.bp.LocalDateTime @@ -81,14 +95,10 @@ import org.threeten.bp.OffsetTime protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { {{#jvm-okhttp3}} - content is File -> RequestBody.create( - MediaType.parse(mediaType), content - ) + content is File -> RequestBody.create(MediaType.parse(mediaType), content) {{/jvm-okhttp3}} {{#jvm-okhttp4}} - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) {{/jvm-okhttp4}} mediaType == FormDataMediaType -> { MultipartBody.Builder() @@ -149,12 +159,12 @@ import org.threeten.bp.OffsetTime MediaType.parse(mediaType), Serializer.jacksonObjectMapper.writeValueAsString(content) {{/jackson}} {{#kotlinx_serialization}} - MediaType.parse(mediaType), Serializer.jvmJson.decodeFromString(content) + MediaType.parse(mediaType), Serializer.jvmJson.encodeToString(content) {{/kotlinx_serialization}} ) {{/jvm-okhttp3}} {{#jvm-okhttp4}} - mediaType == JsonMediaType -> {{#moshi}}Serializer.moshi.adapter(T::class.java).toJson(content){{/moshi}}{{#gson}}Serializer.gson.toJson(content, T::class.java){{/gson}}{{#jackson}}Serializer.jacksonObjectMapper.writeValueAsString(content){{/jackson}}{{#kotlinx_serialization}}Serializer.jvmJson.decodeFromString(content){{/kotlinx_serialization}}.toRequestBody( + mediaType == JsonMediaType -> {{#moshi}}Serializer.moshi.adapter(T::class.java).toJson(content){{/moshi}}{{#gson}}Serializer.gson.toJson(content, T::class.java){{/gson}}{{#jackson}}Serializer.jacksonObjectMapper.writeValueAsString(content){{/jackson}}{{#kotlinx_serialization}}Serializer.jvmJson.encodeToString(content){{/kotlinx_serialization}}.toRequestBody( mediaType.toMediaTypeOrNull() ) {{/jvm-okhttp4}} @@ -171,14 +181,33 @@ import org.threeten.bp.OffsetTime if (bodyContent.isEmpty()) { return null } + if (T::class.java == File::class.java) { + // return tempfile + {{^supportAndroidApiLevel25AndBelow}} + val f = java.nio.file.Files.createTempFile("tmp.{{packageName}}", null).toFile() + {{/supportAndroidApiLevel25AndBelow}} + {{#supportAndroidApiLevel25AndBelow}} + val f = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + java.nio.file.Files.createTempFile("tmp.net.medicineone.teleconsultationandroid.openapi.openapicommon", null).toFile() + } else { + @Suppress("DEPRECATION") + createTempFile("tmp.net.medicineone.teleconsultationandroid.openapi.openapicommon", null) + } + {{/supportAndroidApiLevel25AndBelow}} + f.deleteOnExit() + val out = BufferedWriter(FileWriter(f)) + out.write(bodyContent) + out.close() + return f as T + } return when(mediaType) { - JsonMediaType -> {{#moshi}}Serializer.moshi.adapter(T::class.java).fromJson(bodyContent){{/moshi}}{{#gson}}Serializer.gson.fromJson(bodyContent, T::class.java){{/gson}}{{#jackson}}Serializer.jacksonObjectMapper.readValue(bodyContent, T::class.java){{/jackson}} + JsonMediaType -> {{#moshi}}Serializer.moshi.adapter(T::class.java).fromJson(bodyContent){{/moshi}}{{#gson}}Serializer.gson.fromJson(bodyContent, T::class.java){{/gson}}{{#jackson}}Serializer.jacksonObjectMapper.readValue(bodyContent, T::class.java){{/jackson}}{{#kotlinx_serialization}}Serializer.jvmJson.decodeFromString(bodyContent){{/kotlinx_serialization}} else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") } } {{#hasAuthMethods}} - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { {{#authMethods}} {{#isApiKey}} {{#isKeyInHeader}} @@ -235,7 +264,7 @@ import org.threeten.bp.OffsetTime } {{/hasAuthMethods}} - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { {{#jvm-okhttp3}} val httpUrl = HttpUrl.parse(baseUrl) ?: throw IllegalStateException("baseUrl is invalid.") {{/jvm-okhttp3}} @@ -276,7 +305,7 @@ import org.threeten.bp.OffsetTime } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -291,57 +320,46 @@ import org.threeten.bp.OffsetTime }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, + response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() ) - response.isInformational -> return Informational( - response.message{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() + response.isInformational -> Informational( + response.message{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, + response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, + response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, accept), - response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, accept), + response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, + response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() ) - response.isClientError -> return ClientError( - response.message{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}?.string(), - response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() + response.isClientError -> ClientError( + response.message{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, + response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}?.string(), + response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, + response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() ) - else -> return ServerError( - response.message{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}?.string(), - response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() + else -> ServerError( + response.message{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, + response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}?.string(), + response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, + response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() ) } } - protected fun parameterToString(value: Any?): String { - when (value) { - null -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + protected fun parameterToString(value: Any?): String = when (value) { + null -> "" + is Array<*> -> toMultiValue(value, "csv").toString() + is Iterable<*> -> toMultiValue(value, "csv").toString() + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApplicationDelegates.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApplicationDelegates.kt.mustache deleted file mode 100644 index 631122631764..000000000000 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApplicationDelegates.kt.mustache +++ /dev/null @@ -1,29 +0,0 @@ -package {{packageName}}.infrastructure - -import kotlin.properties.ReadWriteProperty -import kotlin.reflect.KProperty - -{{#nonPublicApi}}internal {{/nonPublicApi}}object ApplicationDelegates { - /** - * Provides a property delegate, allowing the property to be set once and only once. - * - * If unset (no default value), a get on the property will throw [IllegalStateException]. - */ - fun setOnce(defaultValue: T? = null) : ReadWriteProperty = SetOnce(defaultValue) - - private class SetOnce(defaultValue: T? = null) : ReadWriteProperty { - private var isSet = false - private var value: T? = defaultValue - - override fun getValue(thisRef: Any?, property: KProperty<*>): T { - return value ?: throw IllegalStateException("${property.name} not initialized") - } - - override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = synchronized(this) { - if (!isSet) { - this.value = value - isSet = true - } - } - } -} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/api.mustache index 07bf4667f39c..bca56e88bae6 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/api.mustache @@ -47,6 +47,12 @@ import okhttp3.MultipartBody {{/isMultipart}} {{/x-kotlin-multipart-import}} +{{#operation}} +{{#isResponseFile}} +import okhttp3.ResponseBody + +{{/isResponseFile}} +{{/operation}} interface {{classname}} { {{#operation}} /** diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/OAuthOkHttpClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/OAuthOkHttpClient.kt.mustache index 106b0581994b..5c30002e94bb 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/OAuthOkHttpClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/OAuthOkHttpClient.kt.mustache @@ -13,14 +13,13 @@ import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody +import okhttp3.RequestBody.Companion.toRequestBody class OAuthOkHttpClient( - private var client: OkHttpClient + private var client: OkHttpClient = OkHttpClient() ) : HttpClient { - constructor() : this(OkHttpClient()) - @Throws(OAuthSystemException::class, OAuthProblemException::class) override fun execute( request: OAuthClientRequest, @@ -39,7 +38,7 @@ class OAuthOkHttpClient( } } - val body: RequestBody? = if (request.body != null) RequestBody.create(mediaType, request.body) else null + val body: RequestBody? = if (request.body != null) request.body.toRequestBody(mediaType) else null requestBuilder.method(requestMethod, body) try { @@ -48,6 +47,7 @@ class OAuthOkHttpClient( response.body?.string(), response.body?.contentType()?.toString(), response.code, + response.headers.toMultimap(), responseClass) } catch (e: IOException) { throw OAuthSystemException(e) diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/formParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/formParams.mustache index d5267aa77462..041cad115295 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/formParams.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{^isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{{paramName}}}: {{{dataType}}}{{/isFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field("{{baseName}}"){{/isMultipart}} {{{paramName}}}: MultipartBody.Part{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{^isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{{paramName}}}: {{{dataType}}}{{#required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{/isFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field("{{baseName}}"){{/isMultipart}} {{{paramName}}}: MultipartBody.Part{{^required}}? = null{{/required}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache index aa5a8e346732..f546244307bd 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}@Header("{{baseName}}") {{{paramName}}}: {{{dataType}}}{{/isHeaderParam}} \ No newline at end of file +{{#isHeaderParam}}@Header("{{baseName}}") {{{paramName}}}: {{{dataType}}}{{#required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache index 66e77122a811..2d64978b0c2a 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache @@ -21,10 +21,12 @@ import {{packageName}}.auth.HttpBearerAuth {{/authMethods}} {{/hasAuthMethods}} +import okhttp3.Call import okhttp3.Interceptor import okhttp3.OkHttpClient import retrofit2.Retrofit import okhttp3.logging.HttpLoggingInterceptor +import retrofit2.Converter import retrofit2.converter.scalars.ScalarsConverterFactory {{#useRxJava}} import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory @@ -55,7 +57,8 @@ import okhttp3.MediaType.Companion.toMediaType private var baseUrl: String = defaultBasePath, private val okHttpClientBuilder: OkHttpClient.Builder? = null{{^kotlinx_serialization}}, private val serializerBuilder: {{#gson}}Gson{{/gson}}{{#moshi}}Moshi.{{/moshi}}Builder = Serializer.{{#gson}}gson{{/gson}}{{#moshi}}moshi{{/moshi}}Builder{{/kotlinx_serialization}}, - private val okHttpClient : OkHttpClient? = null + private val callFactory : Call.Factory? = null, + private val converterFactory: Converter.Factory? = null, ) { private val apiAuthorizations = mutableMapOf() var logger: ((String) -> Unit)? = null @@ -81,6 +84,11 @@ import okhttp3.MediaType.Companion.toMediaType {{#kotlinx_serialization}} .addConverterFactory(jvmJson.asConverterFactory("application/json".toMediaType())) {{/kotlinx_serialization}} + .apply { + if (converterFactory != null) { + addConverterFactory(converterFactory) + } + } } private val clientBuilder: OkHttpClient.Builder by lazy { @@ -296,8 +304,8 @@ import okhttp3.MediaType.Companion.toMediaType } fun createService(serviceClass: Class): S { - val usedClient = this.okHttpClient ?: clientBuilder.build() - return retrofitBuilder.client(usedClient).build().create(serviceClass) + val usedCallFactory = this.callFactory ?: clientBuilder.build() + return retrofitBuilder.callFactory(usedCallFactory).build().create(serviceClass) } private fun normalizeBaseUrl() { diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache index 91185a97a565..b1cf9583bdbf 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache @@ -155,7 +155,7 @@ import {{packageName}}.auth.* else request(requestConfig, authNames = authNames) } - protected suspend fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent, authNames: kotlin.collections.List): HttpResponse { + protected suspend inline fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent, authNames: kotlin.collections.List): HttpResponse { requestConfig.updateForAuth(authNames) val headers = requestConfig.headers diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/README.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/README.mustache new file mode 100644 index 000000000000..24c4728fdd3a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/README.mustache @@ -0,0 +1,84 @@ +# {{packageName}} - Kotlin Server library for {{appName}} + +## Requires + +* Kotlin 1.1.2 +* Gradle 3.3 + +## Build + +First, create the gradle wrapper script: + +``` +gradle wrapper +``` + +Then, run: + +``` +./gradlew check assemble +``` + +This runs all tests and packages the library. + +## Features/Implementation Notes + +* Supports JSON inputs/outputs, File inputs, and Form inputs. +* Supports collection formats for query parameters: csv, tsv, ssv, pipes. +* Some Kotlin and Java types are fully qualified to avoid conflicts with types defined in OpenAPI definitions. + +{{#generateApiDocs}} + +## Documentation for API Endpoints + +All URIs are relative to *{{{basePath}}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{{summary}}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +{{/generateApiDocs}} + +{{#generateModelDocs}} + +## Documentation for Models + +{{#modelPackage}} +{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} +{{/modelPackage}} +{{^modelPackage}} +No model defined in this package +{{/modelPackage}} +{{/generateModelDocs}} + +{{! TODO: optional documentation for authorization? }} +## Documentation for Authorization + +{{^authMethods}} +All endpoints do not require authorization. +{{/authMethods}} +{{#authMethods}} +{{#last}} +Authentication schemes defined for the API: +{{/last}} +{{/authMethods}} +{{#authMethods}} + +### {{name}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{keyParamName}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorization URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/api_doc.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/api_doc.mustache new file mode 100644 index 000000000000..08d90eef4a2b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/api_doc.mustache @@ -0,0 +1,65 @@ +# {{classname}}{{#description}} +{{description}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +# **{{operationId}}** +> {{#returnType}}{{returnType}} {{/returnType}}{{operationId}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) + +{{summary}}{{#notes}} + +{{notes}}{{/notes}} + +### Example +```kotlin +// Import classes: +//import {{{packageName}}}.infrastructure.* +//import {{{modelPackage}}}.* + +{{! TODO: Auth method documentation examples}} +val apiInstance = {{{classname}}}() +{{#allParams}} +val {{{paramName}}} : {{{dataType}}} = {{{example}}} // {{{dataType}}} | {{{description}}} +{{/allParams}} +try { + {{#returnType}}val result : {{{returnType}}} = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}){{#returnType}} + println(result){{/returnType}} +} catch (e: ClientException) { + println("4xx response calling {{{classname}}}#{{{operationId}}}") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling {{{classname}}}#{{{operationId}}}") + e.printStackTrace() +} +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}{{#generateModelDocs}}[**{{dataType}}**]({{baseType}}.md){{/generateModelDocs}}{{^generateModelDocs}}**{{dataType}}**{{/generateModelDocs}}{{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{#defaultValue}} [default to {{defaultValue}}]{{/defaultValue}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}{{#generateModelDocs}}[**{{returnType}}**]({{returnBaseType}}.md){{/generateModelDocs}}{{^generateModelDocs}}**{{returnType}}**{{/generateModelDocs}}{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{/operation}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/class_doc.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/class_doc.mustache new file mode 100644 index 000000000000..a3405b25c845 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/class_doc.mustache @@ -0,0 +1,15 @@ +# {{classname}} + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{name}}** | {{#isEnum}}[**inline**](#{{datatypeWithEnum}}){{/isEnum}}{{^isEnum}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}}{{/isEnum}} | {{description}} | {{^required}} [optional]{{/required}}{{#isReadOnly}} [readonly]{{/isReadOnly}} +{{/vars}} +{{#vars}}{{#isEnum}} + +{{!NOTE: see java's resources "pojo_doc.mustache" once enums are fully implemented}} +## Enum: {{baseName}} +Name | Value +---- | -----{{#allowableValues}} +{{name}} | {{#values}}{{.}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}} +{{/isEnum}}{{/vars}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class.mustache new file mode 100644 index 000000000000..e22559b5cc98 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class.mustache @@ -0,0 +1,52 @@ +{{#parcelizeModels}} +import android.os.Parcelable +import kotlinx.parcelize.Parcelize + +{{/parcelizeModels}} +{{#serializableModel}} +import java.io.Serializable +{{/serializableModel}} +/** + * {{{description}}} +{{#vars}} + * @param {{name}} {{{description}}} +{{/vars}} + */ +{{#parcelizeModels}} +@Parcelize +{{/parcelizeModels}} +data class {{classname}} ( +{{#requiredVars}} +{{>data_class_req_var}}{{^-last}}, +{{/-last}}{{/requiredVars}}{{#hasRequired}}{{#hasOptional}}, +{{/hasOptional}}{{/hasRequired}}{{#optionalVars}}{{>data_class_opt_var}}{{^-last}}, +{{/-last}}{{/optionalVars}} +) {{^serializableModel}}{{#parcelizeModels}} : Parcelable{{/parcelizeModels}}{{/serializableModel}}{{^parcelizeModels}}{{#serializableModel}}: Serializable {{/serializableModel}}{{/parcelizeModels}}{{#parcelizeModels}}{{#serializableModel}} : Parcelable, Serializable {{/serializableModel}}{{/parcelizeModels}} +{{#vendorExtensions.x-has-data-class-body}} +{ +{{/vendorExtensions.x-has-data-class-body}} +{{#serializableModel}} + companion object { + private const val serialVersionUID: Long = 123 + } +{{/serializableModel}} +{{#hasEnums}} + {{#vars}} + {{#isEnum}} + /** + * {{{description}}} + * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} + */ + enum class {{nameInCamelCase}}(val value: {{dataType}}){ + {{#allowableValues}} + {{#enumVars}} + {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} + {{/enumVars}} + {{/allowableValues}} + } +{{/isEnum}} +{{/vars}} +{{/hasEnums}} +{{#vendorExtensions.x-has-data-class-body}} +} +{{/vendorExtensions.x-has-data-class-body}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class_opt_var.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class_opt_var.mustache new file mode 100644 index 000000000000..b10601187320 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class_opt_var.mustache @@ -0,0 +1,4 @@ +{{#description}} + /* {{{description}}} */ +{{/description}} + {{>modelMutable}} {{{name}}}: {{#isEnum}}{{classname}}.{{nameInCamelCase}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}? = {{#defaultvalue}}{{defaultvalue}}{{/defaultvalue}}{{^defaultvalue}}null{{/defaultvalue}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class_req_var.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class_req_var.mustache new file mode 100644 index 000000000000..c79bfec01bd0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/data_class_req_var.mustache @@ -0,0 +1,4 @@ +{{#description}} + /* {{{description}}} */ +{{/description}} + {{>modelMutable}} {{{name}}}: {{#isEnum}}{{classname}}.{{nameInCamelCase}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/enum_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/enum_class.mustache new file mode 100644 index 000000000000..791398b97894 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/enum_class.mustache @@ -0,0 +1,9 @@ +/** +* {{{description}}} +* Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} +*/ +enum class {{classname}}(val value: {{dataType}}){ +{{#allowableValues}}{{#enumVars}} + {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} +{{/enumVars}}{{/allowableValues}} +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/enum_doc.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/enum_doc.mustache new file mode 100644 index 000000000000..fcb3d7e61aa6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/enum_doc.mustache @@ -0,0 +1,7 @@ +# {{classname}} + +## Enum + +{{#allowableValues}}{{#enumVars}} + * `{{name}}` (value: `{{{value}}}`) +{{/enumVars}}{{/allowableValues}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/ApiKeyAuth.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/ApiKeyAuth.kt.mustache new file mode 100644 index 000000000000..e50c0793be45 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/ApiKeyAuth.kt.mustache @@ -0,0 +1,85 @@ +package {{packageName}}.infrastructure + +import io.ktor.application.ApplicationCall +import io.ktor.application.call +import io.ktor.auth.Authentication +import io.ktor.auth.AuthenticationFailedCause +import io.ktor.auth.AuthenticationPipeline +import io.ktor.auth.AuthenticationProvider +import io.ktor.auth.Credential +import io.ktor.auth.Principal +import io.ktor.auth.UnauthorizedResponse +import io.ktor.http.auth.HeaderValueEncoding +import io.ktor.http.auth.HttpAuthHeader +import io.ktor.request.ApplicationRequest +import io.ktor.response.respond + +enum class ApiKeyLocation(val location: String) { + QUERY("query"), + HEADER("header") +} +data class ApiKeyCredential(val value: String): Credential +data class ApiPrincipal(val apiKeyCredential: ApiKeyCredential?) : Principal + + + +/** +* Represents a Api Key authentication provider +* @param name is the name of the provider, or `null` for a default provider +*/ +class ApiKeyAuthenticationProvider(name: String?) : AuthenticationProvider(name) { + internal var authenticationFunction: suspend ApplicationCall.(ApiKeyCredential) -> Principal? = { null } + + var apiKeyName: String = ""; + + var apiKeyLocation: ApiKeyLocation = ApiKeyLocation.QUERY; + + /** + * Sets a validation function that will check given [ApiKeyCredential] instance and return [Principal], + * or null if credential does not correspond to an authenticated principal + */ + fun validate(body: suspend ApplicationCall.(ApiKeyCredential) -> Principal?) { + authenticationFunction = body + } +} + +fun Authentication.Configuration.apiKeyAuth(name: String? = null, configure: ApiKeyAuthenticationProvider.() -> Unit) { + val provider = ApiKeyAuthenticationProvider(name).apply(configure) + val apiKeyName = provider.apiKeyName + val apiKeyLocation = provider.apiKeyLocation + val authenticate = provider.authenticationFunction + + provider.pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context -> + val credentials = call.request.apiKeyAuthenticationCredentials(apiKeyName, apiKeyLocation) + val principal = credentials?.let { authenticate(call, it) } + + val cause = when { + credentials == null -> AuthenticationFailedCause.NoCredentials + principal == null -> AuthenticationFailedCause.InvalidCredentials + else -> null + } + + if (cause != null) { + context.challenge(apiKeyName, cause) { + // TODO: Verify correct response structure here. + call.respond(UnauthorizedResponse(HttpAuthHeader.Parameterized("API_KEY", mapOf("key" to apiKeyName), HeaderValueEncoding.QUOTED_ALWAYS))) + it.complete() + } + } + + if (principal != null) { + context.principal(principal) + } + } +} + +fun ApplicationRequest.apiKeyAuthenticationCredentials(apiKeyName: String, apiKeyLocation: ApiKeyLocation): ApiKeyCredential? { + val value: String? = when(apiKeyLocation) { + ApiKeyLocation.QUERY -> this.queryParameters[apiKeyName] + ApiKeyLocation.HEADER -> this.headers[apiKeyName] + } + when (value) { + null -> return null + else -> return ApiKeyCredential(value) + } +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/AppMain.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/AppMain.kt.mustache new file mode 100644 index 000000000000..bef736de059b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/AppMain.kt.mustache @@ -0,0 +1,145 @@ +package {{packageName}} + +import com.codahale.metrics.Slf4jReporter +import com.typesafe.config.ConfigFactory +import io.ktor.application.Application +import io.ktor.application.ApplicationStopping +import io.ktor.application.install +import io.ktor.application.log +import io.ktor.client.HttpClient +import io.ktor.client.engine.apache.Apache +import io.ktor.config.HoconApplicationConfig +{{#featureAutoHead}} +import io.ktor.features.AutoHeadResponse +{{/featureAutoHead}} +{{#featureCompression}} +import io.ktor.features.Compression +{{/featureCompression}} +{{#featureCORS}} +import io.ktor.features.CORS +{{/featureCORS}} +{{#featureConditionalHeaders}} +import io.ktor.features.ConditionalHeaders +{{/featureConditionalHeaders}} +import io.ktor.features.ContentNegotiation +import io.ktor.features.DefaultHeaders +{{#featureHSTS}} +import io.ktor.features.HSTS +{{/featureHSTS}} +import io.ktor.gson.GsonConverter +import io.ktor.http.ContentType +import io.ktor.locations.KtorExperimentalLocationsAPI +import io.ktor.locations.Locations +import io.ktor.metrics.Metrics +import io.ktor.routing.Routing +import java.util.concurrent.TimeUnit +import io.ktor.util.KtorExperimentalAPI +{{#hasAuthMethods}} +import io.ktor.auth.Authentication +import io.ktor.auth.oauth +import org.openapitools.server.infrastructure.ApiKeyCredential +import org.openapitools.server.infrastructure.ApiPrincipal +import org.openapitools.server.infrastructure.apiKeyAuth +{{/hasAuthMethods}} +{{#generateApis}}{{#apiInfo}}{{#apis}}import {{apiPackage}}.{{classname}} +{{/apis}}{{/apiInfo}}{{/generateApis}} + +@KtorExperimentalAPI +internal val settings = HoconApplicationConfig(ConfigFactory.defaultApplication(HTTP::class.java.classLoader)) + +object HTTP { + val client = HttpClient(Apache) +} + +@KtorExperimentalAPI +@KtorExperimentalLocationsAPI +fun Application.main() { + install(DefaultHeaders) + install(Metrics) { + val reporter = Slf4jReporter.forRegistry(registry) + .outputTo(log) + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .build() + reporter.start(10, TimeUnit.SECONDS) + } +{{#generateApis}} + install(ContentNegotiation) { + register(ContentType.Application.Json, GsonConverter()) + } + {{#featureAutoHead}} + install(AutoHeadResponse) // see http://ktor.io/features/autoheadresponse.html + {{/featureAutoHead}} + {{#featureConditionalHeaders}} + install(ConditionalHeaders) // see http://ktor.io/features/conditional-headers.html + {{/featureConditionalHeaders}} + {{#featureHSTS}} + install(HSTS, ApplicationHstsConfiguration()) // see http://ktor.io/features/hsts.html + {{/featureHSTS}} + {{#featureCORS}} + install(CORS, ApplicationCORSConfiguration()) // see http://ktor.io/features/cors.html + {{/featureCORS}} + {{#featureCompression}} + install(Compression, ApplicationCompressionConfiguration()) // see http://ktor.io/features/compression.html + {{/featureCompression}} + install(Locations) // see http://ktor.io/features/locations.html + {{#hasAuthMethods}} + install(Authentication) { + {{#authMethods}} + {{#isBasic}} + basic("{{{name}}}") { + validate { credentials -> + // TODO: "Apply your basic authentication functionality." + // Accessible in-method via call.principal() + if (credentials.name == "Swagger" && "Codegen" == credentials.password) { + UserIdPrincipal(credentials.name) + } else { + null + } + } + {{/isBasic}} + {{#isApiKey}} + // "Implement API key auth ({{{name}}}) for parameter name '{{{keyParamName}}}'." + apiKeyAuth("{{{name}}}") { + validate { apikeyCredential: ApiKeyCredential -> + when { + apikeyCredential.value == "keyboardcat" -> ApiPrincipal(apikeyCredential) + else -> null + } + } + } + {{/isApiKey}} + {{#isOAuth}} + {{#bodyAllowed}} + {{/bodyAllowed}} + {{^bodyAllowed}} + oauth("{{name}}") { + client = HttpClient(Apache) + providerLookup = { ApplicationAuthProviders["{{{name}}}"] } + urlProvider = { _ -> + // TODO: define a callback url here. + "/" + } + } + {{/bodyAllowed}} + {{/isOAuth}} + {{/authMethods}} + } + {{/hasAuthMethods}} + install(Routing) { + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{classname}}() + {{/operations}} + {{/apis}} + {{/apiInfo}} + } + +{{/generateApis}} + + environment.monitor.subscribe(ApplicationStopping) + { + HTTP.client.close() + } +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Configuration.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Configuration.kt.mustache new file mode 100644 index 000000000000..3b568d21eba9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Configuration.kt.mustache @@ -0,0 +1,114 @@ +package {{packageName}} + +// Use this file to hold package-level internal functions that return receiver object passed to the `install` method. +import io.ktor.auth.OAuthServerSettings +import io.ktor.features.Compression +import io.ktor.features.HSTS +import io.ktor.features.deflate +import io.ktor.features.gzip +import io.ktor.features.minimumSize +import io.ktor.http.HttpMethod +import io.ktor.util.KtorExperimentalAPI +import java.time.Duration +import java.util.concurrent.Executors + +import {{packageName}}.settings + +{{#featureCORS}} +/** + * Application block for [CORS] configuration. + * + * This file may be excluded in .openapi-generator-ignore, + * and application specific configuration can be applied in this function. + * + * See http://ktor.io/features/cors.html + */ +internal fun ApplicationCORSConfiguration(): CORS.Configuration.() -> Unit { + return { + // method(HttpMethod.Options) + // header(HttpHeaders.XForwardedProto) + // anyHost() + // host("my-host") + // host("my-host:80") + // host("my-host", subDomains = listOf("www")) + // host("my-host", schemes = listOf("http", "https")) + // allowCredentials = true + // maxAge = Duration.ofDays(1) + } +} +{{/featureCORS}} + +{{#featureHSTS}} +/** + * Application block for [HSTS] configuration. + * + * This file may be excluded in .openapi-generator-ignore, + * and application specific configuration can be applied in this function. + * + * See http://ktor.io/features/hsts.html + */ +internal fun ApplicationHstsConfiguration(): HSTS.Configuration.() -> Unit { + return { + maxAge = Duration.ofDays(365) + includeSubDomains = true + preload = false + + // You may also apply any custom directives supported by specific user-agent. For example: + // customDirectives.put("redirectHttpToHttps", "false") + } +} +{{/featureHSTS}} + +{{#featureCompression}} +/** + * Application block for [Compression] configuration. + * + * This file may be excluded in .openapi-generator-ignore, + * and application specific configuration can be applied in this function. + * + * See http://ktor.io/features/compression.html + */ +internal fun ApplicationCompressionConfiguration(): Compression.Configuration.() -> Unit { + return { + gzip { + priority = 1.0 + } + deflate { + priority = 10.0 + minimumSize(1024) // condition + } + } +} +{{/featureCompression}} + +// Defines authentication mechanisms used throughout the application. +@KtorExperimentalAPI +val ApplicationAuthProviders: Map = listOf( +{{#authMethods}} + {{#isOAuth}} + OAuthServerSettings.OAuth2ServerSettings( + name = "{{name}}", + authorizeUrl = "{{authorizationUrl}}", + accessTokenUrl = "{{tokenUrl}}", + requestMethod = HttpMethod.Get, + {{! TODO: flow, doesn't seem to be supported yet by ktor }} + clientId = settings.property("auth.oauth.{{name}}.clientId").getString(), + clientSecret = settings.property("auth.oauth.{{name}}.clientSecret").getString(), + defaultScopes = listOf({{#scopes}}"{{scope}}"{{^-last}}, {{/-last}}{{/scopes}}) + ){{^-last}},{{/-last}} + {{/isOAuth}} +{{/authMethods}} +// OAuthServerSettings.OAuth2ServerSettings( +// name = "facebook", +// authorizeUrl = "https://graph.facebook.com/oauth/authorize", +// accessTokenUrl = "https://graph.facebook.com/oauth/access_token", +// requestMethod = HttpMethod.Post, +// +// clientId = "settings.property("auth.oauth.facebook.clientId").getString()", +// clientSecret = "settings.property("auth.oauth.facebook.clientSecret").getString()", +// defaultScopes = listOf("public_profile") +// ) +).associateBy { it.name } + +// Provides an application-level fixed thread pool on which to execute coroutines (mainly) +internal val ApplicationExecutors = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 4) diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Dockerfile.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Dockerfile.mustache new file mode 100644 index 000000000000..b9158ac26e39 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Dockerfile.mustache @@ -0,0 +1,7 @@ +FROM openjdk:8-jre-alpine + +COPY ./build/libs/{{artifactId}}.jar /root/{{artifactId}}.jar + +WORKDIR /root + +CMD ["java", "-server", "-Xms4g", "-Xmx4g", "-XX:+UseG1GC", "-XX:MaxGCPauseMillis=100", "-XX:+UseStringDeduplication", "-jar", "{{artifactId}}.jar"] \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Paths.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Paths.kt.mustache new file mode 100644 index 000000000000..610f48203aa0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/Paths.kt.mustache @@ -0,0 +1,28 @@ +{{>licenseInfo}} +package {{packageName}} + +import io.ktor.locations.KtorExperimentalLocationsAPI +import io.ktor.locations.Location +{{#imports}}import {{import}} +{{/imports}} + +{{#apiInfo}} +object Paths { +{{#apis}} +{{#operations}} + {{#operation}} + {{^bodyAllowed}} + /** + * {{summary}} + * {{#unescapedNotes}}{{.}}{{/unescapedNotes}} + {{#allParams}}* @param {{paramName}} {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} + {{/allParams}}*/ + @KtorExperimentalLocationsAPI + @Location("{{path}}") class {{operationId}}({{#allParams}}val {{paramName}}: {{{dataType}}}{{^required}}? = null{{/required}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + + {{/bodyAllowed}} + {{/operation}} +{{/operations}} +{{/apis}} +} +{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/README.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/README.mustache new file mode 100644 index 000000000000..4c34e8f6bf2d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/README.mustache @@ -0,0 +1,101 @@ +# {{packageName}} - Kotlin Server library for {{appName}} + +{{#unescapedAppDescription}} +{{.}} +{{/unescapedAppDescription}} + +Generated by OpenAPI Generator {{generatorVersion}}{{^hideGenerationTimestamp}} ({{generatedDate}}){{/hideGenerationTimestamp}}. + +## Requires + +* Kotlin 1.3.21 +* Gradle 4.9 + +## Build + +First, create the gradle wrapper script: + +``` +gradle wrapper +``` + +Then, run: + +``` +./gradlew check assemble +``` + +This runs all tests and packages the library. + +## Running + +The server builds as a fat jar with a main entrypoint. To start the service, run `java -jar ./build/libs/{{artifactId}}.jar`. + +You may also run in docker: + +``` +docker build -t {{artifactId}} . +docker run -p 8080:8080 {{artifactId}} +``` + +## Features/Implementation Notes + +* Supports JSON inputs/outputs, File inputs, and Form inputs (see ktor documentation for more info). +* ~Supports collection formats for query parameters: csv, tsv, ssv, pipes.~ +* Some Kotlin and Java types are fully qualified to avoid conflicts with types defined in OpenAPI definitions. + +{{#generateApiDocs}} + +## Documentation for API Endpoints + +All URIs are relative to *{{{basePath}}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{{summary}}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +{{/generateApiDocs}} + +{{#generateModelDocs}} + +## Documentation for Models + +{{#modelPackage}} +{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} +{{/modelPackage}} +{{^modelPackage}} +No model defined in this package +{{/modelPackage}} +{{/generateModelDocs}} + +{{! TODO: optional documentation for authorization? }} +## Documentation for Authorization + +{{^authMethods}} +All endpoints do not require authorization. +{{/authMethods}} +{{#authMethods}} +{{#last}} +Authentication schemes defined for the API: +{{/last}} +{{/authMethods}} +{{#authMethods}} + +### {{name}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{keyParamName}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorization URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_api_body.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_api_body.mustache new file mode 100644 index 000000000000..9dcf500f49be --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_api_body.mustache @@ -0,0 +1,25 @@ +{{#hasAuthMethods}} +{{>libraries/ktor/_principal}} +if (principal == null) { + call.respond(HttpStatusCode.Unauthorized) +} else { + {{#examples}} + {{#-first}} + {{#lambda.indented}}{{>_response}}{{/lambda.indented}} + {{/-first}} + {{/examples}} + {{^examples}} + call.respond(HttpStatusCode.NotImplemented) + {{/examples}} +} +{{/hasAuthMethods}} +{{^hasAuthMethods}} +{{#examples}} +{{#-first}} +{{>libraries/ktor/_response}} +{{/-first}} +{{/examples}} +{{^examples}} +call.respond(HttpStatusCode.NotImplemented) +{{/examples}} +{{/hasAuthMethods}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_principal.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_principal.mustache new file mode 100644 index 000000000000..d49c5d537f01 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_principal.mustache @@ -0,0 +1,11 @@ +{{#authMethods}} +{{#isBasic}} +val principal = call.authentication.principal() +{{/isBasic}} +{{#isApiKey}} +val principal = call.authentication.principal() +{{/isApiKey}} +{{#isOAuth}} +val principal = call.authentication.principal() +{{/isOAuth}} +{{/authMethods}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_response.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_response.mustache new file mode 100644 index 000000000000..fb26fb4a7f1b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/_response.mustache @@ -0,0 +1,8 @@ +val exampleContentType = "{{{contentType}}}" +val exampleContentString = """{{&example}}""" + +when(exampleContentType) { + "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) + "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) + else -> call.respondText(exampleContentString) +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/api.mustache new file mode 100644 index 000000000000..881e3b108ec3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/api.mustache @@ -0,0 +1,62 @@ +{{>licenseInfo}} +package {{apiPackage}} + +import com.google.gson.Gson +import io.ktor.application.call +import io.ktor.auth.UserIdPrincipal +import io.ktor.auth.authentication +import io.ktor.auth.authenticate +import io.ktor.auth.OAuthAccessTokenResponse +import io.ktor.auth.OAuthServerSettings +import io.ktor.http.ContentType +import io.ktor.http.HttpStatusCode +import io.ktor.locations.KtorExperimentalLocationsAPI +import io.ktor.locations.delete +import io.ktor.locations.get +import io.ktor.response.respond +import io.ktor.response.respondText +import io.ktor.routing.Route +import io.ktor.routing.post +import io.ktor.routing.put +import io.ktor.routing.route + +import {{packageName}}.Paths +import {{packageName}}.infrastructure.ApiPrincipal + + +{{#imports}}import {{import}} +{{/imports}} + +{{#operations}} +@KtorExperimentalLocationsAPI +fun Route.{{classname}}() { + val gson = Gson() + val empty = mutableMapOf() +{{#operation}} + {{#bodyAllowed}} + + route("{{path}}") { + {{#hasAuthMethods}} + {{#authMethods}} + authenticate("{{{name}}}") { + {{/authMethods}} + {{/hasAuthMethods}} + {{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}} { + {{#lambda.indented_12}}{{>libraries/ktor/_api_body}}{{/lambda.indented_12}} + } + {{#hasAuthMethods}} + } + {{/hasAuthMethods}} + } + {{/bodyAllowed}} + {{^bodyAllowed}} + + {{! NOTE: Locations can be used on routes without body parameters.}} + {{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}} { _: Paths.{{operationId}} -> + {{#lambda.indented_8}}{{>libraries/ktor/_api_body}}{{/lambda.indented_8}} + } + {{/bodyAllowed}} + +{{/operation}} +} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/application.conf.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/application.conf.mustache new file mode 100644 index 000000000000..032be42fa11d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/application.conf.mustache @@ -0,0 +1,27 @@ +ktor { + deployment { + environment = development + port = 8080 + autoreload = true + watch = [ {{packageName}} ] + } + + application { + modules = [ {{packageName}}.AppMainKt.main ] + } +} + +# Typesafe config allows multiple ways to provide configuration values without hard-coding them here. +# Please see https://github.com/lightbend/config for details. +auth { + oauth { +{{#authMethods}} +{{#isOAuth}} + {{name}} { + clientId = "" + clientSecret = "" + } +{{/isOAuth}} +{{/authMethods}} + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/build.gradle.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/build.gradle.mustache new file mode 100644 index 000000000000..08c317ea6669 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/build.gradle.mustache @@ -0,0 +1,68 @@ +group '{{groupId}}' +version '{{artifactVersion}}' + +wrapper { + gradleVersion = '4.9' + distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" +} + +buildscript { + ext.kotlin_version = '1.3.21' + ext.ktor_version = '1.1.3' + ext.shadow_version = '2.0.3' + + repositories { + maven { url "https://repo1.maven.org/maven2" } + maven { + url = "https://plugins.gradle.org/m2/" + } + } + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + classpath "com.github.jengelman.gradle.plugins:shadow:$shadow_version" + } +} + +apply plugin: 'java' +apply plugin: 'kotlin' +apply plugin: 'application' + +mainClassName = "io.ktor.server.netty.DevelopmentEngine" + +// Initialization order with shadow 2.0.1 and Gradle 4.3 is weird. +// See https://github.com/johnrengelman/shadow/issues/336#issuecomment-355402508 +apply plugin: 'com.github.johnrengelman.shadow' + +sourceCompatibility = 1.8 + +compileKotlin { + kotlinOptions.jvmTarget = "1.8" +} + +compileTestKotlin { + kotlinOptions.jvmTarget = "1.8" +} + +shadowJar { + baseName = '{{artifactId}}' + classifier = null + version = null +} + +repositories { + maven { url "https://repo1.maven.org/maven2" } + maven { url "https://dl.bintray.com/kotlin/ktor" } + maven { url "https://dl.bintray.com/kotlin/kotlinx" } +} + +dependencies { + compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + compile "io.ktor:ktor-server-netty:$ktor_version" + compile "io.ktor:ktor-metrics:$ktor_version" + compile "io.ktor:ktor-locations:$ktor_version" + compile "io.ktor:ktor-gson:$ktor_version" + compile "io.ktor:ktor-client-core:$ktor_version" + compile "io.ktor:ktor-client-apache:$ktor_version" + compile "ch.qos.logback:logback-classic:1.2.1" + testCompile group: 'junit', name: 'junit', version: '4.13' +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/gradle.properties b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/gradle.properties new file mode 100644 index 000000000000..5f1ed7bbe024 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/gradle.properties @@ -0,0 +1 @@ +org.gradle.caching=true \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/licenseInfo.mustache new file mode 100644 index 000000000000..3a547de74bb7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/licenseInfo.mustache @@ -0,0 +1,11 @@ +/** +* {{{appName}}} +* {{{appDescription}}} +* +* {{#version}}The version of the OpenAPI document: {{{version}}}{{/version}} +* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/logback.xml b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/logback.xml new file mode 100644 index 000000000000..d0eaba8debd6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/libraries/ktor/logback.xml @@ -0,0 +1,15 @@ + + + + %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/licenseInfo.mustache new file mode 100644 index 000000000000..3a547de74bb7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/licenseInfo.mustache @@ -0,0 +1,11 @@ +/** +* {{{appName}}} +* {{{appDescription}}} +* +* {{#version}}The version of the OpenAPI document: {{{version}}}{{/version}} +* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/model.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/model.mustache new file mode 100644 index 000000000000..780dd84b97e0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/model.mustache @@ -0,0 +1,11 @@ +{{>licenseInfo}} +package {{modelPackage}} + +{{#imports}}import {{import}} +{{/imports}} + +{{#models}} +{{#model}} +{{#isEnum}}{{>enum_class}}{{/isEnum}}{{^isEnum}}{{>data_class}}{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/modelMutable.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/modelMutable.mustache new file mode 100644 index 000000000000..4c7f39007171 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/modelMutable.mustache @@ -0,0 +1 @@ +{{#modelMutable}}var{{/modelMutable}}{{^modelMutable}}val{{/modelMutable}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/model_doc.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/model_doc.mustache new file mode 100644 index 000000000000..e3b718421188 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/model_doc.mustache @@ -0,0 +1,3 @@ +{{#models}}{{#model}} +{{#isEnum}}{{>enum_doc}}{{/isEnum}}{{^isEnum}}{{>class_doc}}{{/isEnum}} +{{/model}}{{/models}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/settings.gradle.mustache b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/settings.gradle.mustache new file mode 100644 index 000000000000..448dc07602e2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-server-deprecated/settings.gradle.mustache @@ -0,0 +1 @@ +rootProject.name = '{{artifactId}}' \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/README.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/README.mustache index 24c4728fdd3a..910f1a9c9e21 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/README.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/README.mustache @@ -2,8 +2,8 @@ ## Requires -* Kotlin 1.1.2 -* Gradle 3.3 +* Kotlin 1.4.31 +* Gradle 6.8.2 ## Build diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/data_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/data_class.mustache index e22559b5cc98..215a291253f1 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/data_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/data_class.mustache @@ -15,7 +15,7 @@ import java.io.Serializable {{#parcelizeModels}} @Parcelize {{/parcelizeModels}} -data class {{classname}} ( +data class {{classname}}( {{#requiredVars}} {{>data_class_req_var}}{{^-last}}, {{/-last}}{{/requiredVars}}{{#hasRequired}}{{#hasOptional}}, diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/enum_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/enum_class.mustache index 791398b97894..2f24a1de76b2 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/enum_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/enum_class.mustache @@ -2,7 +2,7 @@ * {{{description}}} * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} */ -enum class {{classname}}(val value: {{dataType}}){ +enum class {{classname}}(val value: {{dataType}}) { {{#allowableValues}}{{#enumVars}} {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} {{/enumVars}}{{/allowableValues}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/ApiKeyAuth.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/ApiKeyAuth.kt.mustache index e50c0793be45..a0abbcddfd04 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/ApiKeyAuth.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/ApiKeyAuth.kt.mustache @@ -1,85 +1,105 @@ package {{packageName}}.infrastructure -import io.ktor.application.ApplicationCall -import io.ktor.application.call -import io.ktor.auth.Authentication -import io.ktor.auth.AuthenticationFailedCause -import io.ktor.auth.AuthenticationPipeline -import io.ktor.auth.AuthenticationProvider -import io.ktor.auth.Credential -import io.ktor.auth.Principal -import io.ktor.auth.UnauthorizedResponse -import io.ktor.http.auth.HeaderValueEncoding -import io.ktor.http.auth.HttpAuthHeader -import io.ktor.request.ApplicationRequest -import io.ktor.response.respond +import io.ktor.application.* +import io.ktor.auth.* +import io.ktor.http.auth.* +import io.ktor.request.* +import io.ktor.response.* enum class ApiKeyLocation(val location: String) { QUERY("query"), HEADER("header") } -data class ApiKeyCredential(val value: String): Credential -data class ApiPrincipal(val apiKeyCredential: ApiKeyCredential?) : Principal - +data class ApiKeyCredential(val value: String) : Credential +data class ApiPrincipal(val apiKeyCredential: ApiKeyCredential?) : Principal /** * Represents a Api Key authentication provider * @param name is the name of the provider, or `null` for a default provider */ -class ApiKeyAuthenticationProvider(name: String?) : AuthenticationProvider(name) { - internal var authenticationFunction: suspend ApplicationCall.(ApiKeyCredential) -> Principal? = { null } +class ApiKeyAuthenticationProvider(configuration: Configuration) : AuthenticationProvider(configuration) { - var apiKeyName: String = ""; + private val authenticationFunction = configuration.authenticationFunction - var apiKeyLocation: ApiKeyLocation = ApiKeyLocation.QUERY; + private val apiKeyName: String = configuration.apiKeyName - /** - * Sets a validation function that will check given [ApiKeyCredential] instance and return [Principal], - * or null if credential does not correspond to an authenticated principal - */ - fun validate(body: suspend ApplicationCall.(ApiKeyCredential) -> Principal?) { - authenticationFunction = body - } -} + private val apiKeyLocation: ApiKeyLocation = configuration.apiKeyLocation -fun Authentication.Configuration.apiKeyAuth(name: String? = null, configure: ApiKeyAuthenticationProvider.() -> Unit) { - val provider = ApiKeyAuthenticationProvider(name).apply(configure) - val apiKeyName = provider.apiKeyName - val apiKeyLocation = provider.apiKeyLocation - val authenticate = provider.authenticationFunction + internal fun install() { + pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context -> + val credentials = call.request.apiKeyAuthenticationCredentials(apiKeyName, apiKeyLocation) + val principal = credentials?.let { authenticationFunction(call, it) } - provider.pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context -> - val credentials = call.request.apiKeyAuthenticationCredentials(apiKeyName, apiKeyLocation) - val principal = credentials?.let { authenticate(call, it) } + val cause = when { + credentials == null -> AuthenticationFailedCause.NoCredentials + principal == null -> AuthenticationFailedCause.InvalidCredentials + else -> null + } - val cause = when { - credentials == null -> AuthenticationFailedCause.NoCredentials - principal == null -> AuthenticationFailedCause.InvalidCredentials - else -> null - } + if (cause != null) { + context.challenge(apiKeyName, cause) { + call.respond( + UnauthorizedResponse( + HttpAuthHeader.Parameterized( + "API_KEY", + mapOf("key" to apiKeyName), + HeaderValueEncoding.QUOTED_ALWAYS + ) + ) + ) + it.complete() + } + } - if (cause != null) { - context.challenge(apiKeyName, cause) { - // TODO: Verify correct response structure here. - call.respond(UnauthorizedResponse(HttpAuthHeader.Parameterized("API_KEY", mapOf("key" to apiKeyName), HeaderValueEncoding.QUOTED_ALWAYS))) - it.complete() + if (principal != null) { + context.principal(principal) } } + } + + class Configuration internal constructor(name: String?) : AuthenticationProvider.Configuration(name) { + + internal var authenticationFunction: suspend ApplicationCall.(ApiKeyCredential) -> Principal? = { + throw NotImplementedError( + "Api Key auth validate function is not specified. Use apiKeyAuth { validate { ... } } to fix." + ) + } - if (principal != null) { - context.principal(principal) + var apiKeyName: String = "" + + var apiKeyLocation: ApiKeyLocation = ApiKeyLocation.QUERY + + /** + * Sets a validation function that will check given [ApiKeyCredential] instance and return [Principal], + * or null if credential does not correspond to an authenticated principal + */ + fun validate(body: suspend ApplicationCall.(ApiKeyCredential) -> Principal?) { + authenticationFunction = body } } } -fun ApplicationRequest.apiKeyAuthenticationCredentials(apiKeyName: String, apiKeyLocation: ApiKeyLocation): ApiKeyCredential? { - val value: String? = when(apiKeyLocation) { +fun Authentication.Configuration.apiKeyAuth( + name: String? = null, + configure: ApiKeyAuthenticationProvider.Configuration.() -> Unit +) { + val configuration = ApiKeyAuthenticationProvider.Configuration(name).apply(configure) + val provider = ApiKeyAuthenticationProvider(configuration) + provider.install() + register(provider) +} + +fun ApplicationRequest.apiKeyAuthenticationCredentials( + apiKeyName: String, + apiKeyLocation: ApiKeyLocation +): ApiKeyCredential? { + val value: String? = when (apiKeyLocation) { ApiKeyLocation.QUERY -> this.queryParameters[apiKeyName] ApiKeyLocation.HEADER -> this.headers[apiKeyName] } - when (value) { - null -> return null - else -> return ApiKeyCredential(value) + return when (value) { + null -> null + else -> ApiKeyCredential(value) } } diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/AppMain.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/AppMain.kt.mustache index bef736de059b..1556c44ae58f 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/AppMain.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/AppMain.kt.mustache @@ -28,15 +28,16 @@ import io.ktor.features.HSTS {{/featureHSTS}} import io.ktor.gson.GsonConverter import io.ktor.http.ContentType +{{#featureLocations}} import io.ktor.locations.KtorExperimentalLocationsAPI import io.ktor.locations.Locations -import io.ktor.metrics.Metrics +{{/featureLocations}} import io.ktor.routing.Routing import java.util.concurrent.TimeUnit -import io.ktor.util.KtorExperimentalAPI {{#hasAuthMethods}} import io.ktor.auth.Authentication import io.ktor.auth.oauth +import io.ktor.metrics.dropwizard.DropwizardMetrics import org.openapitools.server.infrastructure.ApiKeyCredential import org.openapitools.server.infrastructure.ApiPrincipal import org.openapitools.server.infrastructure.apiKeyAuth @@ -44,23 +45,23 @@ import org.openapitools.server.infrastructure.apiKeyAuth {{#generateApis}}{{#apiInfo}}{{#apis}}import {{apiPackage}}.{{classname}} {{/apis}}{{/apiInfo}}{{/generateApis}} -@KtorExperimentalAPI internal val settings = HoconApplicationConfig(ConfigFactory.defaultApplication(HTTP::class.java.classLoader)) object HTTP { val client = HttpClient(Apache) } -@KtorExperimentalAPI +{{#featureLocations}} @KtorExperimentalLocationsAPI +{{/featureLocations}} fun Application.main() { install(DefaultHeaders) - install(Metrics) { + install(DropwizardMetrics) { val reporter = Slf4jReporter.forRegistry(registry) - .outputTo(log) - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .build() + .outputTo(log) + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .build() reporter.start(10, TimeUnit.SECONDS) } {{#generateApis}} @@ -82,7 +83,9 @@ fun Application.main() { {{#featureCompression}} install(Compression, ApplicationCompressionConfiguration()) // see http://ktor.io/features/compression.html {{/featureCompression}} + {{#featureLocations}} install(Locations) // see http://ktor.io/features/locations.html + {{/featureLocations}} {{#hasAuthMethods}} install(Authentication) { {{#authMethods}} @@ -117,8 +120,8 @@ fun Application.main() { client = HttpClient(Apache) providerLookup = { ApplicationAuthProviders["{{{name}}}"] } urlProvider = { _ -> - // TODO: define a callback url here. - "/" + // TODO: define a callback url here. + "/" } } {{/bodyAllowed}} @@ -138,8 +141,7 @@ fun Application.main() { {{/generateApis}} - environment.monitor.subscribe(ApplicationStopping) - { + environment.monitor.subscribe(ApplicationStopping) { HTTP.client.close() } } diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Configuration.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Configuration.kt.mustache index 3b568d21eba9..a8956ec59052 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Configuration.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Configuration.kt.mustache @@ -8,11 +8,7 @@ import io.ktor.features.deflate import io.ktor.features.gzip import io.ktor.features.minimumSize import io.ktor.http.HttpMethod -import io.ktor.util.KtorExperimentalAPI -import java.time.Duration -import java.util.concurrent.Executors - -import {{packageName}}.settings +import java.util.concurrent.TimeUnit {{#featureCORS}} /** @@ -49,7 +45,7 @@ internal fun ApplicationCORSConfiguration(): CORS.Configuration.() -> Unit { */ internal fun ApplicationHstsConfiguration(): HSTS.Configuration.() -> Unit { return { - maxAge = Duration.ofDays(365) + maxAgeInSeconds = TimeUnit.DAYS.toSeconds(365) includeSubDomains = true preload = false @@ -82,7 +78,6 @@ internal fun ApplicationCompressionConfiguration(): Compression.Configuration.() {{/featureCompression}} // Defines authentication mechanisms used throughout the application. -@KtorExperimentalAPI val ApplicationAuthProviders: Map = listOf( {{#authMethods}} {{#isOAuth}} @@ -109,6 +104,3 @@ val ApplicationAuthProviders: Map = listOflibraries/ktor/_principal}} -if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) -} else { - {{#examples}} - {{#-first}} - {{#lambda.indented}}{{>_response}}{{/lambda.indented}} - {{/-first}} - {{/examples}} - {{^examples}} - call.respond(HttpStatusCode.NotImplemented) - {{/examples}} -} +{{#examples}} +{{#-first}} +{{#lambda.indented}}{{>_response}}{{/lambda.indented}} +{{/-first}} +{{/examples}} +{{^examples}} +call.respond(HttpStatusCode.NotImplemented) +{{/examples}} {{/hasAuthMethods}} {{^hasAuthMethods}} {{#examples}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/_principal.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/_principal.mustache index d49c5d537f01..09ae65906ea2 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/_principal.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/_principal.mustache @@ -1,11 +1,11 @@ {{#authMethods}} {{#isBasic}} -val principal = call.authentication.principal() +val principal = call.authentication.principal()!! {{/isBasic}} {{#isApiKey}} -val principal = call.authentication.principal() +val principal = call.authentication.principal()!! {{/isApiKey}} {{#isOAuth}} -val principal = call.authentication.principal() +val principal = call.authentication.principal()!! {{/isOAuth}} {{/authMethods}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/_response.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/_response.mustache index fb26fb4a7f1b..931dad98f5e1 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/_response.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/_response.mustache @@ -1,7 +1,7 @@ val exampleContentType = "{{{contentType}}}" val exampleContentString = """{{&example}}""" -when(exampleContentType) { +when (exampleContentType) { "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/api.mustache index 881e3b108ec3..a3d8c124e817 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/api.mustache @@ -10,17 +10,29 @@ import io.ktor.auth.OAuthAccessTokenResponse import io.ktor.auth.OAuthServerSettings import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode -import io.ktor.locations.KtorExperimentalLocationsAPI -import io.ktor.locations.delete -import io.ktor.locations.get import io.ktor.response.respond import io.ktor.response.respondText import io.ktor.routing.Route +{{#featureLocations}} +import {{packageName}}.Paths +import io.ktor.locations.KtorExperimentalLocationsAPI +import io.ktor.locations.delete +import io.ktor.locations.get +import io.ktor.locations.post +import io.ktor.locations.put +import io.ktor.locations.options +import io.ktor.locations.head +{{/featureLocations}} +{{^featureLocations}} +import io.ktor.routing.delete +import io.ktor.routing.get import io.ktor.routing.post import io.ktor.routing.put +import io.ktor.routing.options +import io.ktor.routing.head import io.ktor.routing.route +{{/featureLocations}} -import {{packageName}}.Paths import {{packageName}}.infrastructure.ApiPrincipal @@ -28,34 +40,33 @@ import {{packageName}}.infrastructure.ApiPrincipal {{/imports}} {{#operations}} + {{#featureLocations}} @KtorExperimentalLocationsAPI + {{/featureLocations}} fun Route.{{classname}}() { val gson = Gson() val empty = mutableMapOf() {{#operation}} - {{#bodyAllowed}} - + {{#hasAuthMethods}} + {{#authMethods}} + authenticate("{{{name}}}") { + {{/authMethods}} + {{/hasAuthMethods}} + {{^featureLocations}} route("{{path}}") { - {{#hasAuthMethods}} - {{#authMethods}} - authenticate("{{{name}}}") { - {{/authMethods}} - {{/hasAuthMethods}} {{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}} { {{#lambda.indented_12}}{{>libraries/ktor/_api_body}}{{/lambda.indented_12}} } - {{#hasAuthMethods}} - } - {{/hasAuthMethods}} } - {{/bodyAllowed}} - {{^bodyAllowed}} - - {{! NOTE: Locations can be used on routes without body parameters.}} - {{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}} { _: Paths.{{operationId}} -> + {{/featureLocations}} + {{#featureLocations}} + {{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}} { {{#lambda.indented_8}}{{>libraries/ktor/_api_body}}{{/lambda.indented_8}} } - {{/bodyAllowed}} + {{/featureLocations}} + {{#hasAuthMethods}} + } + {{/hasAuthMethods}} {{/operation}} } diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/build.gradle.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/build.gradle.mustache index 08c317ea6669..173686fdf88d 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/build.gradle.mustache @@ -2,13 +2,13 @@ group '{{groupId}}' version '{{artifactVersion}}' wrapper { - gradleVersion = '4.9' + gradleVersion = '6.8.2' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.3.21' - ext.ktor_version = '1.1.3' + ext.kotlin_version = '1.4.31' + ext.ktor_version = '1.5.2' ext.shadow_version = '2.0.3' repositories { @@ -29,7 +29,7 @@ apply plugin: 'application' mainClassName = "io.ktor.server.netty.DevelopmentEngine" -// Initialization order with shadow 2.0.1 and Gradle 4.3 is weird. +// Initialization order with shadow 2.0.1 and Gradle 6.8.2 is weird. // See https://github.com/johnrengelman/shadow/issues/336#issuecomment-355402508 apply plugin: 'com.github.johnrengelman.shadow' @@ -59,7 +59,10 @@ dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" compile "io.ktor:ktor-server-netty:$ktor_version" compile "io.ktor:ktor-metrics:$ktor_version" + compile "io.ktor:ktor-auth:$ktor_version" +{{#featureLocations}} compile "io.ktor:ktor-locations:$ktor_version" +{{/featureLocations}} compile "io.ktor:ktor-gson:$ktor_version" compile "io.ktor:ktor-client-core:$ktor_version" compile "io.ktor:ktor-client-apache:$ktor_version" diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/licenseInfo.mustache index 3a547de74bb7..d890606a94ff 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/licenseInfo.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/licenseInfo.mustache @@ -1,11 +1,11 @@ /** -* {{{appName}}} -* {{{appDescription}}} -* -* {{#version}}The version of the OpenAPI document: {{{version}}}{{/version}} -* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} -* -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -* https://openapi-generator.tech -* Do not edit the class manually. + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}The version of the OpenAPI document: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. */ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/enumClass.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/enumClass.mustache index 2f24a1de76b2..bd0794c7f12f 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/enumClass.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/enumClass.mustache @@ -4,6 +4,6 @@ */ enum class {{classname}}(val value: {{dataType}}) { {{#allowableValues}}{{#enumVars}} - {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} + @JsonProperty({{{value}}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} {{/enumVars}}{{/allowableValues}} } diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/Factory.php.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/Factory.php.mustache new file mode 100644 index 000000000000..c517b6936044 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/Factory.php.mustache @@ -0,0 +1,53 @@ +get(EmitterInterface::class), + $container->get(ServerRequestInterface::class), + static fn(\Throwable $error): ResponseInterface => $errorMiddleware->handleError($error) + ); + $application = new Application( + $container->get(MiddlewareFactory::class), + $pipeline, + $container->get(RouteCollector::class), + $runner + ); + $application->pipe($errorMiddleware); + $application->pipe(RouteMiddleware::class); + $application->pipe(MethodNotAllowedMiddleware::class); + $application->pipe(DispatchMiddleware::class); + $application->pipe(NotFoundHandler::class); + + return $application; + } + + protected static function getErrorMiddleware(ContainerInterface $container): Middleware\InternalServerError + { + return $container->get(Middleware\InternalServerError::class); + } +} diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/InternalServerError.php.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/InternalServerError.php.mustache new file mode 100644 index 000000000000..54f4d66a56dc --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/InternalServerError.php.mustache @@ -0,0 +1,45 @@ +handle($request); + ErrorHandler::stop(true); + } + catch (\Throwable $error) { + $result = $this->handleError($error); + } + return $result; + } + + public function handleError(\Throwable $error): ResponseInterface + { + \error_log((string)$error); + return $this->generateEmptyResponse()->withStatus(500, 'Internal server error'); + } + + protected function generateEmptyResponse(): ResponseInterface + { + return ($this->responseGenerator)(); + } +} diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/README.md.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/README.md.mustache new file mode 100644 index 000000000000..fd66369b261a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/README.md.mustache @@ -0,0 +1,34 @@ +# OpenAPI generated server + +Generated by the [OpenAPI Generator](https://openapi-generator.tech) project. + +## Overview +This server stub aims to provide light, yet comprehensive structure for your API project using: + +- PHP: >=8.0 +- [Laminas Mezzio](https://docs.mezzio.dev/mezzio/): >=3.3 +- [Path Handler](https://github.com/Articus/PathHandler): >=0.7 + +## How to use +All you have to do to start development is: + +- install dependencies via [Composer](https://getcomposer.org/) (small note: [ext-yaml](https://pecl.php.net/package/yaml) is used only for configuration parsing, so if you want to drop this dependency, simply adjust `./application/container.php`) +- create cache folder: `mkdir -p ./data/cache` (you will need it later for configuration and metadata caches - check comments in `./application/config.yml`) +- start PHP development server: `php -S 0.0.0.0:8080 -t ./public` (or any other SAPI you prefer, just make sure that you configure webroot to `./public` and rewrites to `./public/index.php`) + +After that you should be able to call all methods from your API spec. Most of the negative scenarios should be handled: + +- `404 Not found` for unknown routes +- `406 Not acceptable` for invalid `Accept` header +- `415 Unsupported media type` for invalid `Content-Type` header +- `400 Malformed JSON` for unparsable JSON body +- `422 Unprocessable entity` for parsable JSON body that fails validation + +But for obvious reason you will not get any `200 OK`, only `501 Not implemented`. So your next steps are: + +- check all TODOs left in the stub code where generator was not smart enough and could not guarantee correct implementation +- implement your API security mechanism (either special attribute or separate middleware) - generator does not do anything about it yet +- implement your handlers - the most tricky part :) + +## Enjoy! +Hopefully this stub will reduce the amount of boilerplate code you have to write manually. If you have any suggestions or questions about `php-mezzio-ph` generator, feel free to create issue either in [Path Handler repository](https://github.com/Articus/PathHandler/issues) or in [OpenAPI Generator repository](https://openapi-generator.tech/issues). diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/api.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/api.mustache new file mode 100644 index 000000000000..fdba51f5e00c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/api.mustache @@ -0,0 +1,73 @@ + {{internal.ze-ph.queryDataType}}::class, + "objectAttr" => "queryData", + "source" => PHAttribute\Transfer::SOURCE_GET + ])] +{{/internal.ze-ph.hasQueryData}} +{{/vendorExtensions}} +{{#bodyParam}} +{{#consumes}} + // TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Consumer("{{{mediaType}}}", PHConsumer\Json::class)] +{{/consumes}} +{{^isPrimitiveType}} + #[PHA\Attribute(PHAttribute\Transfer::class, ["type" => {{dataType}}::class, "objectAttr" => "bodyData"])] +{{/isPrimitiveType}} +{{/bodyParam}} +{{#produces}} + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("{{{mediaType}}}", PHProducer\Transfer::class)] +{{/produces}} + public function {{operationId}}(ServerRequestInterface $request){{#returnType}}: {{returnType}}{{/returnType}} + { + //TODO implement method +{{#vendorExtensions}} +{{#internal.ze-ph.hasQueryData}} + /** @var {{internal.ze-ph.queryDataType}} $queryData */ + $queryData = $request->getAttribute("queryData"); +{{/internal.ze-ph.hasQueryData}} +{{/vendorExtensions}} +{{#bodyParam}} +{{^isPrimitiveType}} + /** @var {{dataType}} $bodyData */ + $bodyData = $request->getAttribute("bodyData"); +{{/isPrimitiveType}} +{{/bodyParam}} + throw new PHException\HttpCode(501, "Not implemented"); + } +{{/operation}} +} +{{/operations}} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/application/config/app.yml b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/app.yml.mustache similarity index 100% rename from samples/openapi3/server/petstore/php-mezzio-ph/application/config/app.yml rename to modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/app.yml.mustache diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/composer.json.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/composer.json.mustache new file mode 100644 index 000000000000..787d5fb97f28 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/composer.json.mustache @@ -0,0 +1,26 @@ +{ + "name": "{{#lambda.lowercase}}{{gitUserId}}/{{gitRepoId}}{{/lambda.lowercase}}", + "description": "{{description}}", + "license": "unlicense", + "version": "{{artifactVersion}}", + "type": "project", + "require": { + "php": "^8.0", + "ext-yaml": "^2.2", + "mezzio/mezzio": "^3.3", + "laminas/laminas-diactoros": "^2.5", + "articus/path-handler": "^0.7", + "articus/data-transfer": "^0.5", + "articus/openapi-generator-common": "^0.2", + "psr/simple-cache": "^1.0", + "laminas/laminas-config": "^3.4", + "laminas/laminas-stdlib": "^3.3", + "laminas/laminas-validator": "^2.14", + "nikic/fast-route": "^1.3" + }, + "autoload": { + "psr-4": { + "": "src/" + } + } +} \ No newline at end of file diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/application/config.yml b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/config.yml similarity index 68% rename from samples/openapi3/server/petstore/php-mezzio-ph/application/config.yml rename to modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/config.yml index 1f106812353f..58056552c5bc 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/application/config.yml +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/config.yml @@ -9,12 +9,13 @@ # router: # cache: # directory: ./data/cache/PathHandler -# #Enable handler metadata cache -# metadata: -# cache: -# directory: ./data/cache/PathHandler + +#Enable handler metadata cache +#Articus\PathHandler\MetadataProvider\PhpAttribute: +# cache: +# directory: ./data/cache/PathHandler #Enable data transfer metadata cache for DTOs -#Articus\DataTransfer\MetadataProvider\Annotation: +#Articus\DataTransfer\MetadataProvider\PhpAttribute: # cache: # directory: ./data/cache/DataTransfer diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/application/container.php b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/container.php similarity index 91% rename from samples/openapi3/server/petstore/php-mezzio-ph/application/container.php rename to modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/container.php index b9638c5584b4..9c54fafcfec7 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/application/container.php +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/container.php @@ -6,9 +6,6 @@ //Use Composer autoload that includes code both from ../src and ../vendor require __DIR__ . '/../vendor/autoload.php'; -//Register Doctrine annotation autoload -\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader('class_exists'); - //Path to file for caching full configuration const CONFIG_CACHE_PATH = __DIR__ . '/../data/cache/config.php'; diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/data_transfer.yml.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/data_transfer.yml.mustache new file mode 100644 index 000000000000..7bdd139bb9ff --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/data_transfer.yml.mustache @@ -0,0 +1,34 @@ +dependencies: + factories: + Articus\DataTransfer\Service: Articus\DataTransfer\Factory + Articus\DataTransfer\MetadataProvider\PhpAttribute: Articus\DataTransfer\MetadataProvider\Factory\PhpAttribute + Articus\DataTransfer\Strategy\PluginManager: Articus\DataTransfer\Strategy\Factory\PluginManager + Articus\DataTransfer\Validator\PluginManager: Articus\DataTransfer\Validator\Factory\PluginManager + Laminas\Validator\ValidatorPluginManager: Laminas\Validator\ValidatorPluginManagerFactory + aliases: + Articus\DataTransfer\ClassMetadataProviderInterface: Articus\DataTransfer\MetadataProvider\PhpAttribute + Articus\DataTransfer\FieldMetadataProviderInterface: Articus\DataTransfer\MetadataProvider\PhpAttribute + +Articus\DataTransfer\Strategy\PluginManager: + invokables: + QueryStringScalar: OpenAPIGenerator\Common\Strategy\QueryStringScalar + QueryStringScalarArray: OpenAPIGenerator\Common\Strategy\QueryStringScalarArray + factories: + Date: OpenAPIGenerator\Common\Strategy\Factory\MutableDate + DateTime: OpenAPIGenerator\Common\Strategy\Factory\MutableDateTime + ObjectList: OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectList + ObjectMap: OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectMap + ScalarList: OpenAPIGenerator\Common\Strategy\Factory\ScalarList + ScalarMap: OpenAPIGenerator\Common\Strategy\Factory\ScalarMap + +Articus\DataTransfer\Validator\PluginManager: + invokables: + Scalar: OpenAPIGenerator\Common\Validator\Scalar + QueryStringScalar: OpenAPIGenerator\Common\Validator\QueryStringScalar + QueryStringScalarArray: OpenAPIGenerator\Common\Validator\QueryStringScalarArray + abstract_factories: + - Articus\DataTransfer\Validator\Factory\Laminas + +validators: + invokables: + Count: Laminas\Validator\IsCountable diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/.gitignore b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/gitignore similarity index 100% rename from samples/openapi3/server/petstore/php-mezzio-ph/.gitignore rename to modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/gitignore diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/public/index.php b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/index.php similarity index 100% rename from samples/openapi3/server/petstore/php-mezzio-ph/public/index.php rename to modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/index.php diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/list_item_type.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/list_item_type.mustache new file mode 100644 index 000000000000..254676614331 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/list_item_type.mustache @@ -0,0 +1,8 @@ +{{#items +}}{{^isContainer +}}{{#isPrimitiveType}}"{{dataType}}"{{/isPrimitiveType +}}{{^isPrimitiveType}}{{dataType}}::class{{/isPrimitiveType +}}{{/isContainer +}}{{#isContainer +}}{{dataType}}::class{{/isContainer +}}{{/items}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/map_item_type.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/map_item_type.mustache new file mode 100644 index 000000000000..a58e19beca54 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/map_item_type.mustache @@ -0,0 +1,8 @@ +{{#additionalProperties +}}{{^isContainer +}}{{#isPrimitiveType}}"{{dataType}}"{{/isPrimitiveType +}}{{^isPrimitiveType}}{{dataType}}::class{{/isPrimitiveType +}}{{/isContainer +}}{{#isContainer +}}{{dataType}}::class{{/isContainer +}}{{/additionalProperties}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model.mustache new file mode 100644 index 000000000000..4d73c1859451 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model.mustache @@ -0,0 +1,13 @@ +model_container}}{{/internal.ze-ph.fromContainer +}}{{^internal.ze-ph.fromContainer}}{{>model_object}}{{/internal.ze-ph.fromContainer +}}{{/vendorExtensions +}}{{^vendorExtensions}}{{>model_object}}{{/vendorExtensions +}}{{/model}}{{/models}} diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_container.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_container.mustache new file mode 100644 index 000000000000..543194c798b5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_container.mustache @@ -0,0 +1,57 @@ +{{#vars +}}{{#isArray +}}#[DTA\Strategy("{{#isPrimitiveType}}ScalarList{{/isPrimitiveType}}{{^isPrimitiveType}}ObjectList{{/isPrimitiveType}}", ["type" => {{>list_item_type}}])] +{{#minItems}}{{^maxItems +}}#[DTA\Validator("Count", ["min" => {{minItems}}], blocker: true)] +{{/maxItems}}{{/minItems +}}{{^minItems}}{{#maxItems +}}#[DTA\Validator("Count", ["max" => {{maxItems}}], blocker: true)] +{{/maxItems}}{{/minItems +}}{{#minItems}}{{#maxItems +}}#[DTA\Validator("Count", ["min" => {{minItems}}, "max" => {{maxItems}}], blocker: true)] +{{/maxItems}}{{/minItems +}}#[DTA\Validator("Collection", ["validators" => [ +{{#isPrimitiveType +}} ["name" => "Scalar", "options" => ["type" => {{>list_item_type}}]] +{{/isPrimitiveType +}}{{#isDate +}} ["name" => "Date"] +{{/isDate +}}{{#isDateTime +}} ["name" => "Date", "options" => ["format" => \DateTime::RFC3339]] +{{/isDateTime +}}{{^isPrimitiveType}}{{^isDate}}{{^isDateTime +}} ["name" => "TypeCompliant", "options" => ["type" => {{>list_item_type}}]] +{{/isDateTime}}{{/isDate}}{{/isPrimitiveType +}}]])] +{{/isArray +}}{{#isMap +}}#[DTA\Strategy("{{#isPrimitiveType}}ScalarMap{{/isPrimitiveType}}{{^isPrimitiveType}}ObjectMap{{/isPrimitiveType}}", ["type" => {{>map_item_type}}])] +{{#minProperties}}{{^maxProperties +}}#[DTA\Validator("Count", ["min" => {{minProperties}}], blocker: true)] +{{/maxProperties}}{{/minProperties +}}{{^minProperties}}{{#maxProperties +}}#[DTA\Validator("Count", ["max" => {{maxProperties}}], blocker: true)] +{{/maxProperties}}{{/minProperties +}}{{#minProperties}}{{#maxProperties +}}#[DTA\Validator("Count", ["min" => {{minProperties}}, "max" => {{maxProperties}}], blocker: true)] +{{/maxProperties}}{{/minProperties +}}#[DTA\Validator("Collection", ["validators" => [ +{{#isPrimitiveType +}} ["name" => "Scalar", "options" => ["type" => {{>map_item_type}}]] +{{/isPrimitiveType +}}{{#isDate +}} ["name" => "Date"] +{{/isDate +}}{{#isDateTime +}} ["name" => "Date", "options" => ["format" => \DateTime::RFC3339]] +{{/isDateTime +}}{{^isPrimitiveType}}{{^isDate}}{{^isDateTime +}} ["name" => "TypeCompliant", "options" => ["type" => {{>map_item_type}}]] +{{/isDateTime}}{{/isDate}}{{/isPrimitiveType +}}]])] +{{/isMap +}}{{/vars +}}class {{classname}} extends \ArrayObject +{ +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_normal_var.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_normal_var.mustache new file mode 100644 index 000000000000..6e215f7fc632 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_normal_var.mustache @@ -0,0 +1,45 @@ +{{#isContainer +}} #[DTA\Strategy("Object", ["type" => {{internal.ze-ph.containerDataType}}::class])] + #[DTA\Validator("TypeCompliant", ["type" => {{internal.ze-ph.containerDataType}}::class])] +{{/isContainer +}}{{^isContainer +}}{{#isPrimitiveType +}} #[DTA\Validator("Scalar", ["type" => "{{dataType}}"])] +{{/isPrimitiveType +}}{{#isDate +}} #[DTA\Strategy("Date")] + #[DTA\Validator("Date")] +{{/isDate +}}{{#isDateTime +}} #[DTA\Strategy("DateTime")] + #[DTA\Validator("Date", ["format" => \DateTime::RFC3339])] +{{/isDateTime +}}{{^isPrimitiveType +}}{{^isDate +}}{{^isDateTime +}} #[DTA\Strategy("Object", ["type" => {{dataType}}::class])] + #[DTA\Validator("TypeCompliant", ["type" => {{dataType}}::class])] +{{/isDateTime +}}{{/isDate +}}{{/isPrimitiveType +}}{{/isContainer +}}{{#hasValidation +}}{{#minLength}}{{#maxLength +}} #[DTA\Validator("StringLength", ["min" => {{minLength}}, "max" => {{maxLength}}])] +{{/maxLength}}{{/minLength +}}{{^minLength}}{{#maxLength +}} #[DTA\Validator("StringLength", ["max" => {{maxLength}}])] +{{/maxLength}}{{/minLength +}}{{#minLength}}{{^maxLength +}} #[DTA\Validator("StringLength", ["min" => {{minLength}}])] +{{/maxLength}}{{/minLength +}}{{#minimum +}} #[DTA\Validator("GreaterThan", ["min" => {{minimum}}{{^exclusiveMinimum}}, "inclusive" => true{{/exclusiveMinimum}}])] +{{/minimum +}}{{#maximum +}} #[DTA\Validator("LessThan", ["max" => {{maximum}}{{^exclusiveMaximum}}, "inclusive" => true{{/exclusiveMaximum}}])] +{{/maximum +}}{{#pattern +}} #[DTA\Validator("Regex", ["pattern" => "{{{pattern}}}"])] +{{/pattern +}}{{/hasValidation}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_object.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_object.mustache new file mode 100644 index 000000000000..253d551e3c73 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_object.mustache @@ -0,0 +1,23 @@ +{{#description +}}/** + * {{description}} + */ +{{/description +}}class {{classname}} +{ +{{#vars +}}{{#description +}} /** + * {{description}} + */ +{{/description +}} #[DTA\Data(field: "{{baseName}}"{{^required}}, nullable: true{{/required}})] +{{#vendorExtensions +}}{{#internal.ze-ph.fromQuery}}{{>model_query_var}}{{/internal.ze-ph.fromQuery +}}{{^internal.ze-ph.fromQuery}}{{>model_normal_var}}{{/internal.ze-ph.fromQuery +}}{{/vendorExtensions +}}{{^vendorExtensions}}{{>model_normal_var}}{{/vendorExtensions +}} public {{dataType}}|null ${{name}} = null; + +{{/vars +}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_query_var.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_query_var.mustache new file mode 100644 index 000000000000..f2e6525b9b93 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_query_var.mustache @@ -0,0 +1,51 @@ +{{#isArray +}}{{#isPrimitiveType +}} #[DTA\Strategy("QueryStringScalarArray", ["type" => {{>list_item_type}}, "format" => "{{internal.ze-ph.collectionFormat}}"])] + #[DTA\Validator("QueryStringScalarArray", ["type" => {{>list_item_type}}, "format" => "{{internal.ze-ph.collectionFormat}}"{{#minItems}}, "min_items" => {{minItems}}{{/minItems}}{{#maxItems}}, "max_items" => {{maxItems}}{{/maxItems}}])] +{{/isPrimitiveType +}}{{^isPrimitiveType +}} // TODO add validator(s) and strategy for list of {{>list_item_type}} and collection format {{internal.ze-ph.collectionFormat}} inside query string +{{/isPrimitiveType +}}{{/isArray +}}{{#isMap +}} // TODO add validator(s) and strategy for map of {{>map_item_type}} and collection format {{internal.ze-ph.collectionFormat}} inside query string +{{/isMap +}}{{^isContainer +}}{{#isPrimitiveType +}} #[DTA\Strategy("QueryStringScalar", ["type" => "{{dataType}}"])] + #[DTA\Validator("QueryStringScalar", ["type" => "{{dataType}}"])] +{{/isPrimitiveType +}}{{#isDate +}} #[DTA\Strategy("Date")] + #[DTA\Validator("Date")] +{{/isDate +}}{{#isDateTime +}} #[DTA\Strategy("DateTime")] + #[DTA\Validator("Date", ["format" => \DateTime::RFC3339])] +{{/isDateTime +}}{{^isPrimitiveType +}}{{^isDate}}{{^isDateTime +}} // TODO add validator(s) and strategy for {{dataType}} inside query string +{{/isDateTime}}{{/isDate +}}{{/isPrimitiveType +}}{{/isContainer +}}{{#hasValidation +}}{{#minLength}}{{#maxLength +}} #[DTA\Validator("StringLength", ["min" => {{minLength}}, "max" => {{maxLength}}])] +{{/maxLength}}{{/minLength +}}{{^minLength}}{{#maxLength +}} #[DTA\Validator("StringLength", ["max" => {{maxLength}}])] +{{/maxLength}}{{/minLength +}}{{#minLength}}{{^maxLength +}} #[DTA\Validator("StringLength", ["min" => {{minLength}}])] +{{/maxLength}}{{/minLength +}}{{#minimum +}} #[DTA\Validator("GreaterThan", ["min" => {{minimum}}{{^exclusiveMinimum}}, "inclusive" => true{{/exclusiveMinimum}}])] +{{/minimum +}}{{#maximum +}} #[DTA\Validator("LessThan", ["max" => {{maximum}}{{^exclusiveMaximum}}, "inclusive" => true{{/exclusiveMaximum}}])] +{{/maximum +}}{{#pattern +}} #[DTA\Validator("Regex", ["pattern" => "{{{pattern}}}"])] +{{/pattern +}}{{/hasValidation}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/path_handler.yml.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/path_handler.yml.mustache new file mode 100644 index 000000000000..a9739a17216c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/path_handler.yml.mustache @@ -0,0 +1,44 @@ +dependencies: + factories: + Mezzio\Router\RouterInterface: Articus\PathHandler\RouteInjectionFactory + Articus\PathHandler\MetadataProviderInterface: Articus\PathHandler\MetadataProvider\Factory\PhpAttribute + Articus\PathHandler\Handler\PluginManager: Articus\PathHandler\Handler\Factory\PluginManager + Articus\PathHandler\Consumer\PluginManager: Articus\PathHandler\Consumer\Factory\PluginManager + Articus\PathHandler\Attribute\PluginManager: Articus\PathHandler\Attribute\Factory\PluginManager + Articus\PathHandler\Producer\PluginManager: Articus\PathHandler\Producer\Factory\PluginManager + +Articus\PathHandler\RouteInjectionFactory: + paths: + '{{basePathWithoutHost}}': +{{#apiInfo}} +{{#apis}} +{{#operations}} + - {{package}}\{{classname}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + +Articus\PathHandler\Handler\PluginManager: + abstract_factories: + - Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory + +#Articus\PathHandler\Consumer\PluginManager: +# factories: +# invokables: + +#Articus\PathHandler\Attribute\PluginManager: +# factories: +# invokables: + +#Articus\PathHandler\Producer\PluginManager: +# factories: +# invokables: + +Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory: +{{#apiInfo}} +{{#apis}} +{{#operations}} + {{package}}\{{classname}}: [] +{{/operations}} +{{/apis}} +{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/Factory.php.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/Factory.php.mustache index 68787c5fd6c4..bee7ad98a781 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/Factory.php.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/Factory.php.mustache @@ -23,20 +23,13 @@ class Factory implements FactoryInterface { public function __invoke(ContainerInterface $container, $requestedName, array $options = null): Application { - $errorMiddleware = $container->get(Middleware\InternalServerError::class); - if (!($errorMiddleware instanceof Middleware\InternalServerError)) { - throw new \LogicException(\sprintf( - 'Invalid error middleware: expecting %s, not %s.', - Middleware\InternalServerError::class, - \is_object($errorMiddleware) ? \get_class($errorMiddleware) : \gettype($errorMiddleware) - )); - } + $errorMiddleware = self::getErrorMiddleware($container); $pipeline = new MiddlewarePipe(); $runner = new RequestHandlerRunner( $pipeline, $container->get(EmitterInterface::class), $container->get(ServerRequestInterface::class), - function(\Throwable $error) use ($errorMiddleware) : ResponseInterface + static function(\Throwable $error) use ($errorMiddleware) : ResponseInterface { return $errorMiddleware->handleError($error); } @@ -55,4 +48,9 @@ class Factory implements FactoryInterface return $application; } + + protected static function getErrorMiddleware(ContainerInterface $container): Middleware\InternalServerError + { + return $container->get(Middleware\InternalServerError::class); + } } diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/README.md.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/README.md.mustache index 584fd1568795..a80470059016 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/README.md.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/README.md.mustache @@ -5,9 +5,9 @@ Generated by the [OpenAPI Generator](https://openapi-generator.tech) project. ## Overview This server stub aims to provide light, yet comprehensive structure for your API project using: -- PHP: >=7.2 +- PHP: >=7.3 - [Laminas Mezzio](https://docs.mezzio.dev/mezzio/): >=3.2 -- [Path Handler](https://github.com/Articus/PathHandler): >=0.6 +- [Path Handler](https://github.com/Articus/PathHandler): >=0.7 ## How to use All you have to do to start development is: diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/api.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/api.mustache index d44e206de6f6..ec0d1df137b2 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/api.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/api.mustache @@ -43,13 +43,7 @@ class {{classname}} * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="{{{mediaType}}}") {{/consumes}} {{^isPrimitiveType}} -{{#isContainer}} - * TODO check if attribute is valid and can handle your container type - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":"{{{dataType}}}","objectAttr":"bodyData"}) -{{/isContainer}} -{{^isContainer}} - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":{{{dataType}}}::class,"objectAttr":"bodyData"}) -{{/isContainer}} + * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":{{dataType}}::class,"objectAttr":"bodyData"}) {{/isPrimitiveType}} {{/bodyParam}} {{#produces}} @@ -61,13 +55,10 @@ class {{classname}} * @throws PHException\HttpCode 501 if the method is not implemented {{#returnType}} * -{{#returnContainer}} - * TODO check if generated return container type is valid -{{/returnContainer}} - * @return {{{returnType}}} + * @return {{returnType}} {{/returnType}} */ - public function {{operationId}}(ServerRequestInterface $request){{#returnType}}: {{#returnContainer}}array{{/returnContainer}}{{^returnContainer}}{{returnType}}{{/returnContainer}}{{/returnType}} + public function {{operationId}}(ServerRequestInterface $request){{#returnType}}: {{returnType}}{{/returnType}} { //TODO implement method {{#vendorExtensions}} @@ -78,7 +69,7 @@ class {{classname}} {{/vendorExtensions}} {{#bodyParam}} {{^isPrimitiveType}} - /** @var {{{dataType}}} $bodyData */ + /** @var {{dataType}} $bodyData */ $bodyData = $request->getAttribute("bodyData"); {{/isPrimitiveType}} {{/bodyParam}} diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/composer.json.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/composer.json.mustache index a768982234ae..de46c4b20ead 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/composer.json.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/composer.json.mustache @@ -5,13 +5,13 @@ "version": "{{artifactVersion}}", "type": "project", "require": { - "php": "^7.2", + "php": "^7.3 || ^8.0", "ext-yaml": "^2.0", "mezzio/mezzio": "^3.2", "laminas/laminas-diactoros": "^2.1", - "articus/path-handler": "^0.6", - "articus/data-transfer": "^0.4", - "articus/openapi-generator-common": "^0.1", + "articus/path-handler": "^0.7", + "articus/data-transfer": "^0.5", + "articus/openapi-generator-common": "^0.2", "doctrine/annotations": "^1.10", "psr/simple-cache": "^1.0", "laminas/laminas-config": "^3.4", diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/config.yml b/modules/openapi-generator/src/main/resources/php-mezzio-ph/config.yml index 1f106812353f..71371becf217 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/config.yml +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/config.yml @@ -9,10 +9,11 @@ # router: # cache: # directory: ./data/cache/PathHandler -# #Enable handler metadata cache -# metadata: -# cache: -# directory: ./data/cache/PathHandler + +#Enable handler metadata cache +#Articus\PathHandler\MetadataProvider\Annotation: +# cache: +# directory: ./data/cache/PathHandler #Enable data transfer metadata cache for DTOs #Articus\DataTransfer\MetadataProvider\Annotation: diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/data_transfer.yml.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/data_transfer.yml.mustache index c5174147c236..548c898fb9c8 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/data_transfer.yml.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/data_transfer.yml.mustache @@ -16,6 +16,10 @@ Articus\DataTransfer\Strategy\PluginManager: factories: Date: OpenAPIGenerator\Common\Strategy\Factory\MutableDate DateTime: OpenAPIGenerator\Common\Strategy\Factory\MutableDateTime + ObjectList: OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectList + ObjectMap: OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectMap + ScalarList: OpenAPIGenerator\Common\Strategy\Factory\ScalarList + ScalarMap: OpenAPIGenerator\Common\Strategy\Factory\ScalarMap Articus\DataTransfer\Validator\PluginManager: invokables: @@ -24,3 +28,7 @@ Articus\DataTransfer\Validator\PluginManager: QueryStringScalarArray: OpenAPIGenerator\Common\Validator\QueryStringScalarArray abstract_factories: - Articus\DataTransfer\Validator\Factory\Laminas + +validators: + invokables: + Count: Laminas\Validator\IsCountable diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/list_item_type.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/list_item_type.mustache new file mode 100644 index 000000000000..254676614331 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/list_item_type.mustache @@ -0,0 +1,8 @@ +{{#items +}}{{^isContainer +}}{{#isPrimitiveType}}"{{dataType}}"{{/isPrimitiveType +}}{{^isPrimitiveType}}{{dataType}}::class{{/isPrimitiveType +}}{{/isContainer +}}{{#isContainer +}}{{dataType}}::class{{/isContainer +}}{{/items}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/map_item_type.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/map_item_type.mustache new file mode 100644 index 000000000000..a58e19beca54 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/map_item_type.mustache @@ -0,0 +1,8 @@ +{{#additionalProperties +}}{{^isContainer +}}{{#isPrimitiveType}}"{{dataType}}"{{/isPrimitiveType +}}{{^isPrimitiveType}}{{dataType}}::class{{/isPrimitiveType +}}{{/isContainer +}}{{#isContainer +}}{{dataType}}::class{{/isContainer +}}{{/additionalProperties}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/model.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model.mustache index 57f70bfc7675..fd2a8cc62087 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/model.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model.mustache @@ -5,23 +5,9 @@ namespace {{package}}; use Articus\DataTransfer\Annotation as DTA; -/** -{{#description}} - * {{description}} -{{/description}} - */ -class {{classname}} -{ -{{#vars}} - /** -{{#description}} - * {{description}} -{{/description}} - * @DTA\Data(field="{{baseName}}"{{^required}}, nullable=true{{/required}}){{#vendorExtensions}}{{#internal.ze-ph.fromQuery}} -{{>model_query_var}}{{/internal.ze-ph.fromQuery}}{{/vendorExtensions}}{{#vendorExtensions}}{{^internal.ze-ph.fromQuery}} -{{>model_normal_var}}{{/internal.ze-ph.fromQuery}}{{/vendorExtensions}}{{^vendorExtensions}} -{{>model_normal_var}}{{/vendorExtensions}} * @var {{dataType}}|null - */ - public ${{name}}; -{{/vars}} -}{{/model}}{{/models}} +{{#vendorExtensions +}}{{#internal.ze-ph.fromContainer}}{{>model_container}}{{/internal.ze-ph.fromContainer +}}{{^internal.ze-ph.fromContainer}}{{>model_object}}{{/internal.ze-ph.fromContainer +}}{{/vendorExtensions +}}{{^vendorExtensions}}{{>model_object}}{{/vendorExtensions +}}{{/model}}{{/models}} diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_container.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_container.mustache new file mode 100644 index 000000000000..bbecf5ed1900 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_container.mustache @@ -0,0 +1,59 @@ +/** +{{#vars +}}{{#isArray +}} * @DTA\Strategy(name="{{#isPrimitiveType}}ScalarList{{/isPrimitiveType}}{{^isPrimitiveType}}ObjectList{{/isPrimitiveType}}", options={"type":{{>list_item_type}}}) +{{#minItems}}{{^maxItems +}} * @DTA\Validator(name="Count", options={"min":{{minItems}}}, blocker=true) +{{/maxItems}}{{/minItems +}}{{^minItems}}{{#maxItems +}} * @DTA\Validator(name="Count", options={"max":{{maxItems}}}, blocker=true) +{{/maxItems}}{{/minItems +}}{{#minItems}}{{#maxItems +}} * @DTA\Validator(name="Count", options={"min":{{minItems}},"max":{{maxItems}}}, blocker=true) +{{/maxItems}}{{/minItems +}} * @DTA\Validator(name="Collection", options={"validators":{ +{{#isPrimitiveType +}} * {"name":"Scalar", "options":{"type":{{>list_item_type}}}} +{{/isPrimitiveType +}}{{#isDate +}} * {"name":"Date"} +{{/isDate +}}{{#isDateTime +}} * {"name":"Date", "options":{"format": \DateTime::RFC3339}} +{{/isDateTime +}}{{^isPrimitiveType}}{{^isDate}}{{^isDateTime +}} * {"name":"TypeCompliant", "options":{"type":{{>list_item_type}}}} +{{/isDateTime}}{{/isDate}}{{/isPrimitiveType +}} * }}) +{{/isArray +}}{{#isMap +}} * @DTA\Strategy(name="{{#isPrimitiveType}}ScalarMap{{/isPrimitiveType}}{{^isPrimitiveType}}ObjectMap{{/isPrimitiveType}}", options={"type":{{>map_item_type}}}) +{{#minProperties}}{{^maxProperties +}} * @DTA\Validator(name="Count", options={"min":{{minProperties}}}, blocker=true) +{{/maxProperties}}{{/minProperties +}}{{^minProperties}}{{#maxProperties +}} * @DTA\Validator(name="Count", options={"max":{{maxProperties}}}, blocker=true) +{{/maxProperties}}{{/minProperties +}}{{#minProperties}}{{#maxProperties +}} * @DTA\Validator(name="Count", options={"min":{{minProperties}},"max":{{maxProperties}}}, blocker=true) +{{/maxProperties}}{{/minProperties +}} * @DTA\Validator(name="Collection", options={"validators":{ +{{#isPrimitiveType +}} * {"name":"Scalar", "options":{"type":{{>map_item_type}}}} +{{/isPrimitiveType +}}{{#isDate +}} * {"name":"Date"} +{{/isDate +}}{{#isDateTime +}} * {"name":"Date", "options":{"format": \DateTime::RFC3339}} +{{/isDateTime +}}{{^isPrimitiveType}}{{^isDate}}{{^isDateTime +}} * {"name":"TypeCompliant", "options":{"type":{{>map_item_type}}}} +{{/isDateTime}}{{/isDate}}{{/isPrimitiveType +}} * }}) +{{/isMap +}}{{/vars +}} */ +class {{classname}} extends \ArrayObject +{ +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_normal_var.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_normal_var.mustache index 33c6e46337a8..fe568901f9b1 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_normal_var.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_normal_var.mustache @@ -1,64 +1,45 @@ -{{^isPrimitiveType}} -{{^isContainer}} -{{^isDate}} -{{^isDateTime}} - * @DTA\Strategy(name="Object", options={"type":{{dataType}}::class}) - * @DTA\Validator(name="TypeCompliant", options={"type":{{dataType}}::class}) -{{/isDateTime}} -{{/isDate}} -{{#isDate}} - * @DTA\Strategy(name="Date") +{{#isContainer +}} * @DTA\Strategy(name="Object", options={"type":{{internal.ze-ph.containerDataType}}::class}) + * @DTA\Validator(name="TypeCompliant", options={"type":{{internal.ze-ph.containerDataType}}::class}) +{{/isContainer +}}{{^isContainer +}}{{#isPrimitiveType +}} * @DTA\Validator(name="Scalar", options={"type":"{{dataType}}"}) +{{/isPrimitiveType +}}{{#isDate +}} * @DTA\Strategy(name="Date") * @DTA\Validator(name="Date") -{{/isDate}} -{{#isDateTime}} - * @DTA\Strategy(name="DateTime") +{{/isDate +}}{{#isDateTime +}} * @DTA\Strategy(name="DateTime") * @DTA\Validator(name="Date", options={"format": \DateTime::RFC3339}) -{{/isDateTime}} -{{/isContainer}} -{{#isContainer}} - * TODO check validator and strategy are correct and can handle container item type - * @DTA\Strategy(name="ObjectArray", options={"type":{{#items}}{{dataType}}{{/items}}::class}) - * @DTA\Validator(name="Collection", options={"validators":{ - * {"name":"TypeCompliant", "options":{"type":{{#items}}{{dataType}}{{/items}}::class}} - * }}) -{{/isContainer}} -{{/isPrimitiveType}} -{{#isPrimitiveType}} -{{#isContainer}} -{{#items}} - * TODO check validator and strategy are correct and can handle container item type - * @DTA\Validator(name="Collection", options={"validators":{ - * {"name":"Scalar", "options":{"type":"{{dataType}}"}} - * }}) -{{/items}} -{{/isContainer}} -{{^isContainer}} - * @DTA\Validator(name="Scalar", options={"type":"{{dataType}}"}) -{{/isContainer}} -{{/isPrimitiveType}} -{{#hasValidation}} -{{#minLength}} -{{#maxLength}} - * @DTA\Validator(name="StringLength", options={"min":{{minLength}}, "max":{{maxLength}}}) -{{/maxLength}} -{{/minLength}} -{{^minLength}} -{{#maxLength}} - * @DTA\Validator(name="StringLength", options={"max":{{maxLength}}}) -{{/maxLength}} -{{/minLength}} -{{#minLength}} -{{^maxLength}} - * @DTA\Validator(name="StringLength", options={"min":{{minLength}}}) -{{/maxLength}} -{{/minLength}} -{{#minimum}} - * @DTA\Validator(name="GreaterThan", options={"min":{{minimum}}{{^exclusiveMinimum}}, "inclusive":true{{/exclusiveMinimum}}}) -{{/minimum}} -{{#maximum}} - * @DTA\Validator(name="LessThan", options={"max":{{maximum}}{{^exclusiveMaximum}}, "inclusive":true{{/exclusiveMaximum}}}) -{{/maximum}} -{{#pattern}} - * @DTA\Validator(name="Regex", options={"pattern":"{{{pattern}}}"}) -{{/pattern}} -{{/hasValidation}} \ No newline at end of file +{{/isDateTime +}}{{^isPrimitiveType +}}{{^isDate +}}{{^isDateTime +}} * @DTA\Strategy(name="Object", options={"type":{{dataType}}::class}) + * @DTA\Validator(name="TypeCompliant", options={"type":{{dataType}}::class}) +{{/isDateTime +}}{{/isDate +}}{{/isPrimitiveType +}}{{/isContainer +}}{{#hasValidation +}}{{#minLength}}{{#maxLength +}} * @DTA\Validator(name="StringLength", options={"min":{{minLength}}, "max":{{maxLength}}}) +{{/maxLength}}{{/minLength +}}{{^minLength}}{{#maxLength +}} * @DTA\Validator(name="StringLength", options={"max":{{maxLength}}}) +{{/maxLength}}{{/minLength +}}{{#minLength}}{{^maxLength +}} * @DTA\Validator(name="StringLength", options={"min":{{minLength}}}) +{{/maxLength}}{{/minLength +}}{{#minimum +}} * @DTA\Validator(name="GreaterThan", options={"min":{{minimum}}{{^exclusiveMinimum}}, "inclusive":true{{/exclusiveMinimum}}}) +{{/minimum +}}{{#maximum +}} * @DTA\Validator(name="LessThan", options={"max":{{maximum}}{{^exclusiveMaximum}}, "inclusive":true{{/exclusiveMaximum}}}) +{{/maximum +}}{{#pattern +}} * @DTA\Validator(name="Regex", options={"pattern":"{{{pattern}}}"}) +{{/pattern +}}{{/hasValidation}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_object.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_object.mustache new file mode 100644 index 000000000000..2e7d61fde458 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_object.mustache @@ -0,0 +1,24 @@ +/** +{{#description +}} * {{description}} +{{/description +}} */ +class {{classname}} +{ +{{#vars +}} /** +{{#description +}} * {{description}} +{{/description +}} * @DTA\Data(field="{{baseName}}"{{^required}}, nullable=true{{/required}}) +{{#vendorExtensions +}}{{#internal.ze-ph.fromQuery}}{{>model_query_var}}{{/internal.ze-ph.fromQuery +}}{{^internal.ze-ph.fromQuery}}{{>model_normal_var}}{{/internal.ze-ph.fromQuery +}}{{/vendorExtensions +}}{{^vendorExtensions}}{{>model_normal_var}}{{/vendorExtensions +}} * @var {{dataType}}|null + */ + public ${{name}}; + +{{/vars +}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_query_var.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_query_var.mustache index 27f0a72c955e..deaf0e370494 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_query_var.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_query_var.mustache @@ -1,52 +1,51 @@ -{{^isPrimitiveType}} -{{^isContainer}} -{{#isDate}} - * @DTA\Strategy(name="Date") +{{#isArray +}}{{#isPrimitiveType +}} * @DTA\Strategy(name="QueryStringScalarArray", options={"type":{{>list_item_type}}, "format":"{{internal.ze-ph.collectionFormat}}"}) + * @DTA\Validator(name="QueryStringScalarArray", options={"type":{{>list_item_type}}, "format":"{{internal.ze-ph.collectionFormat}}"{{#minItems}}, "min_items":{{minItems}}{{/minItems}}{{#maxItems}}, "max_items":{{maxItems}}{{/maxItems}}}) +{{/isPrimitiveType +}}{{^isPrimitiveType +}} * TODO add validator(s) and strategy for list of {{>list_item_type}} and collection format {{internal.ze-ph.collectionFormat}} inside query string +{{/isPrimitiveType +}}{{/isArray +}}{{#isMap +}} * TODO add validator(s) and strategy for map of {{>map_item_type}} and collection format {{internal.ze-ph.collectionFormat}} inside query string +{{/isMap +}}{{^isContainer +}}{{#isPrimitiveType +}} * @DTA\Strategy(name="QueryStringScalar", options={"type":"{{dataType}}"}) + * @DTA\Validator(name="QueryStringScalar", options={"type":"{{dataType}}"}) +{{/isPrimitiveType +}}{{#isDate +}} * @DTA\Strategy(name="Date") * @DTA\Validator(name="Date") -{{/isDate}} -{{#isDateTime}} - * @DTA\Strategy(name="DateTime") +{{/isDate +}}{{#isDateTime +}} * @DTA\Strategy(name="DateTime") * @DTA\Validator(name="Date", options={"format": \DateTime::RFC3339}) -{{/isDateTime}} -{{/isContainer}} -{{#isContainer}} - * TODO add validator(s) and strategy for {{dataType}} and collection format {{internal.ze-ph.collectionFormat}} -{{/isContainer}} -{{/isPrimitiveType}} -{{#isPrimitiveType}} -{{#isContainer}} - * TODO check validator and strategy are correct and can handle container item type - * @DTA\Strategy(name="QueryStringScalarArray", options={"type":"{{#items}}{{dataType}}{{/items}}", "format":"{{internal.ze-ph.collectionFormat}}"}) - * @DTA\Validator(name="QueryStringScalarArray", options={"type":"{{#items}}{{dataType}}{{/items}}", "format":"{{internal.ze-ph.collectionFormat}}"{{#minItems}}, "min_items":{{minItems}}{{/minItems}}{{#maxItems}}, "max_items":{{maxItems}}{{/maxItems}}}) -{{/isContainer}} -{{^isContainer}} - * @DTA\Strategy(name="QueryStringScalar", options={"type":"{{dataType}}"}) - * @DTA\Validator(name="QueryStringScalar", options={"type":"{{dataType}}"}) -{{/isContainer}} -{{/isPrimitiveType}} -{{#hasValidation}} -{{#minLength}} -{{#maxLength}} - * @DTA\Validator(name="StringLength", options={"min":{{minLength}}, "max":{{maxLength}}}) -{{/maxLength}} -{{/minLength}} -{{^minLength}} -{{#maxLength}} - * @DTA\Validator(name="StringLength", options={"max":{{maxLength}}}) -{{/maxLength}} -{{/minLength}} -{{#minLength}} -{{^maxLength}} - * @DTA\Validator(name="StringLength", options={"min":{{minLength}}}) -{{/maxLength}} -{{/minLength}} -{{#minimum}} - * @DTA\Validator(name="GreaterThan", options={"min":{{minimum}}{{^exclusiveMinimum}}, "inclusive":true{{/exclusiveMinimum}}}) -{{/minimum}} -{{#maximum}} - * @DTA\Validator(name="LessThan", options={"max":{{maximum}}{{^exclusiveMaximum}}, "inclusive":true{{/exclusiveMaximum}}}) -{{/maximum}} -{{#pattern}} - * @DTA\Validator(name="Regex", options={"pattern":"{{{pattern}}}"}) -{{/pattern}} -{{/hasValidation}} \ No newline at end of file +{{/isDateTime +}}{{^isPrimitiveType +}}{{^isDate}}{{^isDateTime +}} * TODO add validator(s) and strategy for {{dataType}} inside query string +{{/isDateTime}}{{/isDate +}}{{/isPrimitiveType +}}{{/isContainer +}}{{#hasValidation +}}{{#minLength}}{{#maxLength +}} * @DTA\Validator(name="StringLength", options={"min":{{minLength}}, "max":{{maxLength}}}) +{{/maxLength}}{{/minLength +}}{{^minLength}}{{#maxLength +}} * @DTA\Validator(name="StringLength", options={"max":{{maxLength}}}) +{{/maxLength}}{{/minLength +}}{{#minLength}}{{^maxLength +}} * @DTA\Validator(name="StringLength", options={"min":{{minLength}}}) +{{/maxLength}}{{/minLength +}}{{#minimum +}} * @DTA\Validator(name="GreaterThan", options={"min":{{minimum}}{{^exclusiveMinimum}}, "inclusive":true{{/exclusiveMinimum}}}) +{{/minimum +}}{{#maximum +}} * @DTA\Validator(name="LessThan", options={"max":{{maximum}}{{^exclusiveMaximum}}, "inclusive":true{{/exclusiveMaximum}}}) +{{/maximum +}}{{#pattern +}} * @DTA\Validator(name="Regex", options={"pattern":"{{{pattern}}}"}) +{{/pattern +}}{{/hasValidation}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/path_handler.yml.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/path_handler.yml.mustache index dd01611f359d..1f9167a0fa4e 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/path_handler.yml.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/path_handler.yml.mustache @@ -1,8 +1,13 @@ dependencies: factories: - Mezzio\Router\RouterInterface: Articus\PathHandler\RouteInjection\Factory + Mezzio\Router\RouterInterface: Articus\PathHandler\RouteInjectionFactory + Articus\PathHandler\MetadataProviderInterface: Articus\PathHandler\MetadataProvider\Factory\Annotation + Articus\PathHandler\Handler\PluginManager: Articus\PathHandler\Handler\Factory\PluginManager + Articus\PathHandler\Consumer\PluginManager: Articus\PathHandler\Consumer\Factory\PluginManager + Articus\PathHandler\Attribute\PluginManager: Articus\PathHandler\Attribute\Factory\PluginManager + Articus\PathHandler\Producer\PluginManager: Articus\PathHandler\Producer\Factory\PluginManager -Articus\PathHandler\RouteInjection\Factory: +Articus\PathHandler\RouteInjectionFactory: paths: '{{basePathWithoutHost}}': {{#apiInfo}} @@ -12,18 +17,22 @@ Articus\PathHandler\RouteInjection\Factory: {{/operations}} {{/apis}} {{/apiInfo}} - handlers: - abstract_factories: - - Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory -# consumers: -# factories: -# invokables: -# attributes: -# factories: -# invokables: -# producers: -# factories: -# invokables: + +Articus\PathHandler\Handler\PluginManager: + abstract_factories: + - Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory + +#Articus\PathHandler\Consumer\PluginManager: +# factories: +# invokables: + +#Articus\PathHandler\Attribute\PluginManager: +# factories: +# invokables: + +#Articus\PathHandler\Producer\PluginManager: +# factories: +# invokables: Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory: {{#apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/php-symfony/model_variables.mustache b/modules/openapi-generator/src/main/resources/php-symfony/model_variables.mustache index 3ef46d1c9b05..d79a5feb74ab 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/model_variables.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/model_variables.mustache @@ -7,6 +7,9 @@ * @SerializedName("{{baseName}}") {{#required}} * @Assert\NotNull() + {{^isPrimitiveType}} + * @Assert\Valid() + {{/isPrimitiveType}} {{/required}} {{#isEnum}} {{#isContainer}} diff --git a/modules/openapi-generator/src/main/resources/php/model_generic.mustache b/modules/openapi-generator/src/main/resources/php/model_generic.mustache index 276b2bd9d8cf..64bb657af16d 100644 --- a/modules/openapi-generator/src/main/resources/php/model_generic.mustache +++ b/modules/openapi-generator/src/main/resources/php/model_generic.mustache @@ -188,12 +188,12 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}}{{/parentSchema}}{{^par */ public function listInvalidProperties() { - {{#parent}} + {{#parentSchema}} $invalidProperties = parent::listInvalidProperties(); - {{/parent}} - {{^parent}} + {{/parentSchema}} + {{^parentSchema}} $invalidProperties = []; - {{/parent}} + {{/parentSchema}} {{#vars}} {{#required}} diff --git a/modules/openapi-generator/src/main/resources/powershell/api_doc.mustache b/modules/openapi-generator/src/main/resources/powershell/api_doc.mustache index c892573091e6..7903ec98afed 100644 --- a/modules/openapi-generator/src/main/resources/powershell/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/api_doc.mustache @@ -78,8 +78,8 @@ Name | Type | Description | Notes {{/allParams}} ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type -{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md) (PSCustomObject){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} ### Authorization diff --git a/modules/openapi-generator/src/main/resources/powershell/appveyor.mustache b/modules/openapi-generator/src/main/resources/powershell/appveyor.mustache index bf3770e187a6..d1047879e53b 100644 --- a/modules/openapi-generator/src/main/resources/powershell/appveyor.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/appveyor.mustache @@ -1,24 +1,26 @@ {{> partial_header}} version: 1.0.{build} image: - - Visual Studio 2019 # PS 6.x - #- Visual Studio 2017 # PS 5.x - #- Ubuntu # PS 6.x - # ref: https://www.appveyor.com/docs/build-environment/#build-worker-images + - Visual Studio 2019 # PWSH 7.x + #- Visual Studio 2017 # PS 5.x, PWSH 6.x + #- Ubuntu # PWSH 6.x + # ref: https://www.appveyor.com/docs/windows-images-software/ install: - - ps: $PSVersionTable.PSVersion - - ps: Install-Module Pester -Force -Scope CurrentUser + - pwsh: $PSVersionTable.PSVersion + - pwsh: Install-Module Pester -Force -Scope CurrentUser build: off test_script: - - ps: | + - pwsh: | + .\Build.ps1 + Import-Module -Name '.\src\{{{packageName}}}' $Result = Invoke-Pester -PassThru if ($Result.FailedCount -gt 0) { $host.SetShouldExit($Result.FailedCount) exit $Result.FailedCount } deploy_script: - - ps: | - if ($env:APPVEYOR_REPO_TAG -eq $true -and $env:NuGetApiKey -ne $null -and $env:APPVEYOR_BUILD_WORKER_IMAGE -eq "Visual Studio 2019") { + - pwsh: | + if ($env:APPVEYOR_REPO_TAG -eq $true -and $env:NuGetApiKey -ne $null) { .\Build.ps1 try { Publish-Module -NuGetApiKey $env:NuGetApiKey -Path .\src\{{{packageName}}}\ -Confirm:$False -Verbose diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/Dockerfile.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/Dockerfile.mustache new file mode 100644 index 000000000000..395fed380e6c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/Dockerfile.mustache @@ -0,0 +1,30 @@ +FROM python:3.6 AS builder + +WORKDIR /usr/src/app + +RUN python3 -m venv /venv +ENV PATH="/venv/bin:$PATH" + +RUN pip install --upgrade pip + +COPY . . +RUN pip install --no-cache-dir . + + +FROM python:3.6 AS test_runner +WORKDIR /tmp +COPY --from=builder /venv /venv +COPY --from=builder /usr/src/app/tests tests +ENV PATH=/venv/bin:$PATH + +# install test dependencies +RUN pip install pytest + +# run tests +RUN pytest tests + + +FROM python:3.6 AS service +WORKDIR /root/app/site-packages +COPY --from=test_runner /venv /venv +ENV PATH=/venv/bin:$PATH diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/README.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/README.mustache new file mode 100644 index 000000000000..6528c7920266 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/README.mustache @@ -0,0 +1,32 @@ +# OpenAPI generated FastAPI server + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: {{appVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} + +## Requirements. + +Python >= 3.6 + +## Installation & Usage + +To run the server, please execute the following from the root directory: + +``` + pip3 install -r requirements.txt + uvicorn main:app --host 0.0.0.0 --port {{serverPort}} +``` + +and open your browser at `http://localhost:{{serverPort}}/docs/` to see the docs. + +## Running with Docker + +To run the server on a Docker container, please execute the following from the root directory: + +```bash +docker-compose up --build +``` diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/__init__.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/__init__.mustache new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/api.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/api.mustache new file mode 100644 index 000000000000..21c091251ad8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/api.mustache @@ -0,0 +1,64 @@ +# coding: utf-8 + +from typing import Dict, List + +from fastapi import ( + APIRouter, + Body, + Cookie, + Depends, + Form, + Header, + Path, + Query, + Response, + Security, + status, +) + +from {{modelPackage}}.extra_models import TokenModel +{{#imports}} +{{import}} +{{/imports}} +{{#securityImports.0}}from {{packageName}}.security_api import {{#securityImports}}get_token_{{.}}{{^-last}}, {{/-last}}{{/securityImports}}{{/securityImports.0}} + +router = APIRouter() + + +{{#operations}} +{{#operation}} +@router.{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}( + "{{path}}", + responses={ + {{#responses}} + {{code}}: {{=<% %>=}}{<%#dataType%>"model": <%dataType%>, "description": "<%message%>"<%/dataType%><%^dataType%>"description": "<%message%>"<%/dataType%>}<%={{ }}=%>, + {{/responses}} + }, + tags=[{{#tags}}"{{name}}"{{^-last}},{{/-last}}{{/tags}}], + {{#summary}} + summary="{{summary}}", + {{/summary}} + {{#description}} + description = "{{description}}", + {{/description}} +) +async def {{operationId}}( + {{#allParams}} + {{>endpoint_argument_definition}}, + {{/allParams}} + {{#hasAuthMethods}} + {{#authMethods}} + token_{{name}}: TokenModel = Security( + get_token_{{name}}{{#isOAuth}}, scopes=[{{#scopes}}"{{scope}}"{{^-last}}, {{/-last}}{{/scopes}}]{{/isOAuth}} + ), + {{/authMethods}} + {{/hasAuthMethods}} +) -> {{#returnType}}{{.}}{{/returnType}}{{^returnType}}None{{/returnType}}: # noqa: E501 + {{#notes}}"""{{.}}""" + ...{{/notes}}{{^notes}}...{{/notes}} +{{^-last}} + + +{{/-last}} +{{/operation}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/api_test.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/api_test.mustache new file mode 100644 index 000000000000..a3470a2323ee --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/api_test.mustache @@ -0,0 +1,53 @@ +# coding: utf-8 + +from fastapi.testclient import TestClient + +import json +import pytest + +{{#imports}}{{import}} +{{/imports}} + +{{#operations}} +{{#operation}} + +{{#vendorExtensions.x-skip-test}} +@pytest.mark.skip("{{reason}}") +{{/vendorExtensions.x-skip-test}} +def test_{{operationId}}(client: TestClient): + """Test case for {{{operationId}}} + + {{{summary}}} + """ + {{#bodyParam}} + {{paramName}} = {{#isContainer}}[{{/isContainer}}{{{example}}}{{#isContainer}}]{{/isContainer}} + {{/bodyParam}} + {{#queryParams}} + {{#-first}}params = [{{/-first}}{{^-first}} {{/-first}}("{{paramName}}", {{{example}}}){{^-last}},{{/-last}}{{#-last}}]{{/-last}} + {{/queryParams}} + headers = { {{#headerParams}} + '{{paramName}}': {{{example}}},{{/headerParams}}{{#authMethods}} + {{#isOAuth}}'Authorization': 'Bearer special-key',{{/isOAuth}}{{#isApiKey}}'{{name}}': 'special-key',{{/isApiKey}}{{#isBasicBasic}}'Authorization': 'BasicZm9vOmJhcg==',{{/isBasicBasic}}{{#isBasicBearer}}'Authorization': 'Bearer special-key',{{/isBasicBearer}}{{/authMethods}} + } + {{#formParams}} + {{#-first}} + data = { + {{/-first}} + '{{paramName}}': {{{example}}}{{^-last}},{{/-last}} + {{#-last}} + } + {{/-last}} + {{/formParams}} + response = client.request( + '{{httpMethod}}', + '{{{path}}}'{{#pathParams}}{{#-first}}.format({{/-first}}{{baseName}}={{{example}}}{{^-last}}, {{/-last}}{{#-last}}){{/-last}}{{/pathParams}}, + headers=headers,{{#bodyParam}} + json={{paramName}},{{/bodyParam}}{{#formParams}}{{#-first}} + data=data,{{/-first}}{{/formParams}}{{#queryParams}}{{#-first}} + params=params,{{/-first}}{{/queryParams}} + ) + + assert response.status_code == 200 + +{{/operation}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/conftest.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/conftest.mustache new file mode 100644 index 000000000000..357ea48c3ab8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/conftest.mustache @@ -0,0 +1,20 @@ +import contextlib +from typing import Any + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from {{packageName}}.main import app as application + + +@pytest.fixture +def app() -> FastAPI: + application.dependency_overrides = {} + + return application + + +@pytest.fixture +def client(app) -> TestClient: + return TestClient(app) diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/docker-compose.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/docker-compose.mustache new file mode 100644 index 000000000000..b4ffa0029173 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/docker-compose.mustache @@ -0,0 +1,9 @@ +version: '3.6' +services: + service: + build: + context: . + target: service + ports: + - "{{serverPort}}:{{serverPort}}" + command: uvicorn {{packageName}}.main:app --host 0.0.0.0 --port {{serverPort}} diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/endpoint_argument_definition.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/endpoint_argument_definition.mustache new file mode 100644 index 000000000000..939bfda10a6b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/endpoint_argument_definition.mustache @@ -0,0 +1 @@ +{{#isPathParam}}{{baseName}}{{/isPathParam}}{{^isPathParam}}{{paramName}}{{/isPathParam}}: {{>param_type}} = {{#isPathParam}}Path{{/isPathParam}}{{#isHeaderParam}}Header{{/isHeaderParam}}{{#isFormParam}}Form{{/isFormParam}}{{#isQueryParam}}Query{{/isQueryParam}}{{#isCookieParam}}Cookie{{/isCookieParam}}{{#isBodyParam}}Body{{/isBodyParam}}(None, description="{{description}}") diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/extra_models.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/extra_models.mustache new file mode 100644 index 000000000000..a3a283fb842b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/extra_models.mustache @@ -0,0 +1,8 @@ +# coding: utf-8 + +from pydantic import BaseModel + +class TokenModel(BaseModel): + """Defines a token model.""" + + sub: str diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/gitignore.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/gitignore.mustache new file mode 100644 index 000000000000..a81c8ee12195 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/gitignore.mustache @@ -0,0 +1,138 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/main.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/main.mustache new file mode 100644 index 000000000000..7112b2719784 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/main.mustache @@ -0,0 +1,23 @@ +# coding: utf-8 + +{{>partial_header}} + +from fastapi import FastAPI + +{{#apiInfo}} +{{#apis}} +from {{apiPackage}}.{{classFilename}} import router as {{classname}}Router +{{/apis}} +{{/apiInfo}} + +app = FastAPI( + title="{{appName}}", + description="{{appDescription}}", + version="{{appVersion}}", +) + +{{#apiInfo}} +{{#apis}} +app.include_router({{classname}}Router) +{{/apis}} +{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/model.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/model.mustache new file mode 100644 index 000000000000..f6a15877fa4f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/model.mustache @@ -0,0 +1,35 @@ +# coding: utf-8 + +from datetime import date, datetime + +from typing import Dict, List, Optional + +from pydantic import BaseModel, EmailStr, validator +{{#models}} +{{#model}} +{{#pyImports}} +{{import}} +{{/pyImports}} +{{/model}} +{{/models}} + + +{{#models}} +{{#model}} +class {{classname}}(BaseModel): + """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + + Do not edit the class manually. + + {{classname}} - a model defined in OpenAPI + + {{#vars}} + {{name}}: The {{name}} of this {{classname}}{{^required}} [Optional]{{/required}}. + {{/vars}} + """ + +{{#vars}} + {{name}}: {{#required}}{{dataType}}{{/required}}{{^required}}Optional[{{dataType}}] = None{{/required}} +{{/vars}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/openapi.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/openapi.mustache new file mode 100644 index 000000000000..51ebafb0187d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/param_type.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/param_type.mustache new file mode 100644 index 000000000000..d97c018015fa --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/param_type.mustache @@ -0,0 +1 @@ +{{#isString}}str{{/isString}}{{#isInteger}}int{{/isInteger}}{{#isLong}}int{{/isLong}}{{#isFloat}}float{{/isFloat}}{{#isDouble}}float{{/isDouble}}{{#isByteArray}}str{{/isByteArray}}{{#isBinary}}str{{/isBinary}}{{#isBoolean}}bool{{/isBoolean}}{{#isDate}}str{{/isDate}}{{#isDateTime}}str{{/isDateTime}}{{#isModel}}{{dataType}}{{/isModel}}{{#isContainer}}{{dataType}}{{/isContainer}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/partial_header.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/partial_header.mustache new file mode 100644 index 000000000000..62e28acde9b9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/partial_header.mustache @@ -0,0 +1,17 @@ +""" +{{#appName}} + {{{appName}}} +{{/appName}} + +{{#appDescription}} + {{{appDescription}}} +{{/appDescription}} + + {{#version}} + The version of the OpenAPI document: {{{version}}} + {{/version}} + {{#infoEmail}} + Contact: {{{infoEmail}}} + {{/infoEmail}} + Generated by: https://openapi-generator.tech +""" diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/pyproject_toml.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/pyproject_toml.mustache new file mode 100644 index 000000000000..c2826df30203 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/pyproject_toml.mustache @@ -0,0 +1,30 @@ +[build-system] +requires = ["setuptools", "wheel"] +build-backend = "setuptools.build_meta" + +[tool.black] +line-length = 88 +exclude = ''' +( + /( + \.eggs # exclude a few common directories in the + | \.git # root of the project + | \.hg + | \.mypy_cache + | \.tox + | \.venv + | _build + | buck-out + | build + | dist + )/ +) +''' + +[tool.isort] +profile = "black" +skip = [ + '.eggs', '.git', '.hg', '.mypy_cache', '.nox', '.pants.d', '.tox', + '.venv', '_build', 'buck-out', 'build', 'dist', 'node_modules', 'venv', +] +skip_gitignore = true diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/requirements.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/requirements.mustache new file mode 100644 index 000000000000..ce66f96d42c9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/requirements.mustache @@ -0,0 +1,36 @@ +aiofiles==0.5.0 +aniso8601==7.0.0 +async-exit-stack==1.0.1 +async-generator==1.10 +certifi==2020.12.5 +chardet==4.0.0 +click==7.1.2 +dnspython==2.1.0 +email-validator==1.1.2 +fastapi==0.65.1 +graphene==2.1.8 +graphql-core==2.3.2 +graphql-relay==2.0.1 +h11==0.12.0 +httptools==0.1.2 +idna==2.10 +itsdangerous==1.1.0 +Jinja2==2.11.3 +MarkupSafe==2.0.1 +orjson==3.5.2 +promise==2.3 +pydantic==1.8.2 +python-dotenv==0.17.1 +python-multipart==0.0.5 +PyYAML==5.4.1 +requests==2.25.1 +Rx==1.6.1 +six==1.16.0 +starlette==0.14.2 +typing-extensions==3.10.0.0 +ujson==4.0.2 +urllib3==1.26.4 +uvicorn==0.13.4 +uvloop==0.14.0 +watchgod==0.7 +websockets==8.1 diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/security_api.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/security_api.mustache new file mode 100644 index 000000000000..77bceb11cfa5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/security_api.mustache @@ -0,0 +1,157 @@ +# coding: utf-8 + +from typing import List + +from fastapi import APIRouter, Depends, Response, Security, status +from fastapi.openapi.models import OAuthFlowImplicit, OAuthFlows +from fastapi.security import ( + HTTPAuthorizationCredentials, + HTTPBasic, + HTTPBasicCredentials, + HTTPBearer, + OAuth2, + OAuth2AuthorizationCodeBearer, + OAuth2PasswordBearer, + SecurityScopes, +) +from fastapi.security.api_key import APIKey, APIKeyCookie, APIKeyHeader, APIKeyQuery + +from {{modelPackage}}.extra_models import TokenModel + +{{#authMethods}} +{{#isOAuth}} +{{#isPassword}} +oauth2_password = OAuth2PasswordBearer( + tokenUrl="{{tokenUrl}}", + scopes={ +{{#scopes}} + "{{scope}}": "{{description}}", +{{/scopes}} + } +) +{{/isPassword}} +{{#isCode}} +oauth2_code = OAuth2AuthorizationCodeBearer( + authorizationUrl="{{authorizationUrl}}", + tokenUrl="{{tokenUrl}}", + refreshUrl="{{refreshUrl}}", + scopes={ +{{#scopes}} + "{{scope}}": "{{description}}", +{{/scopes}} + } +) +{{/isCode}} +{{#isImplicit}} +oauth2_implicit = OAuth2( + flows=OAuthFlows( + implicit=OAuthFlowImplicit( + authorizationUrl="{{authorizationUrl}}", + scopes={ +{{#scopes}} + "{{scope}}": "{{description}}", +{{/scopes}} + } + ) + ) +) +{{/isImplicit}} + + +def get_token_{{name}}( + security_scopes: SecurityScopes, token: str = Depends(oauth2_{{#isPassword}}password{{/isPassword}}{{#isCode}}code{{/isCode}}{{#isImplicit}}implicit{{/isImplicit}}) +) -> TokenModel: + """ + Validate and decode token. + + :param token Token provided by Authorization header + :type token: str + :return: Decoded token information or None if token is invalid + :rtype: TokenModel | None + """ + + ... + + +def validate_scope_{{name}}( + required_scopes: SecurityScopes, token_scopes: List[str] +) -> bool: + """ + Validate required scopes are included in token scope + + :param required_scopes Required scope to access called API + :type required_scopes: List[str] + :param token_scopes Scope present in token + :type token_scopes: List[str] + :return: True if access to called API is allowed + :rtype: bool + """ + + return False + +{{/isOAuth}} +{{#isApiKey}} + +def get_token_{{name}}( + {{#isKeyInHeader}}token_api_key_header: str = Security( + APIKeyHeader(name="{{keyParamName}}", auto_error=False) + ),{{/isKeyInHeader}}{{#isKeyInCookie}} + token_api_key_cookie: str = Security( + APIKeyCookie(name="{{keyParamName}}", auto_error=False) + ),{{/isKeyInCookie}}{{#isKeyInQuery}} + token_api_key_query: str = Security( + APIKeyQuery(name="{{keyParamName}}", auto_error=False) + ),{{/isKeyInQuery}} +) -> TokenModel: + """ + Check and retrieve authentication information from api_key. + + {{#isKeyInHeader}}:param token_api_key_header API key provided by Authorization[{{keyParamName}}] header{{/isKeyInHeader}} + {{#isKeyInCookie}}:param token_api_key_cookie API key provided by Authorization[{{keyParamName}}] cookie{{/isKeyInCookie}} + {{#isKeyInQuery}}:param token_api_key_query API key provided by [{{keyParamName}}] query{{/isKeyInQuery}} + :type token_api_key_{{#isKeyInHeader}}header{{/isKeyInHeader}}{{#isKeyInCookie}}cookie{{/isKeyInCookie}}{{#isKeyInQuery}}query{{/isKeyInQuery}}: str + :return: Information attached to provided api_key or None if api_key is invalid or does not allow access to called API + :rtype: TokenModel | None + """ + + ... + +{{/isApiKey}} +{{#isBasicBasic}} + +basic_auth = HTTPBasic() + + +def get_token_{{name}}( + credentials: HTTPBasicCredentials = Depends(basic_auth) +) -> TokenModel: + """ + Check and retrieve authentication information from basic auth. + + :param credentials Credentials provided by Authorization header + :type credentials: HTTPBasicCredentials + :rtype: TokenModel | None + """ + + ... + +{{/isBasicBasic}} +{{#isBasicBearer}} + +bearer_auth = HTTPBearer() + + +def get_token_{{name}}(credentials: HTTPAuthorizationCredentials = Depends(bearer_auth)) -> TokenModel: + """ + Check and retrieve authentication information from custom bearer token. + + :param credentials Credentials provided by Authorization header + :type credentials: HTTPAuthorizationCredentials + :return: Decoded token information or None if token is invalid + :rtype: TokenModel | None + """ + + ... + +{{/isBasicBearer}} +{{/authMethods}} diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/setup_cfg.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/setup_cfg.mustache new file mode 100644 index 000000000000..ff5cfe968e0b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/setup_cfg.mustache @@ -0,0 +1,23 @@ +[metadata] +name = {{packageName}} +version = {{appVersion}} +description = {{appDescription}} +long_description = file: README.md +keywords = OpenAPI {{appName}} +python_requires = >= 3.6.* +classifiers = + Operating System :: OS Independent + Programming Language :: Python :: 3 + Programming Language :: Python :: 3.6 + +[options] +install_requires = + fastapi[all] +setup_requires = + setuptools +package_dir= + =src +packages=find_namespace: + +[options.packages.find] +where=src diff --git a/modules/openapi-generator/src/main/resources/python-flask/requirements.mustache b/modules/openapi-generator/src/main/resources/python-flask/requirements.mustache index 6e2cf517819f..2d1a20a01902 100644 --- a/modules/openapi-generator/src/main/resources/python-flask/requirements.mustache +++ b/modules/openapi-generator/src/main/resources/python-flask/requirements.mustache @@ -22,3 +22,4 @@ typing >= 3.5.2.2 pyyaml < 5.3; python_version<="2.7" {{/supportPython2}} setuptools >= 21.0.0 +Flask == 1.1.2 diff --git a/modules/openapi-generator/src/main/resources/python-legacy/model.mustache b/modules/openapi-generator/src/main/resources/python-legacy/model.mustache index 5b4048915eb8..236b8f8c3a2e 100644 --- a/modules/openapi-generator/src/main/resources/python-legacy/model.mustache +++ b/modules/openapi-generator/src/main/resources/python-legacy/model.mustache @@ -2,7 +2,10 @@ {{>partial_header}} -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -203,7 +206,7 @@ class {{classname}}(object): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/modules/openapi-generator/src/main/resources/python/api.mustache b/modules/openapi-generator/src/main/resources/python/api.mustache index cbad6df2c543..37339fc51156 100644 --- a/modules/openapi-generator/src/main/resources/python/api.mustache +++ b/modules/openapi-generator/src/main/resources/python/api.mustache @@ -230,8 +230,8 @@ class {{classname}}(object): 'min_length': {{minLength}},{{/minLength}}{{#maxItems}} 'max_items': {{maxItems}},{{/maxItems}}{{#minItems}} 'min_items': {{minItems}},{{/minItems}}{{#maximum}} - {{#exclusiveMaximum}}'exclusive_maximum'{{/exclusiveMaximum}}'inclusive_maximum'{{^exclusiveMaximum}}{{/exclusiveMaximum}}: {{maximum}},{{/maximum}}{{#minimum}} - {{#exclusiveMinimum}}'exclusive_minimum'{{/exclusiveMinimum}}'inclusive_minimum'{{^exclusiveMinimum}}{{/exclusiveMinimum}}: {{minimum}},{{/minimum}}{{#pattern}} + {{#exclusiveMaximum}}'exclusive_maximum'{{/exclusiveMaximum}}{{^exclusiveMaximum}}'inclusive_maximum'{{/exclusiveMaximum}}: {{maximum}},{{/maximum}}{{#minimum}} + {{#exclusiveMinimum}}'exclusive_minimum'{{/exclusiveMinimum}}{{^exclusiveMinimum}}'inclusive_minimum'{{/exclusiveMinimum}}: {{minimum}},{{/minimum}}{{#pattern}} 'regex': { 'pattern': r'{{{vendorExtensions.x-regex}}}', # noqa: E501{{#vendorExtensions.x-modifiers}} {{#-first}}'flags': (re.{{.}}{{/-first}}{{^-first}} re.{{.}}{{/-first}}{{^-last}} | {{/-last}}{{#-last}}){{/-last}}{{/vendorExtensions.x-modifiers}} diff --git a/modules/openapi-generator/src/main/resources/python/model.mustache b/modules/openapi-generator/src/main/resources/python/model.mustache index 680b60644c0d..c8e1bfaa0042 100644 --- a/modules/openapi-generator/src/main/resources/python/model.mustache +++ b/modules/openapi-generator/src/main/resources/python/model.mustache @@ -17,6 +17,9 @@ from {{packageName}}.model_utils import ( # noqa: F401 none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from {{packageName}}.exceptions import ApiAttributeError + {{#models}} {{#model}} {{#imports}} diff --git a/modules/openapi-generator/src/main/resources/python/model_doc.mustache b/modules/openapi-generator/src/main/resources/python/model_doc.mustache index ff7358618ea5..3f7c8263df20 100644 --- a/modules/openapi-generator/src/main/resources/python/model_doc.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_doc.mustache @@ -28,9 +28,9 @@ Name | Type | Description | Notes {{#optionalVars}} **{{name}}** | {{^complexType}}**{{dataType}}**{{/complexType}}{{#complexType}}[**{{dataType}}**]({{complexType}}.md){{/complexType}} | {{description}} | [optional] {{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}} if omitted the server will use the default value of {{{.}}}{{/defaultValue}} {{/optionalVars}} -{{#additionalPropertiesType}} -**any string name** | **{{additionalPropertiesType}}** | any string name can be used but the value must be the correct type | [optional] -{{/additionalPropertiesType}} +{{#additionalProperties}} +**any string name** | {{^complexType}}**{{dataType}}**{{/complexType}}{{#complexType}}[**{{dataType}}**]({{complexType}}.md){{/complexType}} | any string name can be used but the value must be the correct type | [optional] +{{/additionalProperties}} [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/classvars.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/classvars.mustache index 88ae5df9f121..0e5ff25b97fb 100644 --- a/modules/openapi-generator/src/main/resources/python/model_templates/classvars.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_templates/classvars.mustache @@ -60,7 +60,7 @@ {{/optionalVars}} } -{{#additionalPropertiesType}} +{{#additionalProperties}} @cached_property def additional_properties_type(): """ @@ -72,11 +72,11 @@ lazy_import() {{/-first}} {{/imports}} - return ({{{additionalPropertiesType}}},) # noqa: E501 -{{/additionalPropertiesType}} -{{^additionalPropertiesType}} + return ({{{dataType}}},) # noqa: E501 +{{/additionalProperties}} +{{^additionalProperties}} additional_properties_type = None -{{/additionalPropertiesType}} +{{/additionalProperties}} _nullable = {{#isNullable}}True{{/isNullable}}{{^isNullable}}False{{/isNullable}} diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/invalid_pos_args.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/invalid_pos_args.mustache new file mode 100644 index 000000000000..143d50c8250c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/invalid_pos_args.mustache @@ -0,0 +1,9 @@ + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_composed.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_composed.mustache new file mode 100644 index 000000000000..81a4af3f822c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_composed.mustache @@ -0,0 +1,66 @@ + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """{{classname}} - a model defined in OpenAPI + + Keyword Args: +{{#requiredVars}} +{{#defaultValue}} + {{name}} ({{{dataType}}}):{{#description}} {{{description}}}.{{/description}} defaults to {{{defaultValue}}}{{#allowableValues}}, must be one of [{{#enumVars}}{{{value}}}, {{/enumVars}}]{{/allowableValues}} # noqa: E501 +{{/defaultValue}} +{{^defaultValue}} + {{name}} ({{{dataType}}}):{{#description}} {{{description}}}{{/description}} +{{/defaultValue}} +{{/requiredVars}} +{{> model_templates/docstring_init_required_kwargs }} +{{#optionalVars}} + {{name}} ({{{dataType}}}):{{#description}} {{{description}}}.{{/description}} [optional]{{#defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/defaultValue}} # noqa: E501 +{{/optionalVars}} + """ + +{{#requiredVars}} +{{#defaultValue}} + {{name}} = kwargs.get('{{name}}', {{{defaultValue}}}) +{{/defaultValue}} +{{/requiredVars}} + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + +{{> model_templates/invalid_pos_args }} + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_normal.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_normal.mustache new file mode 100644 index 000000000000..3b82ba7fc3a6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_normal.mustache @@ -0,0 +1,17 @@ +{{> model_templates/method_from_openapi_data_shared }} + +{{#isEnum}} + self.value = value +{{/isEnum}} +{{#requiredVars}} + self.{{name}} = {{name}} +{{/requiredVars}} + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_shared.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_shared.mustache new file mode 100644 index 000000000000..9dd84236b9ff --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_shared.mustache @@ -0,0 +1,49 @@ + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls{{#requiredVars}}{{^defaultValue}}, {{name}}{{/defaultValue}}{{/requiredVars}}, *args, **kwargs): # noqa: E501 + """{{classname}} - a model defined in OpenAPI + +{{#requiredVars}} +{{#-first}} + Args: +{{/-first}} +{{^defaultValue}} + {{name}} ({{{dataType}}}):{{#description}} {{{description}}}{{/description}} +{{/defaultValue}} +{{#-last}} + +{{/-last}} +{{/requiredVars}} + Keyword Args: +{{#requiredVars}} +{{#defaultValue}} + {{name}} ({{{dataType}}}):{{#description}} {{{description}}}.{{/description}} defaults to {{{defaultValue}}}{{#allowableValues}}, must be one of [{{#enumVars}}{{{value}}}, {{/enumVars}}]{{/allowableValues}} # noqa: E501 +{{/defaultValue}} +{{/requiredVars}} +{{> model_templates/docstring_init_required_kwargs }} +{{#optionalVars}} + {{name}} ({{{dataType}}}):{{#description}} {{{description}}}.{{/description}} [optional]{{#defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/defaultValue}} # noqa: E501 +{{/optionalVars}} + """ + +{{#requiredVars}} +{{#defaultValue}} + {{name}} = kwargs.get('{{name}}', {{{defaultValue}}}) +{{/defaultValue}} +{{/requiredVars}} + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + +{{> model_templates/invalid_pos_args }} + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_simple.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_simple.mustache new file mode 100644 index 000000000000..0756046ede25 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/model_templates/method_from_openapi_data_simple.mustache @@ -0,0 +1,62 @@ + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """{{classname}} - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] ({{{dataType}}}):{{#description}} {{{description}}}.{{/description}}{{#defaultValue}} if omitted defaults to {{{defaultValue}}}{{/defaultValue}}{{#allowableValues}}, must be one of [{{#enumVars}}{{{value}}}, {{/enumVars}}]{{/allowableValues}} # noqa: E501 + + Keyword Args: + value ({{{dataType}}}):{{#description}} {{{description}}}.{{/description}}{{#defaultValue}} if omitted defaults to {{{defaultValue}}}{{/defaultValue}}{{#allowableValues}}, must be one of [{{#enumVars}}{{{value}}}, {{/enumVars}}]{{/allowableValues}} # noqa: E501 +{{> model_templates/docstring_init_required_kwargs }} + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) +{{#defaultValue}} + else: + value = {{{defaultValue}}} +{{/defaultValue}} +{{^defaultValue}} + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) +{{/defaultValue}} + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + +{{> model_templates/invalid_pos_args }} + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_composed.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/method_init_composed.mustache index 9b298379710c..cc6f4b46bd71 100644 --- a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_composed.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_templates/method_init_composed.mustache @@ -10,7 +10,48 @@ '_additional_properties_model_instances', ]) -{{> model_templates/method_init_shared }} + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """{{classname}} - a model defined in OpenAPI + + Keyword Args: +{{#requiredVars}} +{{^isReadOnly}} +{{#defaultValue}} + {{name}} ({{{dataType}}}):{{#description}} {{{description}}}.{{/description}} defaults to {{{defaultValue}}}{{#allowableValues}}, must be one of [{{#enumVars}}{{{value}}}, {{/enumVars}}]{{/allowableValues}} # noqa: E501 +{{/defaultValue}} +{{^defaultValue}} + {{name}} ({{{dataType}}}):{{#description}} {{{description}}}{{/description}} +{{/defaultValue}} +{{/isReadOnly}} +{{/requiredVars}} +{{> model_templates/docstring_init_required_kwargs }} +{{#optionalVars}} + {{name}} ({{{dataType}}}):{{#description}} {{{description}}}.{{/description}} [optional]{{#defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/defaultValue}} # noqa: E501 +{{/optionalVars}} + """ + +{{#requiredVars}} +{{^isReadOnly}} +{{#defaultValue}} + {{name}} = kwargs.get('{{name}}', {{{defaultValue}}}) +{{/defaultValue}} +{{/isReadOnly}} +{{/requiredVars}} + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + +{{> model_templates/invalid_pos_args }} + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) constant_args = { '_check_type': _check_type, @@ -19,28 +60,21 @@ '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { -{{#requiredVars}} - '{{name}}': {{name}}, -{{/requiredVars}} - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue - setattr(self, var_name, var_value) \ No newline at end of file + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_normal.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/method_init_normal.mustache index e670b4ffb4c3..bc5e7686f815 100644 --- a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_normal.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_templates/method_init_normal.mustache @@ -13,7 +13,9 @@ self.value = value {{/isEnum}} {{#requiredVars}} +{{^isReadOnly}} self.{{name}} = {{name}} +{{/isReadOnly}} {{/requiredVars}} for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ @@ -22,4 +24,7 @@ self.additional_properties_type is None: # discard variable. continue - setattr(self, var_name, var_value) \ No newline at end of file + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_shared.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/method_init_shared.mustache index a766c14bac0f..0eb4de6a13e9 100644 --- a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_shared.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_templates/method_init_shared.mustache @@ -1,8 +1,9 @@ @convert_js_args_to_python_args - def __init__(self{{#requiredVars}}{{^defaultValue}}, {{name}}{{/defaultValue}}{{/requiredVars}}, *args, **kwargs): # noqa: E501 + def __init__(self{{#requiredVars}}{{^isReadOnly}}{{^defaultValue}}, {{name}}{{/defaultValue}}{{/isReadOnly}}{{/requiredVars}}, *args, **kwargs): # noqa: E501 """{{classname}} - a model defined in OpenAPI {{#requiredVars}} +{{^isReadOnly}} {{#-first}} Args: {{/-first}} @@ -12,12 +13,15 @@ {{#-last}} {{/-last}} +{{/isReadOnly}} {{/requiredVars}} Keyword Args: {{#requiredVars}} +{{^isReadOnly}} {{#defaultValue}} {{name}} ({{{dataType}}}):{{#description}} {{{description}}}.{{/description}} defaults to {{{defaultValue}}}{{#allowableValues}}, must be one of [{{#enumVars}}{{{value}}}, {{/enumVars}}]{{/allowableValues}} # noqa: E501 {{/defaultValue}} +{{/isReadOnly}} {{/requiredVars}} {{> model_templates/docstring_init_required_kwargs }} {{#optionalVars}} @@ -26,9 +30,11 @@ """ {{#requiredVars}} +{{^isReadOnly}} {{#defaultValue}} {{name}} = kwargs.get('{{name}}', {{{defaultValue}}}) {{/defaultValue}} +{{/isReadOnly}} {{/requiredVars}} _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) @@ -36,15 +42,7 @@ _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - if args: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) +{{> model_templates/invalid_pos_args }} self._data_store = {} self._check_type = _check_type diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_simple.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/method_init_simple.mustache index 9e06a6a22ed9..c6950a7d3642 100644 --- a/modules/openapi-generator/src/main/resources/python/model_templates/method_init_simple.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_templates/method_init_simple.mustache @@ -46,15 +46,7 @@ _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - if args: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) +{{> model_templates/invalid_pos_args }} self._data_store = {} self._check_type = _check_type diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/methods_setattr_getattr_composed.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/methods_setattr_getattr_composed.mustache index 6b1013ca997d..de7887ebdbda 100644 --- a/modules/openapi-generator/src/main/resources/python/model_templates/methods_setattr_getattr_composed.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_templates/methods_setattr_getattr_composed.mustache @@ -4,27 +4,43 @@ self.__dict__[name] = value return - # set the attribute on the correct instance - model_instances = self._var_name_to_model_instances.get( - name, self._additional_properties_model_instances) - if model_instances: - for model_instance in model_instances: - if model_instance == self: - self.set_attribute(name, value) - else: - setattr(model_instance, name, value) - if name not in self._var_name_to_model_instances: - # we assigned an additional property - self.__dict__['_var_name_to_model_instances'][name] = ( - model_instance - ) - return None + """ + Use cases: + 1. additional_properties_type is None (additionalProperties == False in spec) + Check for property presence in self.openapi_types + if not present then throw an error + if present set in self, set attribute + always set on composed schemas + 2. additional_properties_type exists + set attribute on self + always set on composed schemas + """ + if self.additional_properties_type is None: + """ + For an attribute to exist on a composed schema it must: + - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND + - fulfill schema_requirements in each oneOf/anyOf/allOf schemas - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) + schema_requirements: + For an attribute to exist on a schema it must: + - be present in properties at the schema OR + - have additionalProperties unset (defaults additionalProperties = any type) OR + - have additionalProperties set + """ + if name not in self.openapi_types: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + # attribute must be set on self and composed instances + self.set_attribute(name, value) + for model_instance in self._composed_instances: + setattr(model_instance, name, value) + if name not in self._var_name_to_model_instances: + # we assigned an additional property + self.__dict__['_var_name_to_model_instances'][name] = self._composed_instances + [self] + return None __unset_attribute_value__ = object() @@ -34,13 +50,12 @@ return self.__dict__[name] # get the attribute from the correct instance - model_instances = self._var_name_to_model_instances.get( - name, self._additional_properties_model_instances) + model_instances = self._var_name_to_model_instances.get(name) values = [] - # A composed model stores child (oneof/anyOf/allOf) models under - # self._var_name_to_model_instances. A named property can exist in - # multiple child models. If the property is present in more than one - # child model, the value must be the same across all the child models. + # A composed model stores self and child (oneof/anyOf/allOf) models under + # self._var_name_to_model_instances. + # Any property must exist in self and all model instances + # The value stored in all model instances must be the same if model_instances: for model_instance in model_instances: if name in model_instance._data_store: diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/model_composed.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/model_composed.mustache index 76fe3a8f5074..9a5ab0f66b6b 100644 --- a/modules/openapi-generator/src/main/resources/python/model_templates/model_composed.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_templates/model_composed.mustache @@ -24,6 +24,21 @@ class {{classname}}(ModelComposed): {{/optionalVars}} } + read_only_vars = { +{{#requiredVars}} +{{#isReadOnly}} + '{{name}}', # noqa: E501 +{{/isReadOnly}} +{{/requiredVars}} +{{#optionalVars}} +{{#isReadOnly}} + '{{name}}', # noqa: E501 +{{/isReadOnly}} +{{/optionalVars}} + } + +{{> model_templates/method_from_openapi_data_composed }} + {{> model_templates/method_init_composed }} @cached_property diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/model_normal.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/model_normal.mustache index 9aada8f5a08b..513aa01e66e1 100644 --- a/modules/openapi-generator/src/main/resources/python/model_templates/model_normal.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_templates/model_normal.mustache @@ -24,6 +24,21 @@ class {{classname}}(ModelNormal): {{/optionalVars}} } + read_only_vars = { +{{#requiredVars}} +{{#isReadOnly}} + '{{name}}', # noqa: E501 +{{/isReadOnly}} +{{/requiredVars}} +{{#optionalVars}} +{{#isReadOnly}} + '{{name}}', # noqa: E501 +{{/isReadOnly}} +{{/optionalVars}} + } + _composed_schemas = {} +{{> model_templates/method_from_openapi_data_normal}} + {{> model_templates/method_init_normal}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_templates/model_simple.mustache b/modules/openapi-generator/src/main/resources/python/model_templates/model_simple.mustache index a4055af756be..1a41a9cf7e27 100644 --- a/modules/openapi-generator/src/main/resources/python/model_templates/model_simple.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_templates/model_simple.mustache @@ -13,6 +13,10 @@ class {{classname}}(ModelSimple): attribute_map = {} + read_only_vars = set() + _composed_schemas = None -{{> model_templates/method_init_simple}} \ No newline at end of file +{{> model_templates/method_init_simple}} + +{{> model_templates/method_from_openapi_data_simple}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/model_utils.mustache b/modules/openapi-generator/src/main/resources/python/model_utils.mustache index fb60afb60d6f..c7944e4fdcf5 100644 --- a/modules/openapi-generator/src/main/resources/python/model_utils.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_utils.mustache @@ -21,6 +21,22 @@ none_type = type(None) file_type = io.IOBase +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(_self, *args, **kwargs): + """ + An attribute named `self` received from the api will conflicts with the reserved `self` + parameter of a class method. During generation, `self` attributes are mapped + to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. + """ + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python(kwargs, _self if isinstance(_self, type) else _self.__class__) + return fn(_self, *args, **kwargs) + return wrapped_init + + class cached_property(object): # this caches the result of the function call for fn with no inputs # use this as a decorator on fuction methods that you want converted @@ -212,6 +228,121 @@ class OpenApiModel(object): return new_inst + @classmethod + @convert_js_args_to_python_args + def _new_from_openapi_data(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return cls._from_openapi_data(*args, **kwargs) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return cls._from_openapi_data(*args, **kwargs) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = cls._from_openapi_data(*args, **kwargs) + + + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + return new_inst + + class ModelSimple(OpenApiModel): """the parent class of models whose type != object in their swagger/openapi""" @@ -911,14 +1042,14 @@ def deserialize_model(model_data, model_class, path_to_item, check_type, _spec_property_naming=spec_property_naming) if issubclass(model_class, ModelSimple): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) elif isinstance(model_data, list): - return model_class(*model_data, **kw_args) + return model_class._new_from_openapi_data(*model_data, **kw_args) if isinstance(model_data, dict): kw_args.update(model_data) - return model_class(**kw_args) + return model_class._new_from_openapi_data(**kw_args) elif isinstance(model_data, PRIMITIVE_TYPES): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) def deserialize_file(response_data, configuration, content_disposition=None): @@ -1204,12 +1335,20 @@ def model_to_dict(model_instance, serialize=True): model_instances = [model_instance] if model_instance._composed_schemas: model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} for model_instance in model_instances: for attr, value in model_instance._data_store.items(): if serialize: # we use get here because additional property key names do not # exist in attribute_map - attr = model_instance.attribute_map.get(attr, attr) + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) if isinstance(value, list): if not value: # empty list or None @@ -1237,6 +1376,16 @@ def model_to_dict(model_instance, serialize=True): result[attr] = model_to_dict(value, serialize=serialize) else: result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] return result @@ -1280,30 +1429,19 @@ def get_valid_classes_phrase(input_classes): return "is one of [{0}]".format(", ".join(all_class_names)) -def convert_js_args_to_python_args(fn): - from functools import wraps - @wraps(fn) - def wrapped_init(_self, *args, **kwargs): - """ - An attribute named `self` received from the api will conflicts with the reserved `self` - parameter of a class method. During generation, `self` attributes are mapped - to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. - """ - spec_property_naming = kwargs.get('_spec_property_naming', False) - if spec_property_naming: - kwargs = change_keys_js_to_python(kwargs, _self.__class__) - return fn(_self, *args, **kwargs) - return wrapped_init - - def get_allof_instances(self, model_args, constant_args): """ Args: self: the class we are handling model_args (dict): var_name to var_value used to make instances - constant_args (dict): var_name to var_value - used to make instances + constant_args (dict): + metadata arguments: + _check_type + _path_to_item + _spec_property_naming + _configuration + _visited_composed_classes Returns composed_instances (list) @@ -1311,20 +1449,8 @@ def get_allof_instances(self, model_args, constant_args): composed_instances = [] for allof_class in self._composed_schemas['allOf']: - # no need to handle changing js keys to python because - # for composed schemas, allof parameters are included in the - # composed schema and were changed to python keys in __new__ - # extract a dict of only required keys from fixed_model_args - kwargs = {} - var_names = set(allof_class.openapi_types.keys()) - for var_name in var_names: - if var_name in model_args: - kwargs[var_name] = model_args[var_name] - - # and use it to make the instance - kwargs.update(constant_args) try: - allof_instance = allof_class(**kwargs) + allof_instance = allof_class(**model_args, **constant_args) composed_instances.append(allof_instance) except Exception as ex: raise ApiValueError( @@ -1384,31 +1510,9 @@ def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): single_value_input = allows_single_value_input(oneof_class) - if not single_value_input: - # transform js keys from input data to python keys in fixed_model_args - fixed_model_args = change_keys_js_to_python( - model_kwargs, oneof_class) - - # Extract a dict with the properties that are declared in the oneOf schema. - # Undeclared properties (e.g. properties that are allowed because of the - # additionalProperties attribute in the OAS document) are not added to - # the dict. - kwargs = {} - var_names = set(oneof_class.openapi_types.keys()) - for var_name in var_names: - if var_name in fixed_model_args: - kwargs[var_name] = fixed_model_args[var_name] - - # do not try to make a model with no input args - if len(kwargs) == 0: - continue - - # and use it to make the instance - kwargs.update(constant_kwargs) - try: if not single_value_input: - oneof_instance = oneof_class(**kwargs) + oneof_instance = oneof_class(**model_kwargs, **constant_kwargs) else: if issubclass(oneof_class, ModelSimple): oneof_instance = oneof_class(model_arg, **constant_kwargs) @@ -1465,24 +1569,8 @@ def get_anyof_instances(self, model_args, constant_args): # none_type deserialization is handled in the __new__ method continue - # transform js keys to python keys in fixed_model_args - fixed_model_args = change_keys_js_to_python(model_args, anyof_class) - - # extract a dict of only required keys from these_model_vars - kwargs = {} - var_names = set(anyof_class.openapi_types.keys()) - for var_name in var_names: - if var_name in fixed_model_args: - kwargs[var_name] = fixed_model_args[var_name] - - # do not try to make a model with no input args - if len(kwargs) == 0: - continue - - # and use it to make the instance - kwargs.update(constant_args) try: - anyof_instance = anyof_class(**kwargs) + anyof_instance = anyof_class(**model_args, **constant_args) anyof_instances.append(anyof_instance) except Exception: pass @@ -1495,47 +1583,34 @@ def get_anyof_instances(self, model_args, constant_args): return anyof_instances -def get_additional_properties_model_instances( - composed_instances, self): - additional_properties_model_instances = [] - all_instances = [self] - all_instances.extend(composed_instances) - for instance in all_instances: - if instance.additional_properties_type is not None: - additional_properties_model_instances.append(instance) - return additional_properties_model_instances - - -def get_var_name_to_model_instances(self, composed_instances): - var_name_to_model_instances = {} - all_instances = [self] - all_instances.extend(composed_instances) - for instance in all_instances: - for var_name in instance.openapi_types: - if var_name not in var_name_to_model_instances: - var_name_to_model_instances[var_name] = [instance] - else: - var_name_to_model_instances[var_name].append(instance) - return var_name_to_model_instances - - -def get_unused_args(self, composed_instances, model_args): - unused_args = dict(model_args) - # arguments apssed to self were already converted to python names +def get_discarded_args(self, composed_instances, model_args): + """ + Gathers the args that were discarded by configuration.discard_unknown_keys + """ + model_arg_keys = model_args.keys() + discarded_args = set() + # arguments passed to self were already converted to python names # before __init__ was called - for var_name_py in self.attribute_map: - if var_name_py in unused_args: - del unused_args[var_name_py] for instance in composed_instances: if instance.__class__ in self._composed_schemas['allOf']: - for var_name_py in instance.attribute_map: - if var_name_py in unused_args: - del unused_args[var_name_py] + try: + keys = instance.to_dict().keys() + discarded_keys = model_args - keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass else: - for var_name_js in instance.attribute_map.values(): - if var_name_js in unused_args: - del unused_args[var_name_js] - return unused_args + try: + all_keys = set(model_to_dict(instance, serialize=False).keys()) + js_keys = model_to_dict(instance, serialize=True).keys() + all_keys.update(js_keys) + discarded_keys = model_arg_keys - all_keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass + return discarded_args def validate_get_composed_info(constant_args, model_args, self): @@ -1579,36 +1654,42 @@ def validate_get_composed_info(constant_args, model_args, self): composed_instances.append(oneof_instance) anyof_instances = get_anyof_instances(self, model_args, constant_args) composed_instances.extend(anyof_instances) + """ + set additional_properties_model_instances + additional properties must be evaluated at the schema level + so self's additional properties are most important + If self is a composed schema with: + - no properties defined in self + - additionalProperties: False + Then for object payloads every property is an additional property + and they are not allowed, so only empty dict is allowed + + Properties must be set on all matching schemas + so when a property is assigned toa composed instance, it must be set on all + composed instances regardless of additionalProperties presence + keeping it to prevent breaking changes in v5.0.1 + TODO remove cls._additional_properties_model_instances in 6.0.0 + """ + additional_properties_model_instances = [] + if self.additional_properties_type is not None: + additional_properties_model_instances = [self] - # map variable names to composed_instances - var_name_to_model_instances = get_var_name_to_model_instances( - self, composed_instances) - - # set additional_properties_model_instances - additional_properties_model_instances = ( - get_additional_properties_model_instances(composed_instances, self) - ) - - # set any remaining values - unused_args = get_unused_args(self, composed_instances, model_args) - if len(unused_args) > 0 and \ - len(additional_properties_model_instances) == 0 and \ - (self._configuration is None or - not self._configuration.discard_unknown_keys): - raise ApiValueError( - "Invalid input arguments input when making an instance of " - "class %s. Not all inputs were used. The unused input data " - "is %s" % (self.__class__.__name__, unused_args) - ) + """ + no need to set properties on self in here, they will be set in __init__ + By here all composed schema oneOf/anyOf/allOf instances have their properties set using + model_args + """ + discarded_args = get_discarded_args(self, composed_instances, model_args) - # no need to add additional_properties to var_name_to_model_instances here - # because additional_properties_model_instances will direct us to that - # instance when we use getattr or setattr - # and we update var_name_to_model_instances in setattr + # map variable names to composed_instances + var_name_to_model_instances = {} + for prop_name in model_args: + if prop_name not in discarded_args: + var_name_to_model_instances[prop_name] = [self] + composed_instances return [ composed_instances, var_name_to_model_instances, additional_properties_model_instances, - unused_args + discarded_args ] diff --git a/modules/openapi-generator/src/main/resources/r/model.mustache b/modules/openapi-generator/src/main/resources/r/model.mustache index 1b853ec37302..28b7ce9145b1 100644 --- a/modules/openapi-generator/src/main/resources/r/model.mustache +++ b/modules/openapi-generator/src/main/resources/r/model.mustache @@ -47,6 +47,9 @@ {{#isString}} stopifnot(is.character(`{{baseName}}`), length(`{{baseName}}`) == 1) {{/isString}} + {{#isBoolean}} + stopifnot(is.logical(`{{baseName}}`), length(`{{baseName}}`) == 1) + {{/isBoolean}} {{#isDate}} stopifnot(is.character(`{{baseName}}`), length(`{{baseName}}`) == 1) {{/isDate}} @@ -88,6 +91,9 @@ {{#isString}} stopifnot(is.character(`{{baseName}}`), length(`{{baseName}}`) == 1) {{/isString}} + {{#isBoolean}} + stopifnot(is.logical(`{{baseName}}`), length(`{{baseName}}`) == 1) + {{/isBoolean}} {{#isDate}} stopifnot(is.character(`{{baseName}}`), length(`{{baseName}}`) == 1) {{/isDate}} @@ -185,7 +191,7 @@ {{/isArray}} {{#isMap}} {{#isPrimitiveType}} - {{#isNumeric}}%d{{/isNumeric}}{{^isNumeric}}"%s"{{/isNumeric}} + {{#isNumeric}}%d{{/isNumeric}}{{^isNumeric}}{{^isBoolean}}"{{/isBoolean}}%s{{^isBoolean}}"{{/isBoolean}}{{/isNumeric}} {{/isPrimitiveType}} {{^isPrimitiveType}}%s {{/isPrimitiveType}} @@ -193,7 +199,7 @@ {{/isContainer}} {{^isContainer}} {{#isPrimitiveType}} - {{#isNumeric}}%d{{/isNumeric}}{{^isNumeric}}"%s"{{/isNumeric}} + {{#isNumeric}}%d{{/isNumeric}}{{^isNumeric}}{{^isBoolean}}"{{/isBoolean}}%s{{^isBoolean}}"{{/isBoolean}}{{/isNumeric}} {{/isPrimitiveType}} {{^isPrimitiveType}}%s {{/isPrimitiveType}} @@ -218,7 +224,7 @@ {{/isContainer}} {{^isContainer}} {{#isPrimitiveType}} - self$`{{baseName}}` + {{#isBoolean}}tolower({{/isBoolean}}self$`{{baseName}}`{{#isBoolean}}){{/isBoolean}} {{/isPrimitiveType}} {{^isPrimitiveType}} jsonlite::toJSON(self$`{{baseName}}`$toJSON(), auto_unbox=TRUE, digits = NA) @@ -253,4 +259,3 @@ {{/isEnum}} {{/model}} {{/models}} - diff --git a/modules/openapi-generator/src/main/resources/ruby-sinatra-server/Dockerfile b/modules/openapi-generator/src/main/resources/ruby-sinatra-server/Dockerfile new file mode 100644 index 000000000000..41be83d48ece --- /dev/null +++ b/modules/openapi-generator/src/main/resources/ruby-sinatra-server/Dockerfile @@ -0,0 +1,32 @@ +## Build libraries +FROM ruby:3.0-alpine as rubydev + +## for thin or falcon +#RUN apk --no-cache add make g++ libc-dev +## for puma +#RUN apk --no-cache add make gcc libc-dev + +ADD . /app +WORKDIR /app + +RUN bundle config set path lib +RUN bundle install + +## Build Runtime image +FROM ruby:3.0-alpine + +RUN apk --no-cache add tzdata ## ca-certificates + +COPY --from=rubydev /app /app +WORKDIR /app + +ENV SINATRA_HOST 0.0.0.0 +ENV SINATRA_PORT 8080 +EXPOSE $SINATRA_PORT + +RUN addgroup sinatra +RUN adduser -S -G sinatra sinatra +USER sinatra +RUN bundle config set path lib + +CMD bundle exec rackup --host $SINATRA_HOST -p $SINATRA_PORT diff --git a/modules/openapi-generator/src/main/resources/ruby-sinatra-server/Gemfile b/modules/openapi-generator/src/main/resources/ruby-sinatra-server/Gemfile index be9c3168ea6f..90d7b0e3bcdc 100644 --- a/modules/openapi-generator/src/main/resources/ruby-sinatra-server/Gemfile +++ b/modules/openapi-generator/src/main/resources/ruby-sinatra-server/Gemfile @@ -1,4 +1,5 @@ source 'https://rubygems.org' +gem "webrick" gem "sinatra" -gem "sinatra-cross_origin" \ No newline at end of file +gem "sinatra-cross_origin" diff --git a/modules/openapi-generator/src/main/resources/ruby-sinatra-server/README.md b/modules/openapi-generator/src/main/resources/ruby-sinatra-server/README.md index bf132cb042a2..aecb705a1946 100644 --- a/modules/openapi-generator/src/main/resources/ruby-sinatra-server/README.md +++ b/modules/openapi-generator/src/main/resources/ruby-sinatra-server/README.md @@ -1,4 +1,4 @@ -# Swagger for Sinatra +# OpenAPI for Sinatra ## Overview This is a project to provide Swagger support inside the [Sinatra](http://www.sinatrarb.com/) framework. You can find @@ -6,24 +6,60 @@ out more about both the spec and the framework at http://swagger.io. For more i Wordnik's APIs, please visit http://developer.wordnik.com. ## Prerequisites -You need to install ruby 1.9.3 and the following gems: +As of ruby 3.0.0, the webrick web server library was removed. +You need to install a rack-supported web server, such as webrick and thin. + +The default Gemfile is as follows. +Update the name of the web server as your prefer. ``` -sinatra -sinatra-cross_origin +source 'https://rubygems.org' + +gem "webrick" +gem "sinatra" +gem "sinatra-cross_origin" ``` ## Getting started -This sample was generated with the [OpenAPI Generator](https://github.com/openapitools/openapi-generator) project. +To generate a ruby-sinatra server for petstore.yaml, please run the following: + +``` +openapi-generator-cli generate \ + -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml \ + -g ruby-sinatra -o code +``` + +To run the generated server, please run the following: + +``` +cd code/ +bundle config set path lib +bundle install +bundle exec rackup -p 8080 +``` + +You can access the application by the following URL: + +``` +http://localhost:8080/v2/store/inventory +``` + +## Docker +If you want to use a web server other than webrick, you need to edit the generated Dockerfile to prepare the compiler and the make command. Please check the comment of the Dockerfile. + +To run the code on docker, you can use the Dockerfile as follows: + +### Build the docker image +The "container_name" can be changed for your preferences. ``` -rackup -p 4567 config.ru +docker build . --tag "container_name" ``` -In your [swagger ui](https://github.com/swagger-api/swagger-ui), put in the following URL: +### Run the docker image ``` -http://localhost:4567/resources.json +docker run -it --rm -p 8080:8080 "container_name" ``` Voila! diff --git a/modules/openapi-generator/src/main/resources/scala-akka-client/apiInvoker.mustache b/modules/openapi-generator/src/main/resources/scala-akka-client/apiInvoker.mustache index 8c81b0b2d8b5..a82135170c43 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-client/apiInvoker.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-client/apiInvoker.mustache @@ -18,6 +18,7 @@ import de.heikoseeberger.akkahttpjson4s.Json4sSupport import org.json4s._ import org.json4s.jackson.JsonMethods._ import org.json4s.jackson.Serialization +import scala.collection.compat._ import scala.collection.immutable import scala.concurrent.{ ExecutionContext, ExecutionContextExecutor, Future } @@ -86,7 +87,7 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC private val http = Http() - val CompressionFilter: HttpMessage ⇒ Boolean = (msg: HttpMessage) => + val CompressionFilter: HttpMessage => Boolean = (msg: HttpMessage) => Seq( { _: HttpMessage => settings.compressionEnabled }, Encoder.DefaultFilter, @@ -115,7 +116,7 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC private def headers(headers: Map[String, Any]): immutable.Seq[HttpHeader] = headers.asFormattedParams .map { case (name, value) => RawHeader(name, value.toString) } - .to[immutable.Seq] + .to(immutable.Seq) private def bodyPart(name: String, value: Any): BodyPart = { @@ -147,9 +148,9 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC case MediaTypes.`multipart/form-data` => Multipart.FormData(Source(params.toList.map { case (name, value) => bodyPart(name, value) })) case MediaTypes.`application/x-www-form-urlencoded` => - FormData(params.mapValues(_.toString)) + FormData(params.view.mapValues(_.toString).toMap) case _: MediaType => // Default : application/x-www-form-urlencoded. - FormData(params.mapValues(_.toString)) + FormData(params.view.mapValues(_.toString).toMap) } ) } @@ -187,7 +188,9 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC params + (keyName -> key.value) case (params, _) => params }.asFormattedParams + .view .mapValues(_.toString) + .toMap .foldRight[Query](Uri.Query.Empty) { case ((name, value), acc) => acc.+:(name, value) } @@ -196,7 +199,9 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC def makeUri(r: ApiRequest[_]): Uri = { val opPath = r.operationPath.replaceAll("\\{format\\}", "json") val opPathWithParams = r.pathParams.asFormattedParams + .view .mapValues(_.toString) + .toMap .foldLeft(opPath) { case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value) } @@ -213,13 +218,13 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC http .singleRequest(request) .map { response => - val decoder: Coder with StreamDecoder = response.encoding match { - case HttpEncodings.gzip ⇒ - Gzip - case HttpEncodings.deflate ⇒ - Deflate - case HttpEncodings.identity ⇒ - NoCoding + val decoder: Decoder with Decoder = response.encoding match { + case HttpEncodings.gzip => + Coders.Gzip + case HttpEncodings.deflate => + Coders.Deflate + case HttpEncodings.identity => + Coders.NoCoding case HttpEncoding(encoding) => throw new IllegalArgumentException(s"Unsupported encoding: $encoding") } @@ -247,13 +252,13 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC request .responseForCode(response.status.intValue) match { case Some((Manifest.Unit, state: ResponseState)) => - Future(responseForState(state, Unit).asInstanceOf[ApiResponse[T]]) + Future(responseForState(state, ()).asInstanceOf[ApiResponse[T]]) case Some((manifest, state: ResponseState)) if manifest == mf => implicit val m: Unmarshaller[HttpEntity, T] = unmarshaller[T](mf, serialization, formats) Unmarshal(response.entity) .to[T] .recoverWith { - case e ⇒ throw ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), e) + case e => throw ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), e) } .map(value => responseForState(state, value)) case None | Some(_) => diff --git a/modules/openapi-generator/src/main/resources/scala-akka-client/apiSettings.mustache b/modules/openapi-generator/src/main/resources/scala-akka-client/apiSettings.mustache index d5856ccc17d1..22f56080b01c 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-client/apiSettings.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-client/apiSettings.mustache @@ -3,12 +3,12 @@ package {{invokerPackage}} import java.util.concurrent.TimeUnit -import akka.actor.{ ExtendedActorSystem, Extension, ExtensionKey } +import akka.actor.{ActorSystem, ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider} import akka.http.scaladsl.model.StatusCodes.CustomStatusCode import akka.http.scaladsl.model.headers.RawHeader import com.typesafe.config.Config -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import scala.concurrent.duration.FiniteDuration class ApiSettings(config: Config) extends Extension { @@ -32,4 +32,13 @@ class ApiSettings(config: Config) extends Extension { } } -object ApiSettings extends ExtensionKey[ApiSettings] +object ApiSettings extends ExtensionId[ApiSettings] with ExtensionIdProvider { + + override def lookup = ApiSettings + + override def createExtension(system: ExtendedActorSystem): ApiSettings = + new ApiSettings(system) + + // needed to get the type right when used from Java + override def get(system: ActorSystem): ApiSettings = super.get(system) +} diff --git a/modules/openapi-generator/src/main/resources/scala-akka-client/build.sbt.mustache b/modules/openapi-generator/src/main/resources/scala-akka-client/build.sbt.mustache index c26dae841c7b..e4c21c19d0c0 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-client/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-client/build.sbt.mustache @@ -1,22 +1,26 @@ version := "{{artifactVersion}}" name := "{{artifactId}}" organization := "{{groupId}}" -scalaVersion := "2.12.8" + +scalaVersion := "2.12.13" +crossScalaVersions := Seq(scalaVersion.value, "2.13.4") + libraryDependencies ++= Seq( - "com.typesafe" % "config" % "1.3.3", - "com.typesafe.akka" %% "akka-actor" % "2.5.21", - "com.typesafe.akka" %% "akka-stream" % "2.5.21", - "com.typesafe.akka" %% "akka-http" % "10.1.7", + "com.typesafe" % "config" % "1.4.1", + "com.typesafe.akka" %% "akka-actor" % "2.6.12", + "com.typesafe.akka" %% "akka-stream" % "2.6.12", + "com.typesafe.akka" %% "akka-http" % "10.2.3", {{#joda}} "joda-time" % "joda-time" % "2.10.1", {{/joda}} - "org.json4s" %% "json4s-jackson" % "3.6.5", - "org.json4s" %% "json4s-ext" % "3.6.5", - "de.heikoseeberger" %% "akka-http-json4s" % "1.25.2", + "org.json4s" %% "json4s-jackson" % "3.6.7", + "org.json4s" %% "json4s-ext" % "3.6.7", + "de.heikoseeberger" %% "akka-http-json4s" % "1.27.0", + "org.scala-lang.modules" %% "scala-collection-compat" % "2.4.1", // test dependencies - "org.scalatest" %% "scalatest" % "3.0.5" % "test", - "junit" % "junit" % "4.13.1" % "test" + "org.scalatest" %% "scalatest" % "3.2.3" % "test", + "org.scalatestplus" %% "junit-4-13" % "3.2.3.0" % "test" ) resolvers ++= Seq(Resolver.mavenLocal) diff --git a/modules/openapi-generator/src/main/resources/scala-akka-client/pom.mustache b/modules/openapi-generator/src/main/resources/scala-akka-client/pom.mustache index 78cbec12128a..e82df0c17b9a 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-client/pom.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-client/pom.mustache @@ -15,18 +15,19 @@ UTF-8 1.8 - 2.12.8 - 3.5.3 - 3.2.11 - 2.5.21 - 10.1.7 + 2.12.13 + 3.6.7 + 3.6.7 + 2.6.12 + 10.2.3 {{#joda}} 2.10.1 {{/joda}} - 1.3.3 - 1.25.2 - 4.13.1 - 3.0.5 + 1.4.1 + 1.27.0 + 2.4.1 + 3.2.3 + 3.2.3.0 3.3.1 @@ -80,6 +81,11 @@ akka-http-json4s_2.12 ${akka.http.json4s.version} + + org.scala-lang.modules + scala-collection-compat_2.12 + ${scala.compat.version} + @@ -89,9 +95,9 @@ test - junit - junit - ${junit.version} + org.scalatestplus + junit-4-13_2.12 + ${scala.test.plus.version} test diff --git a/modules/openapi-generator/src/main/resources/scala-akka-client/project/build.properties.mustache b/modules/openapi-generator/src/main/resources/scala-akka-client/project/build.properties.mustache new file mode 100644 index 000000000000..dc07aed85e00 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-akka-client/project/build.properties.mustache @@ -0,0 +1 @@ +sbt.version=1.3.10 \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-akka-http-server/multipartDirectives.mustache b/modules/openapi-generator/src/main/resources/scala-akka-http-server/multipartDirectives.mustache index 98a2186fd2e7..6e802204c57d 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-http-server/multipartDirectives.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-http-server/multipartDirectives.mustache @@ -1,6 +1,7 @@ package {{invokerPackage}} import java.io.File +import java.nio.file.Files import akka.annotation.ApiMayChange import akka.http.scaladsl.model.Multipart.FormData @@ -69,7 +70,7 @@ trait MultipartDirectives { object MultipartDirectives extends MultipartDirectives with FileUploadDirectives { val tempFileFromFileInfo: FileInfo => File = { - file: FileInfo => File.createTempFile(file.fileName, ".tmp") + file: FileInfo => Files.createTempFile(file.fileName, ".tmp").toFile() } } diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/api.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/api.mustache index fa99fc624755..28cf170922d3 100644 --- a/modules/openapi-generator/src/main/resources/scala-sttp/api.mustache +++ b/modules/openapi-generator/src/main/resources/scala-sttp/api.mustache @@ -30,7 +30,7 @@ class {{classname}}(baseUrl: String) { .header("{{keyParamName}}", apiKey){{/isKeyInHeader}}{{#isKeyInCookie}} .cookie("{{keyParamName}}", apiKey){{/isKeyInCookie}}{{/isApiKey}}{{/authMethods}}{{#formParams.0}}{{^isMultipart}} .body(Map({{#formParams}} - {{>paramFormCreation}}{{^-last}}, {{/-last}}{{/formParams}} + {{>paramFormCreation}}{{^-last}},{{/-last}}{{/formParams}} )){{/isMultipart}}{{#isMultipart}} .multipartBody(Seq({{#formParams}} {{>paramMultipartCreation}}{{^-last}}, {{/-last}}{{/formParams}} diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/build.sbt.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/build.sbt.mustache index a20ba532f446..3072a54368c3 100644 --- a/modules/openapi-generator/src/main/resources/scala-sttp/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/scala-sttp/build.sbt.mustache @@ -2,8 +2,8 @@ version := "{{artifactVersion}}" name := "{{artifactId}}" organization := "{{groupId}}" -scalaVersion := "2.13.2" -crossScalaVersions := Seq(scalaVersion.value, "2.12.10") +scalaVersion := "2.13.5" +crossScalaVersions := Seq(scalaVersion.value, "2.12.13") libraryDependencies ++= Seq( "com.softwaremill.sttp.client" %% "core" % "{{sttpClientVersion}}", diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/project/build.properties.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/project/build.properties.mustache index 654fe70c42c7..e67343ae796c 100644 --- a/modules/openapi-generator/src/main/resources/scala-sttp/project/build.properties.mustache +++ b/modules/openapi-generator/src/main/resources/scala-sttp/project/build.properties.mustache @@ -1 +1 @@ -sbt.version=1.3.12 +sbt.version=1.5.0 diff --git a/modules/openapi-generator/src/main/resources/swift5/APIs.mustache b/modules/openapi-generator/src/main/resources/swift5/APIs.mustache index 42bdf74007f1..b05f06301797 100644 --- a/modules/openapi-generator/src/main/resources/swift5/APIs.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/APIs.mustache @@ -6,7 +6,10 @@ import Foundation -{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class {{projectName}}API { +@available(*, deprecated, renamed: "{{projectName}}") +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} typealias {{projectName}}API = {{projectName}} + +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class {{projectName}} { {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var basePath = "{{{basePath}}}" {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var credential: URLCredential? {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var customHeaders: [String: String] = [:]{{#useAlamofire}} @@ -33,7 +36,7 @@ import Foundation self.parameters = parameters self.headers = headers - addHeaders({{projectName}}API.customHeaders) + addHeaders({{projectName}}.customHeaders) } {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func addHeaders(_ aHeaders: [String: String]) { @@ -42,7 +45,7 @@ import Foundation } } - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -52,7 +55,7 @@ import Foundation } {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func addCredential() -> Self { - credential = {{projectName}}API.credential + credential = {{projectName}}.credential return self } } diff --git a/modules/openapi-generator/src/main/resources/swift5/Cartfile.mustache b/modules/openapi-generator/src/main/resources/swift5/Cartfile.mustache index 3f6269c23ab9..5dbbc4577207 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Cartfile.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Cartfile.mustache @@ -1,3 +1,4 @@ {{#useAlamofire}}github "Alamofire/Alamofire" ~> 4.9.1{{/useAlamofire}}{{#usePromiseKit}} -github "mxcl/PromiseKit" ~> 6.13.1{{/usePromiseKit}}{{#useRxSwift}} -github "ReactiveX/RxSwift" ~> 5.1.1{{/useRxSwift}} +github "mxcl/PromiseKit" ~> 6.15.3{{/usePromiseKit}}{{#useRxSwift}} +github "ReactiveX/RxSwift" ~> 6.2.0{{/useRxSwift}} +github "Flight-School/AnyCodable" ~> 0.6.0 diff --git a/modules/openapi-generator/src/main/resources/swift5/Configuration.mustache b/modules/openapi-generator/src/main/resources/swift5/Configuration.mustache index 78f54279711d..a154850602e5 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Configuration.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Configuration.mustache @@ -6,9 +6,18 @@ import Foundation +{{#swiftUseApiNamespace}} +@available(*, deprecated, renamed: "{{projectName}}.Configuration") +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} typealias Configuration = {{projectName}}.Configuration + +extension {{projectName}} { +{{/swiftUseApiNamespace}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class Configuration { // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" } +{{#swiftUseApiNamespace}} +} +{{/swiftUseApiNamespace}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache b/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache index 1a23697a04b9..a4d5dd4b3058 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache @@ -4,7 +4,10 @@ // https://openapi-generator.tech // -import Foundation{{#usePromiseKit}} +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif{{#usePromiseKit}} import PromiseKit{{/usePromiseKit}} extension Bool: JSONEncodable { @@ -53,6 +56,12 @@ extension Array: JSONEncodable { } } +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + extension Dictionary: JSONEncodable { func encodeToJSON() -> Any { var dictionary = [AnyHashable: Any]() @@ -85,7 +94,7 @@ extension UUID: JSONEncodable { func encodeToJSON() -> Any { return self.uuidString } -} +}{{#generateModelAdditionalProperties}} extension String: CodingKey { @@ -171,7 +180,7 @@ extension KeyedDecodingContainerProtocol { return map } -} +}{{/generateModelAdditionalProperties}} extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { diff --git a/modules/openapi-generator/src/main/resources/swift5/Package.swift.mustache b/modules/openapi-generator/src/main/resources/swift5/Package.swift.mustache index d173f21077b2..5dc55ffef832 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Package.swift.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Package.swift.mustache @@ -1,4 +1,4 @@ -// swift-tools-version:5.0 +// swift-tools-version:5.1 import PackageDescription @@ -19,14 +19,15 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.6.0")), {{#useAlamofire}} .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.1"), {{/useAlamofire}} {{#usePromiseKit}} - .package(url: "https://github.com/mxcl/PromiseKit.git", from: "6.12.0"), + .package(url: "https://github.com/mxcl/PromiseKit.git", from: "6.15.3"), {{/usePromiseKit}} {{#useRxSwift}} - .package(url: "https://github.com/ReactiveX/RxSwift.git", from: "5.0.0"), + .package(url: "https://github.com/ReactiveX/RxSwift.git", from: "6.2.0"), {{/useRxSwift}} ], targets: [ @@ -34,8 +35,8 @@ let package = Package( // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "{{projectName}}", - dependencies: [{{#useAlamofire}}"Alamofire", {{/useAlamofire}}{{#usePromiseKit}}"PromiseKit", {{/usePromiseKit}}{{#useRxSwift}}"RxSwift"{{/useRxSwift}}], - path: "{{projectName}}/Classes" + dependencies: ["AnyCodable", {{#useAlamofire}}"Alamofire", {{/useAlamofire}}{{#usePromiseKit}}"PromiseKit", {{/usePromiseKit}}{{#useRxSwift}}"RxSwift"{{/useRxSwift}}], + path: "{{#swiftPackagePath}}{{swiftPackagePath}}{{/swiftPackagePath}}{{^swiftPackagePath}}{{#useSPMFileStructure}}Sources/{{projectName}}{{/useSPMFileStructure}}{{^useSPMFileStructure}}{{projectName}}/Classes{{/useSPMFileStructure}}{{/swiftPackagePath}}" ), ] ) diff --git a/modules/openapi-generator/src/main/resources/swift5/Podspec.mustache b/modules/openapi-generator/src/main/resources/swift5/Podspec.mustache index c0539662ce75..7ad13354aac2 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Podspec.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Podspec.mustache @@ -25,14 +25,15 @@ Pod::Spec.new do |s| {{#podDocumentationURL}} s.documentation_url = '{{podDocumentationURL}}' {{/podDocumentationURL}} - s.source_files = '{{projectName}}/Classes/**/*.swift' + s.source_files = '{{#swiftPackagePath}}{{swiftPackagePath}}{{/swiftPackagePath}}{{^swiftPackagePath}}{{#useSPMFileStructure}}Sources/{{projectName}}{{/useSPMFileStructure}}{{^useSPMFileStructure}}{{projectName}}/Classes{{/useSPMFileStructure}}{{/swiftPackagePath}}/**/*.swift' {{#usePromiseKit}} - s.dependency 'PromiseKit/CorePromise', '~> 6.13.1' + s.dependency 'PromiseKit/CorePromise', '~> 6.15.3' {{/usePromiseKit}} {{#useRxSwift}} - s.dependency 'RxSwift', '~> 5.1.1' + s.dependency 'RxSwift', '~> 6.2.0' {{/useRxSwift}} {{#useAlamofire}} s.dependency 'Alamofire', '~> 4.9.1' {{/useAlamofire}} + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.0' end diff --git a/modules/openapi-generator/src/main/resources/swift5/XcodeGen.mustache b/modules/openapi-generator/src/main/resources/swift5/XcodeGen.mustache index a81137ae138e..aed8dcb76b2d 100644 --- a/modules/openapi-generator/src/main/resources/swift5/XcodeGen.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/XcodeGen.mustache @@ -4,14 +4,15 @@ targets: type: framework platform: iOS deploymentTarget: "9.0" - sources: [{{projectName}}] + sources: [{{#swiftPackagePath}}{{swiftPackagePath}}{{/swiftPackagePath}}{{^swiftPackagePath}}{{#useSPMFileStructure}}Sources{{/useSPMFileStructure}}{{^useSPMFileStructure}}{{projectName}}{{/useSPMFileStructure}}{{/swiftPackagePath}}] info: path: ./Info.plist version: {{#podVersion}}{{podVersion}}{{/podVersion}}{{^podVersion}}{{#apiInfo}}{{version}}{{/apiInfo}}{{^apiInfo}}}0.0.1{{/apiInfo}}{{/podVersion}} settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - {{#useAlamofire}}dependencies:{{/useAlamofire}}{{^useAlamofire}}{{#useRxSwift}}dependencies:{{/useRxSwift}}{{/useAlamofire}}{{^useAlamofire}}{{^useRxSwift}}{{#usePromiseKit}}dependencies:{{/usePromiseKit}}{{/useRxSwift}}{{/useAlamofire}}{{#useAlamofire}} + dependencies: + - carthage: AnyCodable{{#useAlamofire}} - carthage: Alamofire{{/useAlamofire}}{{#useRxSwift}} - carthage: RxSwift{{/useRxSwift}}{{#usePromiseKit}} - carthage: PromiseKit{{/usePromiseKit}} diff --git a/modules/openapi-generator/src/main/resources/swift5/api.mustache b/modules/openapi-generator/src/main/resources/swift5/api.mustache index f1e181e25241..92643fdf2686 100644 --- a/modules/openapi-generator/src/main/resources/swift5/api.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/api.mustache @@ -12,7 +12,7 @@ import RxSwift{{/useRxSwift}}{{#useCombine}} import Combine #endif{{/useCombine}}{{#swiftUseApiNamespace}} -extension {{projectName}}API { +extension {{projectName}} { {{/swiftUseApiNamespace}} {{#description}} @@ -49,7 +49,7 @@ extension {{projectName}}API { {{#isDeprecated}} @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, completion: @escaping ((_ data: {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}?, _ error: Error?) -> Void)) { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}.apiResponseQueue, completion: @escaping ((_ data: {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}?, _ error: Error?) -> Void)) { {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result -> Void in switch result { {{#returnType}} @@ -81,7 +81,7 @@ extension {{projectName}}API { {{#isDeprecated}} @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}.apiResponseQueue) -> Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { let deferred = Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.pending() {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result -> Void in switch result { @@ -112,7 +112,7 @@ extension {{projectName}}API { {{#isDeprecated}} @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}.apiResponseQueue) -> Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { return Observable.create { observer -> Disposable in {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result -> Void in switch result { @@ -147,7 +147,7 @@ extension {{projectName}}API { @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> AnyPublisher<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error> { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}.apiResponseQueue) -> AnyPublisher<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error> { return Future<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error>.init { promise in {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result -> Void in switch result { @@ -179,7 +179,7 @@ extension {{projectName}}API { {{#isDeprecated}} @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} - open class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error>) -> Void)) { + open class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error>) -> Void)) { {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result -> Void in switch result { {{#returnType}} @@ -229,7 +229,7 @@ extension {{projectName}}API { let {{paramName}}PreEscape = "\({{#isEnum}}{{paramName}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}}{{^isEnum}}APIHelper.mapValueToPathItem({{paramName}}){{/isEnum}})" let {{paramName}}PostEscape = {{paramName}}PreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{{=<% %>=}}{<%baseName%>}<%={{ }}=%>", with: {{paramName}}PostEscape, options: .literal, range: nil){{/pathParams}} - let URLString = {{projectName}}API.basePath + path + let URLString = {{projectName}}.basePath + path {{#bodyParam}} let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: {{paramName}}) {{/bodyParam}} @@ -248,13 +248,13 @@ extension {{projectName}}API { let parameters: [String: Any]? = nil {{/hasFormParams}} {{/bodyParam}}{{#hasQueryParams}} - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([{{^queryParams}}:{{/queryParams}} + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([{{^queryParams}}:{{/queryParams}} {{#queryParams}} {{> _param}}, {{/queryParams}} ]){{/hasQueryParams}}{{^hasQueryParams}} - let url = URLComponents(string: URLString){{/hasQueryParams}} + let urlComponents = URLComponents(string: URLString){{/hasQueryParams}} let nillableHeaders: [String: Any?] = [{{^headerParams}}{{^hasFormParams}} :{{/hasFormParams}}{{/headerParams}}{{#hasFormParams}} @@ -264,9 +264,9 @@ extension {{projectName}}API { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.{{#returnType}}getBuilder(){{/returnType}}{{^returnType}}getNonDecodableBuilder(){{/returnType}} + let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}.requestBuilderFactory.{{#returnType}}getBuilder(){{/returnType}}{{^returnType}}getNonDecodableBuilder(){{/returnType}} - return requestBuilder.init(method: "{{httpMethod}}", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "{{httpMethod}}", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } {{/operation}} diff --git a/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache b/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache index 71e9670965bf..b336fa9a7a63 100644 --- a/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache @@ -76,7 +76,7 @@ private var managerStore = SynchronizedDictionary, Error>) -> Void) { + override {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let managerId = UUID().uuidString // Create a new manager for each request to customize its request header let manager = createSessionManager() @@ -190,16 +190,18 @@ private var managerStore = SynchronizedDictionary() return modifiedRequest } - override {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() @@ -205,16 +205,18 @@ private var urlSessionStore = SynchronizedDictionary() } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.{{projectName}}.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ private var urlSessionStore = SynchronizedDictionary() completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ private var urlSessionStore = SynchronizedDictionary() for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in {{projectName}}API.customHeaders { + for (key, value) in {{projectName}}.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ private var urlSessionStore = SynchronizedDictionary() completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.{{projectName}}.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/modules/openapi-generator/src/main/resources/swift5/model.mustache b/modules/openapi-generator/src/main/resources/swift5/model.mustache index a5870644a60e..f9107398cfa3 100644 --- a/modules/openapi-generator/src/main/resources/swift5/model.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/model.mustache @@ -6,10 +6,24 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +{{#swiftUseApiNamespace}} + +@available(*, deprecated, renamed: "{{projectName}}.{{classname}}") +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} typealias {{classname}} = {{projectName}}.{{classname}} + +extension {{projectName}} { +{{/swiftUseApiNamespace}} {{#description}} /** {{description}} */{{/description}}{{#isDeprecated}} -@available(*, deprecated, message: "This schema is deprecated."){{/isDeprecated}}{{#isArray}} +@available(*, deprecated, message: "This schema is deprecated."){{/isDeprecated}}{{#vendorExtensions.x-is-one-of-interface}} +{{> modelOneOf}}{{/vendorExtensions.x-is-one-of-interface}}{{^vendorExtensions.x-is-one-of-interface}}{{#isArray}} {{> modelArray}}{{/isArray}}{{^isArray}}{{#isEnum}} {{> modelEnum}}{{/isEnum}}{{^isEnum}} -{{> modelObject}}{{/isEnum}}{{/isArray}}{{/model}}{{/models}} +{{> modelObject}}{{/isEnum}}{{/isArray}}{{/vendorExtensions.x-is-one-of-interface}}{{/model}}{{/models}} +{{#swiftUseApiNamespace}} +} +{{/swiftUseApiNamespace}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/swift5/modelObject.mustache b/modules/openapi-generator/src/main/resources/swift5/modelObject.mustache index 9956f81794dc..da0d44247fc0 100644 --- a/modules/openapi-generator/src/main/resources/swift5/modelObject.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/modelObject.mustache @@ -1,4 +1,4 @@ -{{^objcCompatible}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct {{classname}}: Codable, Hashable { +{{^objcCompatible}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#useClasses}}final class{{/useClasses}}{{^useClasses}}struct{{/useClasses}} {{classname}}: Codable{{#vendorExtensions.x-swift-hashable}}, Hashable{{/vendorExtensions.x-swift-hashable}} { {{/objcCompatible}}{{#objcCompatible}}@objc {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} class {{classname}}: NSObject, Codable { {{/objcCompatible}} @@ -11,17 +11,17 @@ {{#isEnum}} {{#description}}/** {{description}} */ {{/description}}{{#deprecated}}@available(*, deprecated, message: "This property is deprecated.") - {{/deprecated}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var {{name}}: {{{datatypeWithEnum}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}} + {{/deprecated}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var {{{name}}}: {{{datatypeWithEnum}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}} {{/isEnum}} {{^isEnum}} {{#description}}/** {{description}} */ {{/description}}{{#deprecated}}@available(*, deprecated, message: "This property is deprecated.") - {{/deprecated}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var {{name}}: {{{datatype}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}} + {{/deprecated}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var {{{name}}}: {{{datatype}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}} {{#objcCompatible}} {{#vendorExtensions.x-swift-optional-scalar}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var {{name}}Num: NSNumber? { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var {{{name}}}Num: NSNumber? { get { - return {{name}} as NSNumber? + return {{{name}}} as NSNumber? } } {{/vendorExtensions.x-swift-optional-scalar}} @@ -30,13 +30,19 @@ {{/allVars}} {{#hasVars}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init({{#allVars}}{{name}}: {{{datatypeWithEnum}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}{{^required}} = nil{{/required}}{{/defaultValue}}{{^-last}}, {{/-last}}{{/allVars}}) { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init({{#allVars}}{{{name}}}: {{{datatypeWithEnum}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}{{^required}} = nil{{/required}}{{/defaultValue}}{{^-last}}, {{/-last}}{{/allVars}}) { {{#allVars}} - self.{{name}} = {{name}} + self.{{{name}}} = {{{name}}} {{/allVars}} } {{/hasVars}} -{{#additionalPropertiesType}} + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum CodingKeys: {{#hasVars}}String, {{/hasVars}}CodingKey, CaseIterable { + {{#allVars}} + case {{{name}}}{{#vendorExtensions.x-codegen-escaped-property-name}} = "{{{baseName}}}"{{/vendorExtensions.x-codegen-escaped-property-name}} + {{/allVars}} + }{{#generateModelAdditionalProperties}}{{#additionalPropertiesType}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var additionalProperties: [String: {{{additionalPropertiesType}}}] = [:] {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} subscript(key: String) -> {{{additionalPropertiesType}}}? { @@ -50,40 +56,50 @@ set { additionalProperties[key] = newValue } - } + }{{/additionalPropertiesType}}{{/generateModelAdditionalProperties}} // Encodable protocol methods {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func encode(to encoder: Encoder) throws { - - var container = encoder.container(keyedBy: String.self) - + var container = encoder.container(keyedBy: CodingKeys.self) {{#allVars}} - try container.encode{{#required}}{{#isNullable}}IfPresent{{/isNullable}}{{/required}}{{^required}}IfPresent{{/required}}({{{name}}}, forKey: "{{{baseName}}}") + try container.encode{{^required}}IfPresent{{/required}}({{{name}}}, forKey: .{{{name}}}) {{/allVars}} - try container.encodeMap(additionalProperties) - } + {{#generateModelAdditionalProperties}} + {{#additionalPropertiesType}} + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + {{/additionalPropertiesType}} + {{/generateModelAdditionalProperties}} + }{{#generateModelAdditionalProperties}}{{#additionalPropertiesType}} // Decodable protocol methods {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}}{{#objcCompatible}} required{{/objcCompatible}} init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) {{#allVars}} - {{name}} = try container.decode{{#required}}{{#isNullable}}IfPresent{{/isNullable}}{{/required}}{{^required}}IfPresent{{/required}}({{{datatypeWithEnum}}}.self, forKey: "{{{baseName}}}") + {{{name}}} = try container.decode{{#required}}{{#isNullable}}IfPresent{{/isNullable}}{{/required}}{{^required}}IfPresent{{/required}}({{{datatypeWithEnum}}}.self, forKey: .{{{name}}}) {{/allVars}} var nonAdditionalPropertyKeys = Set() {{#allVars}} nonAdditionalPropertyKeys.insert("{{{baseName}}}") {{/allVars}} - additionalProperties = try container.decodeMap({{{additionalPropertiesType}}}.self, excludedKeys: nonAdditionalPropertyKeys) - } -{{/additionalPropertiesType}} -{{^additionalPropertiesType}}{{#vendorExtensions.x-codegen-has-escaped-property-names}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum CodingKeys: String, CodingKey, CaseIterable { + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap({{{additionalPropertiesType}}}.self, excludedKeys: nonAdditionalPropertyKeys) + }{{/additionalPropertiesType}}{{/generateModelAdditionalProperties}}{{^objcCompatible}}{{#useClasses}}{{#vendorExtensions.x-swift-hashable}} + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func == (lhs: {{classname}}, rhs: {{classname}}) -> Bool { {{#allVars}} - case {{name}}{{#vendorExtensions.x-codegen-escaped-property-name}} = "{{{baseName}}}"{{/vendorExtensions.x-codegen-escaped-property-name}} + lhs.{{{name}}} == rhs.{{{name}}}{{^-last}} &&{{/-last}} {{/allVars}} + {{#generateModelAdditionalProperties}}{{#additionalPropertiesType}}{{#hasVars}}&& {{/hasVars}}lhs.additionalProperties == rhs.additionalProperties{{/additionalPropertiesType}}{{/generateModelAdditionalProperties}} } -{{/vendorExtensions.x-codegen-has-escaped-property-names}}{{/additionalPropertiesType}} + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func hash(into hasher: inout Hasher) { + {{#allVars}} + hasher.combine({{{name}}}{{^required}}?{{/required}}.hashValue) + {{/allVars}} + {{#generateModelAdditionalProperties}}{{#additionalPropertiesType}}hasher.combine(additionalProperties.hashValue){{/additionalPropertiesType}}{{/generateModelAdditionalProperties}} + }{{/vendorExtensions.x-swift-hashable}}{{/useClasses}}{{/objcCompatible}} } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/swift5/modelOneOf.mustache b/modules/openapi-generator/src/main/resources/swift5/modelOneOf.mustache new file mode 100644 index 000000000000..8aeddcc3c123 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/swift5/modelOneOf.mustache @@ -0,0 +1,31 @@ +public enum {{classname}}: Codable { + {{#oneOf}} + case type{{.}}({{.}}) + {{/oneOf}} + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + {{#oneOf}} + case .type{{.}}(let value): + try container.encode(value) + {{/oneOf}} + } + } + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + {{#oneOf}} + {{#-first}} + if let value = try? container.decode({{.}}.self) { + {{/-first}} + {{^-first}} + } else if let value = try? container.decode({{.}}.self) { + {{/-first}} + self = .type{{.}}(value) + {{/oneOf}} + } else { + throw DecodingError.typeMismatch(Self.Type.self, .init(codingPath: decoder.codingPath, debugDescription: "Unable to decode instance of {{classname}}")) + } + } +} diff --git a/modules/openapi-generator/src/main/resources/swift5/model_doc.mustache b/modules/openapi-generator/src/main/resources/swift5/model_doc.mustache index d3e4ecf5c760..6b68575707a6 100644 --- a/modules/openapi-generator/src/main/resources/swift5/model_doc.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/model_doc.mustache @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isContainer}}[**{{dataType}}**]({{complexType}}.md){{/isContainer}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{#vars}}**{{{name}}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isContainer}}[**{{dataType}}**]({{complexType}}.md){{/isContainer}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} {{/vars}} [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/modules/openapi-generator/src/main/resources/typescript-angular/configuration.mustache b/modules/openapi-generator/src/main/resources/typescript-angular/configuration.mustache index 02632f0c64c7..40aaec67f477 100644 --- a/modules/openapi-generator/src/main/resources/typescript-angular/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-angular/configuration.mustache @@ -64,7 +64,11 @@ export class {{configurationClassName}} { {{#isApiKey}} this.credentials['{{name}}'] = () => { {{! Fallback behaviour may be removed for 5.0 release. See #5062 }} - return this.apiKeys['{{name}}'] || this.apiKeys['{{keyParamName}}']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['{{name}}'] || this.apiKeys['{{keyParamName}}']; + } }; {{/isApiKey}} {{#isBasic}} diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache index ddcbbbb86e99..b425c807a246 100644 --- a/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache @@ -34,7 +34,8 @@ export const {{classname}}AxiosParamCreator = function (configuration?: Configur {{#allParams}} * @param {{=<% %>=}}{<%&dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} {{/allParams}} - * @param {*} [options] Override http request option. + * @param {*} [options] Override http request option.{{#isDeprecated}} + * @deprecated{{/isDeprecated}} * @throws {RequiredError} */ {{nickname}}: async ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options: any = {}): Promise => { @@ -158,7 +159,7 @@ export const {{classname}}AxiosParamCreator = function (configuration?: Configur }) {{/isCollectionFormatMulti}} {{^isCollectionFormatMulti}} - localVarFormParams.{{#multipartFormData}}append{{/multipartFormData}}{{^multipartFormData}}set{{/multipartFormData}}({{paramName}}.join(COLLECTION_FORMATS.{{collectionFormat}})); + localVarFormParams.{{#multipartFormData}}append{{/multipartFormData}}{{^multipartFormData}}set{{/multipartFormData}}('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS.{{collectionFormat}})); {{/isCollectionFormatMulti}} }{{/isArray}} {{^isArray}} @@ -217,7 +218,8 @@ export const {{classname}}Fp = function(configuration?: Configuration) { {{#allParams}} * @param {{=<% %>=}}{<%&dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} {{/allParams}} - * @param {*} [options] Override http request option. + * @param {*} [options] Override http request option.{{#isDeprecated}} + * @deprecated{{/isDeprecated}} * @throws {RequiredError} */ async {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}>> { @@ -245,7 +247,8 @@ export const {{classname}}Factory = function (configuration?: Configuration, bas {{#allParams}} * @param {{=<% %>=}}{<%&dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} {{/allParams}} - * @param {*} [options] Override http request option. + * @param {*} [options] Override http request option.{{#isDeprecated}} + * @deprecated{{/isDeprecated}} * @throws {RequiredError} */ {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: any): AxiosPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> { @@ -272,7 +275,8 @@ export interface {{classname}}Interface { {{#allParams}} * @param {{=<% %>=}}{<%&dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} {{/allParams}} - * @param {*} [options] Override http request option. + * @param {*} [options] Override http request option.{{#isDeprecated}} + * @deprecated{{/isDeprecated}} * @throws {RequiredError} * @memberof {{classname}}Interface */ @@ -336,7 +340,8 @@ export class {{classname}} extends BaseAPI { * @param {{=<% %>=}}{<%&dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} {{/allParams}} {{/useSingleRequestParameter}} - * @param {*} [options] Override http request option. + * @param {*} [options] Override http request option.{{#isDeprecated}} + * @deprecated{{/isDeprecated}} * @throws {RequiredError} * @memberof {{classname}} */ diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache index 00d4e010fa0d..3036e3662907 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache @@ -109,7 +109,7 @@ export function {{classname}}ToJSON(value?: {{classname}} | null): any { {{^isPrimitiveType}} {{#isArray}} {{#uniqueItems}} - '{{baseName}}': {{^required}}value.{{name}} === undefined ? undefined : {{/required}}({{#isNullable}}value.{{name}} === null ? null : {{/isNullable}}Array.from((value.{{name}} as Set).map({{#items}}{{datatype}}{{/items}}ToJSON))), + '{{baseName}}': {{^required}}value.{{name}} === undefined ? undefined : {{/required}}({{#isNullable}}value.{{name}} === null ? null : {{/isNullable}}Array.from(value.{{name}} as Set).map({{#items}}{{datatype}}{{/items}}ToJSON)), {{/uniqueItems}} {{^uniqueItems}} '{{baseName}}': {{^required}}value.{{name}} === undefined ? undefined : {{/required}}({{#isNullable}}value.{{name}} === null ? null : {{/isNullable}}(value.{{name}} as Array).map({{#items}}{{datatype}}{{/items}}ToJSON)), diff --git a/modules/openapi-generator/src/main/resources/typescript-node/package.mustache b/modules/openapi-generator/src/main/resources/typescript-node/package.mustache index ff1c5c44519d..3679a80fadd9 100644 --- a/modules/openapi-generator/src/main/resources/typescript-node/package.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-node/package.mustache @@ -15,7 +15,7 @@ "dependencies": { "bluebird": "^3.5.0", "request": "^2.81.0", - "@types/bluebird": "*", + "@types/bluebird": "3.5.33", "@types/request": "*", "rewire": "^3.0.2" }, diff --git a/modules/openapi-generator/src/main/resources/typescript/api/api.mustache b/modules/openapi-generator/src/main/resources/typescript/api/api.mustache index 95cb62e631fb..1d36944043b2 100644 --- a/modules/openapi-generator/src/main/resources/typescript/api/api.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/api/api.mustache @@ -39,8 +39,8 @@ export class {{classname}}RequestFactory extends BaseAPIRequestFactory { * @param {{paramName}} {{description}} {{/allParams}} */ - public async {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: Configuration): Promise { - let config = options || this.configuration; + public async {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}_options?: Configuration): Promise { + let _config = _options || this.configuration; {{#allParams}} {{#required}} @@ -57,7 +57,7 @@ export class {{classname}}RequestFactory extends BaseAPIRequestFactory { .replace('{' + '{{baseName}}' + '}', encodeURIComponent(String({{paramName}}))){{/pathParams}}; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.{{httpMethod}}); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.{{httpMethod}}); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -132,7 +132,7 @@ export class {{classname}}RequestFactory extends BaseAPIRequestFactory { {{/hasAuthMethods}} // Apply auth methods {{#authMethods}} - authMethod = config.authMethods["{{name}}"] + authMethod = _config.authMethods["{{name}}"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/modules/openapi-generator/src/main/resources/typescript/auth/auth.mustache b/modules/openapi-generator/src/main/resources/typescript/auth/auth.mustache index 0e0ae23b1f28..bfb303e741ed 100644 --- a/modules/openapi-generator/src/main/resources/typescript/auth/auth.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/auth/auth.mustache @@ -75,8 +75,12 @@ export class {{#lambda.pascalcase}}{{name}}{{/lambda.pascalcase}}Authentication public constructor({{#useInversify}}@inject(AbstractTokenProvider) @named("{{name}}") {{/useInversify}}private tokenProvider: TokenProvider) {} {{/isBasicBearer}} {{#isOAuth}} - // TODO: How to handle oauth2 authentication! - public constructor() {} + /** + * Configures OAuth2 with the necessary properties + * + * @param accessToken: The access token to be used for every request + */ + public constructor(private accessToken: string) {} {{/isOAuth}} public getName(): string { @@ -85,7 +89,7 @@ export class {{#lambda.pascalcase}}{{name}}{{/lambda.pascalcase}}Authentication public {{#isBasicBearer}}async {{/isBasicBearer}}applySecurityAuthentication(context: RequestContext) { {{#isApiKey}} - context.{{#isKeyInHeader}}setHeaderParam{{/isKeyInHeader}}{{#isKeyInQuery}}addCookie{{/isKeyInQuery}}{{#isKeyInCookie}}setQueryParam{{/isKeyInCookie}}("{{keyParamName}}", this.apiKey); + context.{{#isKeyInHeader}}setHeaderParam{{/isKeyInHeader}}{{#isKeyInQuery}}setQueryParam{{/isKeyInQuery}}{{#isKeyInCookie}}addCookie{{/isKeyInCookie}}("{{keyParamName}}", this.apiKey); {{/isApiKey}} {{#isBasicBasic}} let comb = this.username + ":" + this.password; @@ -95,7 +99,7 @@ export class {{#lambda.pascalcase}}{{name}}{{/lambda.pascalcase}}Authentication context.setHeaderParam("Authorization", "Bearer " + await this.tokenProvider.getToken()); {{/isBasicBearer}} {{#isOAuth}} - // TODO + context.setHeaderParam("Authorization", "Bearer " + this.accessToken); {{/isOAuth}} } } @@ -119,7 +123,7 @@ export const authMethodServices = { export type ApiKeyConfiguration = string; export type HttpBasicConfiguration = { "username": string, "password": string }; export type HttpBearerConfiguration = { tokenProvider: TokenProvider }; -export type OAuth2Configuration = string; +export type OAuth2Configuration = { accessToken: string }; export type AuthMethodsConfiguration = { {{#authMethods}} @@ -152,6 +156,7 @@ export function configureAuthMethods(config: AuthMethodsConfiguration | undefine config["{{name}}"]["tokenProvider"] {{/isBasicBearer}} {{#isOAuth}} + config["{{name}}"]["accessToken"] {{/isOAuth}} ); } diff --git a/modules/openapi-generator/src/main/resources/typescript/types/ObservableAPI.mustache b/modules/openapi-generator/src/main/resources/typescript/types/ObservableAPI.mustache index b001eba36b45..da871ce94dde 100644 --- a/modules/openapi-generator/src/main/resources/typescript/types/ObservableAPI.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/types/ObservableAPI.mustache @@ -62,8 +62,8 @@ export class Observable{{classname}} { * @param {{paramName}} {{description}} {{/allParams}} */ - public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: Configuration): Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> { - const requestContextPromise = this.requestFactory.{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}options); + public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}_options?: Configuration): Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> { + const requestContextPromise = this.requestFactory.{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); diff --git a/modules/openapi-generator/src/main/resources/typescript/types/PromiseAPI.mustache b/modules/openapi-generator/src/main/resources/typescript/types/PromiseAPI.mustache index 4014dec1e068..9d74dd2a746e 100644 --- a/modules/openapi-generator/src/main/resources/typescript/types/PromiseAPI.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/types/PromiseAPI.mustache @@ -52,8 +52,8 @@ export class Promise{{classname}} { * @param {{paramName}} {{description}} {{/allParams}} */ - public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: Configuration): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> { - const result = this.api.{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}options); + public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}_options?: Configuration): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> { + const result = this.api.{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}_options); return result.toPromise(); } diff --git a/modules/openapi-generator/src/main/resources/wsdl-schema/jaxb-customization.mustache b/modules/openapi-generator/src/main/resources/wsdl-schema/jaxb-customization.mustache new file mode 100644 index 000000000000..cfdd31b1b58a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/wsdl-schema/jaxb-customization.mustache @@ -0,0 +1,50 @@ + + + + true + false + + {{#models}} + {{#model}} + {{^allOf}} + {{#vars}} + {{#isEnum}} + {{#baseType}} + + + {{#allowableValues}} + {{#enumVars}} + + {{/enumVars}} + {{/allowableValues}} + + + {{/baseType}} + {{/isEnum}} + {{/vars}} + {{/allOf}} + {{/model}} + {{/models}} + + {{#models}} + {{#model}} + {{^vars}} + + + {{#allowableValues}} + {{#enumVars}} + + {{/enumVars}} + {{/allowableValues}} + + + {{/vars}} + {{/model}} + {{/models}} + + diff --git a/modules/openapi-generator/src/main/resources/wsdl-schema/wsdl-converter.mustache b/modules/openapi-generator/src/main/resources/wsdl-schema/wsdl-converter.mustache new file mode 100644 index 000000000000..c136126eb5a1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/wsdl-schema/wsdl-converter.mustache @@ -0,0 +1,348 @@ + + + + + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + + + {{#responses}} + {{#is4xx}} + + + {{message}} + + + {{/is4xx}} + {{#is5xx}} + + + {{message}} + + + {{/is5xx}} + {{/responses}} + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + {{#models}} + {{#model}} + {{^vendorExtensions.x-is-openapimodel-enum}} + + {{#description}} + + {{description}} + + {{/description}} + + {{#vars}} + {{#vendorExtensions.x-prop-has-minormax}} + + + {{#description}} + + {{description}} + + {{/description}} + + {{#maximum}} + + {{/maximum}} + {{#minimum}} + + {{/minimum}} + {{#maxLength}} + + {{/maxLength}} + {{#minLength}} + + {{/minLength}} + + + + {{/vendorExtensions.x-prop-has-minormax}} + {{^vendorExtensions.x-prop-has-minormax}} + {{#isContainer}} + + {{/isContainer}} + {{^isContainer}} + + {{/isContainer}} + {{#description}} + + {{description}} + + + {{/description}} + {{/vendorExtensions.x-prop-has-minormax}} + {{/vars}} + + + {{/vendorExtensions.x-is-openapimodel-enum}} + {{/model}} + {{/models}} + {{#models}} + {{#model}} + {{^allOf}} + {{#vars}} + {{#isEnum}} + {{#baseType}} + + {{#description}} + + {{description}} + + {{/description}} + + {{#allowableValues}} + {{#enumVars}} + + {{/enumVars}} + {{/allowableValues}} + + + {{/baseType}} + {{/isEnum}} + {{/vars}} + {{/allOf}} + {{/model}} + {{/models}} + {{#models}} + {{#model}} + {{^vars}} + + {{#description}} + + {{description}} + + {{/description}} + + {{#allowableValues}} + {{#enumVars}} + + {{/enumVars}} + {{/allowableValues}} + + + {{/vars}} + {{/model}} + {{/models}} + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + {{#allParams}} + {{#isEnum}} + + + {{#allowableValues}} + {{#enumVars}} + + {{/enumVars}} + {{/allowableValues}} + + + {{/isEnum}} + {{/allParams}} + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + {{#hasParams}} + + + {{#allParams}} + {{#vendorExtensions.x-param-has-minormax}} + + + {{#description}} + + {{description}} + + {{/description}} + + {{#maximum}} + + {{/maximum}} + {{#minimum}} + + {{/minimum}} + {{#maxLength}} + + {{/maxLength}} + {{#minLength}} + + {{/minLength}} + + + + {{/vendorExtensions.x-param-has-minormax}} + {{^vendorExtensions.x-param-has-minormax}} + + {{#description}} + + {{description}} + + + {{/description}} + {{/vendorExtensions.x-param-has-minormax}} + {{/allParams}} + + + {{/hasParams}} + {{^hasParams}} + + {{/hasParams}} + {{#responses}} + {{^is4xx}} + {{^is5xx}} + + + {{#message}} + + + {{message}} + + + {{/message}} + {{^message}} + + {{/message}} + + + {{/is5xx}} + {{/is4xx}} + {{/responses}} + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + + + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + + + + {{#responses}} + {{#is2xx}} + + + + {{/is2xx}} + {{#isDefault}} + + + + {{/isDefault}} + {{#is4xx}} + + + + {{/is4xx}} + {{#is5xx}} + + + + {{/is5xx}} + {{/responses}} + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + + {{#notes}} + {{notes}} + {{/notes}} + {{^notes}} + {{#summary}} + {{summary}} + {{/summary}} + {{/notes}} + + {{#responses}} + {{^is4xx}} + {{^is5xx}} + + {{#message}} + {{message}} + + {{/message}} + {{/is5xx}} + {{/is4xx}} + {{#is4xx}} + + {{#message}} + {{message}} + + {{/message}} + {{/is4xx}} + {{#is5xx}} + + {{#message}} + {{message}} + + {{/message}} + {{/is5xx}} + {{/responses}} + + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + + + + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + + + + + + {{#responses}} + {{#is2xx}} + + + + {{/is2xx}} + {{#is4xx}} + + + + {{/is4xx}} + {{#is5xx}} + + + + {{/is5xx}} + {{/responses}} + + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + + + {{appDescription}} + + + + + \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java index a21c506d5a22..1d249e687e4d 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java @@ -1188,12 +1188,15 @@ public void testComposedSchemaOneOfDiscriminatorsInvalid() { Schema sc = openAPI.getComponents().getSchemas().get(modelName); + /* + // comment out below as we're now showing warnings instead of throwing exceptions try { codegen.fromModel(modelName, sc); Assert.assertTrue(false, "A RuntimeException should have been thrown when processing "+modelName+ " but it was not"); } catch (RuntimeException re) { Assert.assertEquals(re.getMessage(), errorMessageExpected); } + */ } } @@ -1220,12 +1223,15 @@ public void testComposedSchemaAnyOfDiscriminatorsInvalid() { Schema sc = openAPI.getComponents().getSchemas().get(modelName); + /* + // comment out below as we're now showing warnings instead of throwing exceptions try { codegen.fromModel(modelName, sc); Assert.assertTrue(false, "A RuntimeException should have been thrown when processing "+modelName+ " but it was not"); } catch (RuntimeException re) { Assert.assertEquals(re.getMessage(), errorMessageExpected); } + */ } } @@ -1256,7 +1262,8 @@ public void testComposedSchemaAnyOfDiscriminatorMap() { // inline anyOf with inline anyOf model doesn't work because we have null $refs and we throw an exception final String fmodelName = "FruitInlineInlineDisc"; final Schema fsc = openAPI.getComponents().getSchemas().get(fmodelName); - Assert.assertThrows(() -> codegen.fromModel(fmodelName, fsc)); + // comment out below as we're now showing warnings instead of throwing exceptions + //Assert.assertThrows(() -> codegen.fromModel(fmodelName, fsc)); // ref anyOf models with discriminator in properties in those models modelName = "FruitReqDisc"; @@ -1341,7 +1348,8 @@ public void testComposedSchemaOneOfDiscriminatorMap() { // inline oneOf with inline oneOf model doesn't work because we have null $refs and we throw an exception final String fmodelName = "FruitInlineInlineDisc"; final Schema fsc = openAPI.getComponents().getSchemas().get(fmodelName); - Assert.assertThrows(() -> codegen.fromModel(fmodelName, fsc)); + // comment out below as we're now showing warnings instead of throwing exceptions + //Assert.assertThrows(() -> codegen.fromModel(fmodelName, fsc)); // ref oneOf models with discriminator in properties in those models modelName = "FruitReqDisc"; @@ -3429,4 +3437,127 @@ public void testHasRequiredInResponses() { } } } + + @Test + public void testBooleansSetForIntSchemas() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_9447.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.setOpenAPI(openAPI); + codegen.setDisallowAdditionalPropertiesIfNotPresent(false); + + String modelName; + Schema sc; + CodegenModel cm; + + modelName = "UnboundedInteger"; + sc = openAPI.getComponents().getSchemas().get(modelName); + cm = codegen.fromModel(modelName, sc); + assertEquals(cm.isUnboundedInteger, true); + assertEquals(cm.isInteger, true); + assertEquals(cm.isShort, false); + assertEquals(cm.isLong, false); + + modelName = "Int32"; + sc = openAPI.getComponents().getSchemas().get(modelName); + cm = codegen.fromModel(modelName, sc); + assertEquals(cm.isUnboundedInteger, false); + assertEquals(cm.isInteger, true); + assertEquals(cm.isShort, true); + assertEquals(cm.isLong, false); + + modelName = "Int64"; + sc = openAPI.getComponents().getSchemas().get(modelName); + cm = codegen.fromModel(modelName, sc); + assertEquals(cm.isUnboundedInteger, false); + assertEquals(cm.isInteger, false); + assertEquals(cm.isShort, false); + assertEquals(cm.isLong, true); + + modelName = "ObjectModelWithIntegerProps"; + sc = openAPI.getComponents().getSchemas().get(modelName); + cm = codegen.fromModel(modelName, sc); + assertEquals(cm.isUnboundedInteger, false); + assertEquals(cm.isInteger, false); + assertEquals(cm.isShort, false); + assertEquals(cm.isLong, false); + CodegenProperty cp; + cp = cm.vars.get(0); + assertEquals(cp.isUnboundedInteger, true); + assertEquals(cp.isInteger, true); + assertEquals(cp.isShort, false); + assertEquals(cp.isLong, false); + cp = cm.vars.get(1); + assertEquals(cp.isUnboundedInteger, false); + assertEquals(cp.isInteger, true); + assertEquals(cp.isShort, true); + assertEquals(cp.isLong, false); + cp = cm.vars.get(2); + assertEquals(cp.isUnboundedInteger, false); + assertEquals(cp.isInteger, false); + assertEquals(cp.isShort, false); + assertEquals(cp.isLong, true); + + String path; + Operation operation; + CodegenOperation co; + CodegenParameter cpa; + CodegenResponse cr; + + path = "/UnboundedInteger"; + operation = openAPI.getPaths().get(path).getPost(); + co = codegen.fromOperation(path, "POST", operation, null); + cpa = co.pathParams.get(0); + assertEquals(cpa.isUnboundedInteger, true); + assertEquals(cpa.isInteger, true); + assertEquals(cpa.isShort, false); + assertEquals(cpa.isLong, false); + cpa = co.bodyParam; + assertEquals(cpa.isUnboundedInteger, true); + assertEquals(cpa.isInteger, true); + assertEquals(cpa.isShort, false); + assertEquals(cpa.isLong, false); + cr = co.responses.get(0); + assertEquals(cr.isUnboundedInteger, true); + assertEquals(cr.isInteger, true); + assertEquals(cr.isShort, false); + assertEquals(cr.isLong, false); + + path = "/Int32"; + operation = openAPI.getPaths().get(path).getPost(); + co = codegen.fromOperation(path, "POST", operation, null); + cpa = co.pathParams.get(0); + assertEquals(cpa.isUnboundedInteger, false); + assertEquals(cpa.isInteger, true); + assertEquals(cpa.isShort, true); + assertEquals(cpa.isLong, false); + cpa = co.bodyParam; + assertEquals(cpa.isUnboundedInteger, false); + assertEquals(cpa.isInteger, true); + assertEquals(cpa.isShort, true); + assertEquals(cpa.isLong, false); + cr = co.responses.get(0); + assertEquals(cr.isUnboundedInteger, false); + assertEquals(cr.isInteger, true); + assertEquals(cr.isShort, true); + assertEquals(cr.isLong, false); + + path = "/Int64"; + operation = openAPI.getPaths().get(path).getPost(); + co = codegen.fromOperation(path, "POST", operation, null); + cpa = co.pathParams.get(0); + assertEquals(cpa.isUnboundedInteger, false); + assertEquals(cpa.isInteger, false); + assertEquals(cpa.isShort, false); + assertEquals(cpa.isLong, true); + cpa = co.bodyParam; + assertEquals(cpa.isUnboundedInteger, false); + assertEquals(cpa.isInteger, false); + assertEquals(cpa.isShort, false); + assertEquals(cpa.isLong, true); + cr = co.responses.get(0); + assertEquals(cr.isUnboundedInteger, false); + assertEquals(cr.isInteger, false); + assertEquals(cr.isShort, false); + assertEquals(cr.isLong, true); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultGeneratorTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultGeneratorTest.java index 1dee6ced3017..81869d78f91f 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultGeneratorTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultGeneratorTest.java @@ -459,7 +459,7 @@ public void testBuiltinLibraryTemplates() throws IOException { List files = generator.opts(clientOptInput).generate(); - Assert.assertEquals(files.size(), 24); + Assert.assertEquals(files.size(), 26); // Generator should report a library templated file as a generated file TestUtils.ensureContainsFile(files, output, "src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt"); @@ -501,7 +501,7 @@ public void testBuiltinNonLibraryTemplates() throws IOException { List files = generator.opts(clientOptInput).generate(); - Assert.assertEquals(files.size(), 24); + Assert.assertEquals(files.size(), 26); // Generator should report README.md as a generated file TestUtils.ensureContainsFile(files, output, "README.md"); @@ -566,7 +566,7 @@ public void testCustomLibraryTemplates() throws IOException { List files = generator.opts(clientOptInput).generate(); - Assert.assertEquals(files.size(), 24); + Assert.assertEquals(files.size(), 26); // Generator should report a library templated file as a generated file TestUtils.ensureContainsFile(files, output, "src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt"); @@ -620,7 +620,7 @@ public void testCustomNonLibraryTemplates() throws IOException { List files = generator.opts(clientOptInput).generate(); - Assert.assertEquals(files.size(), 24); + Assert.assertEquals(files.size(), 26); // Generator should report README.md as a generated file TestUtils.ensureContainsFile(files, output, "README.md"); @@ -662,5 +662,62 @@ public void testHandlesTrailingSlashInServers() { Assert.assertEquals(servers.get(1).url, "http://trailingshlash.io:80/v1"); Assert.assertEquals(servers.get(2).url, "http://notrailingslash.io:80/v2"); } -} + @Test + public void testProcessUserDefinedTemplatesWithConfig() throws IOException { + Path target = Files.createTempDirectory("test"); + Path templates = Files.createTempDirectory("templates"); + File output = target.toFile(); + try { + // Create custom template + File customTemplate = new File(templates.toFile(), "README.mustache"); + new File(customTemplate.getParent()).mkdirs(); + Files.write(customTemplate.toPath(), + "# {{someKey}}".getBytes(StandardCharsets.UTF_8), + StandardOpenOption.CREATE); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("python") + .setInputSpec("src/test/resources/3_0/petstore.yaml") + .setPackageName("io.something") + .setTemplateDir(templates.toAbsolutePath().toString()) + .addAdditionalProperty("files", "src/test/resources/sampleConfig.json:\n\t folder: supportingjson "+ + "\n\t destinationFilename: supportingconfig.json \n\t templateType: SupportingFiles") + .setSkipOverwrite(false) + .setOutputDir(target.toAbsolutePath().toString()); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + DefaultGenerator generator = new DefaultGenerator(false); + + generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.API_DOCS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.API_TESTS, "false"); + + List files = generator.opts(clientOptInput).generate(); + + // remove commented code based on review - files does not seem to be supported in CodegenConfigurator + // supporting files sanity check + // TestUtils.ensureContainsFile(files, output, "sampleConfig.json"); + // Assert.assertTrue(new File(output, "sampleConfig.json").exists()); + + // Generator should report api_client.py as a generated file + TestUtils.ensureContainsFile(files, output, "io/something/api_client.py"); + + // Generated file should exist on the filesystem after generation + File apiClient = new File(output, "io/something/api_client.py"); + Assert.assertTrue(apiClient.exists()); + + // Generated file should contain our custom packageName + TestUtils.assertFileContains(apiClient.toPath(), + "from io.something import rest" + ); + } finally { + output.delete(); + templates.toFile().delete(); + } + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CSharpModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CSharpModelTest.java index 40ebe3023153..4a8f8f3e3bc6 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CSharpModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CSharpModelTest.java @@ -25,6 +25,7 @@ import org.openapitools.codegen.CodegenProperty; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.languages.AspNetCoreServerCodegen; import org.openapitools.codegen.languages.CSharpClientCodegen; import org.testng.Assert; import org.testng.annotations.Test; @@ -264,6 +265,126 @@ public void nullablePropertyTest() { Assert.assertTrue(property3.isPrimitiveType); } + @Test(description = "convert a model with a nullable property without nullable annotation") + public void nullablePropertyWithoutNullableReferenceTypesTest() { + final Schema model = new Schema() + .description("a sample model") + .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT).nullable(true)) + .addProperties("urls", new ArraySchema() + .items(new StringSchema()).nullable(true)) + .addProperties("name", new StringSchema().nullable(true)) + .addProperties("subObject", new Schema().addProperties("name", new StringSchema()).nullable(true)) + .addRequiredItem("id"); + final DefaultCodegen codegen = new AspNetCoreServerCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 4); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.dataType, "long?"); + Assert.assertEquals(property1.name, "Id"); + Assert.assertNull(property1.defaultValue); + Assert.assertEquals(property1.baseType, "long?"); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isPrimitiveType); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "urls"); + Assert.assertEquals(property2.dataType, "List"); + Assert.assertEquals(property2.name, "Urls"); + Assert.assertNull(property2.defaultValue); + Assert.assertEquals(property2.baseType, "List"); + Assert.assertEquals(property2.containerType, "array"); + Assert.assertFalse(property2.required); + Assert.assertTrue(property2.isPrimitiveType); + Assert.assertTrue(property2.isContainer); + + final CodegenProperty property3 = cm.vars.get(2); + Assert.assertEquals(property3.baseName, "name"); + Assert.assertEquals(property3.dataType, "string"); + Assert.assertEquals(property3.name, "Name"); + Assert.assertNull(property3.defaultValue); + Assert.assertEquals(property3.baseType, "string"); + Assert.assertFalse(property3.required); + Assert.assertTrue(property3.isPrimitiveType); + + final CodegenProperty property4 = cm.vars.get(3); + Assert.assertEquals(property4.baseName, "subObject"); + Assert.assertEquals(property4.dataType, "Object"); + Assert.assertEquals(property4.name, "SubObject"); + Assert.assertNull(property4.defaultValue); + Assert.assertEquals(property4.baseType, "Object"); + Assert.assertFalse(property4.required); + Assert.assertTrue(property4.isPrimitiveType); + } + + @Test(description = "convert a model with a nullable property using nullable annotation") + public void nullablePropertyWithNullableReferenceTypesTest() { + final Schema model = new Schema() + .description("a sample model") + .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT).nullable(true)) + .addProperties("urls", new ArraySchema() + .items(new StringSchema()).nullable(true)) + .addProperties("name", new StringSchema().nullable(true)) + .addProperties("subObject", new Schema().addProperties("name", new StringSchema()).nullable(true)) + .addRequiredItem("id"); + final DefaultCodegen codegen = new AspNetCoreServerCodegen(); + codegen.additionalProperties().put(AspNetCoreServerCodegen.NULLABLE_REFERENCE_TYPES, true); + codegen.processOpts(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 4); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.dataType, "long?"); + Assert.assertEquals(property1.name, "Id"); + Assert.assertNull(property1.defaultValue); + Assert.assertEquals(property1.baseType, "long?"); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isPrimitiveType); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "urls"); + Assert.assertEquals(property2.dataType, "List"); + Assert.assertEquals(property2.name, "Urls"); + Assert.assertNull(property2.defaultValue); + Assert.assertEquals(property2.baseType, "List?"); + Assert.assertEquals(property2.containerType, "array"); + Assert.assertFalse(property2.required); + Assert.assertTrue(property2.isPrimitiveType); + Assert.assertTrue(property2.isContainer); + + final CodegenProperty property3 = cm.vars.get(2); + Assert.assertEquals(property3.baseName, "name"); + Assert.assertEquals(property3.dataType, "string?"); + Assert.assertEquals(property3.name, "Name"); + Assert.assertNull(property3.defaultValue); + Assert.assertEquals(property3.baseType, "string?"); + Assert.assertFalse(property3.required); + Assert.assertFalse(property3.isPrimitiveType); + + final CodegenProperty property4 = cm.vars.get(3); + Assert.assertEquals(property4.baseName, "subObject"); + Assert.assertEquals(property4.dataType, "Object?"); + Assert.assertEquals(property4.name, "SubObject"); + Assert.assertNull(property4.defaultValue); + Assert.assertEquals(property4.baseType, "Object?"); + Assert.assertFalse(property4.required); + Assert.assertFalse(property4.isPrimitiveType); + } + @Test(description = "convert a model with list property") public void listPropertyTest() { final Schema model = new Schema() diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinModelCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinModelCodegenTest.java index 6885057c1c04..19829496e239 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinModelCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinModelCodegenTest.java @@ -9,6 +9,7 @@ import org.openapitools.codegen.languages.AbstractKotlinCodegen; import org.openapitools.codegen.languages.KotlinClientCodegen; import org.openapitools.codegen.languages.KotlinServerCodegen; +import org.openapitools.codegen.languages.KotlinServerDeprecatedCodegen; import org.openapitools.codegen.languages.KotlinSpringServerCodegen; import org.openapitools.codegen.languages.KotlinVertxServerCodegen; import org.testng.annotations.DataProvider; @@ -28,6 +29,7 @@ public Object[][] client() { return new Object[][]{ {new KotlinClientCodegen()}, {new KotlinServerCodegen()}, + {new KotlinServerDeprecatedCodegen()}, {new KotlinSpringServerCodegen()}, {new KotlinVertxServerCodegen()}, }; diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PythonClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PythonClientOptionsProvider.java index 7beb3ec69c0d..fc7d74074dd8 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PythonClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PythonClientOptionsProvider.java @@ -19,7 +19,7 @@ import com.google.common.collect.ImmutableMap; import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.languages.PythonLegacyClientCodegen; +import org.openapitools.codegen.languages.PythonClientCodegen; import java.util.Map; @@ -30,6 +30,8 @@ public class PythonClientOptionsProvider implements OptionsProvider { public static final String PACKAGE_URL_VALUE = ""; public static final String USE_NOSE_VALUE = "false"; public static final String RECURSION_LIMIT = "1200"; + public static final String DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT = "false"; + public static final String PYTHON_ATTR_NONE_IF_UNSET = "false"; @Override public String getLanguage() { @@ -39,16 +41,17 @@ public String getLanguage() { @Override public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(PythonLegacyClientCodegen.PACKAGE_URL, PACKAGE_URL_VALUE) + return builder.put(PythonClientCodegen.PACKAGE_URL, PACKAGE_URL_VALUE) .put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) .put(CodegenConstants.PROJECT_NAME, PROJECT_NAME_VALUE) .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) - .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .put(CodegenConstants.SOURCECODEONLY_GENERATION, "false") .put(CodegenConstants.LIBRARY, "urllib3") - .put(PythonLegacyClientCodegen.USE_NOSE, USE_NOSE_VALUE) - .put(PythonLegacyClientCodegen.RECURSION_LIMIT, RECURSION_LIMIT) + .put(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT) + .put(PythonClientCodegen.USE_NOSE, USE_NOSE_VALUE) + .put(PythonClientCodegen.RECURSION_LIMIT, RECURSION_LIMIT) + .put(PythonClientCodegen.PYTHON_ATTR_NONE_IF_UNSET, PYTHON_ATTR_NONE_IF_UNSET) .build(); } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PythonLegacyClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PythonLegacyClientOptionsProvider.java new file mode 100644 index 000000000000..90e76caea16f --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/PythonLegacyClientOptionsProvider.java @@ -0,0 +1,59 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright 2018 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.options; + +import com.google.common.collect.ImmutableMap; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.PythonLegacyClientCodegen; + +import java.util.Map; + +public class PythonLegacyClientOptionsProvider implements OptionsProvider { + public static final String PACKAGE_NAME_VALUE = "swagger_client_python"; + public static final String PROJECT_NAME_VALUE = "swagger-client-python"; + public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String PACKAGE_URL_VALUE = ""; + public static final String USE_NOSE_VALUE = "false"; + public static final String RECURSION_LIMIT = "1200"; + + @Override + public String getLanguage() { + return "python"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(PythonLegacyClientCodegen.PACKAGE_URL, PACKAGE_URL_VALUE) + .put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) + .put(CodegenConstants.PROJECT_NAME, PROJECT_NAME_VALUE) + .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") + .put(CodegenConstants.SOURCECODEONLY_GENERATION, "false") + .put(CodegenConstants.LIBRARY, "urllib3") + .put(PythonLegacyClientCodegen.USE_NOSE, USE_NOSE_VALUE) + .put(PythonLegacyClientCodegen.RECURSION_LIMIT, RECURSION_LIMIT) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java index e432b326d1c1..fa562df6d7f4 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java @@ -21,6 +21,7 @@ import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.languages.Swift5ClientCodegen; +import java.io.File; import java.util.Map; public class Swift5OptionsProvider implements OptionsProvider { @@ -45,9 +46,14 @@ public class Swift5OptionsProvider implements OptionsProvider { public static final String POD_DOCUMENTATION_URL_VALUE = "podDocumentationURL"; public static final String READONLY_PROPERTIES_VALUE = "false"; public static final String SWIFT_USE_API_NAMESPACE_VALUE = "swiftUseApiNamespace"; + public static final String USE_BACKTICKS_ESCAPES_VALUE = "false"; + public static final String GENERATE_MODEL_ADDITIONAL_PROPERTIES_VALUE = "true"; + public static final String HASHABLE_MODELS_VALUE = "true"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; public static final String LIBRARY_VALUE = "alamofire"; + public static final String USE_SPM_FILE_STRUCTURE_VALUE = "false"; + public static final String SWIFT_PACKAGE_PATH_VALUE = ""; @Override public String getLanguage() { @@ -77,6 +83,7 @@ public Map createOptions() { .put(Swift5ClientCodegen.POD_DOCUMENTATION_URL, POD_DOCUMENTATION_URL_VALUE) .put(Swift5ClientCodegen.READONLY_PROPERTIES, READONLY_PROPERTIES_VALUE) .put(Swift5ClientCodegen.SWIFT_USE_API_NAMESPACE, SWIFT_USE_API_NAMESPACE_VALUE) + .put(Swift5ClientCodegen.USE_BACKTICK_ESCAPES, USE_BACKTICKS_ESCAPES_VALUE) .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) @@ -84,6 +91,12 @@ public Map createOptions() { .put(CodegenConstants.LIBRARY, LIBRARY_VALUE) .put(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "true") .put(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, "true") + .put(Swift5ClientCodegen.USE_SPM_FILE_STRUCTURE, USE_SPM_FILE_STRUCTURE_VALUE) + .put(Swift5ClientCodegen.SWIFT_PACKAGE_PATH, SWIFT_PACKAGE_PATH_VALUE) + .put(Swift5ClientCodegen.GENERATE_MODEL_ADDITIONAL_PROPERTIES, GENERATE_MODEL_ADDITIONAL_PROPERTIES_VALUE) + .put(Swift5ClientCodegen.HASHABLE_MODELS, HASHABLE_MODELS_VALUE) + .put(Swift5ClientCodegen.MAP_FILE_BINARY_TO_DATA, "false") + .put(Swift5ClientCodegen.USE_CLASSES, "false") .build(); } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/AbstractPythonConnexionServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/AbstractPythonConnexionServerCodegenTest.java new file mode 100644 index 000000000000..0e1e46c347f8 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/AbstractPythonConnexionServerCodegenTest.java @@ -0,0 +1,114 @@ +package org.openapitools.codegen.python; + +import static org.openapitools.codegen.languages.AbstractPythonConnexionServerCodegen.PYTHON_SRC_ROOT; +import static org.openapitools.codegen.languages.AbstractPythonConnexionServerCodegen.USE_PYTHON_SRC_ROOT_IN_IMPORTS; + +import java.io.File; +import java.util.Collections; +import java.util.Map; +import java.util.Objects; + +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang3.ObjectUtils; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.AbstractPythonConnexionServerCodegen; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class AbstractPythonConnexionServerCodegenTest { + + /** + * Passing "description" as first param to succinctly identify the significance of test parameters. + */ + @Test(dataProvider = "data") + public void test(String description, Map additionalProperties, String modelName, + ExpectedValues expectedValues) { + AbstractPythonConnexionServerCodegen codegen = new MockAbstractPythonConnexionServerCodegen("", false); + codegen.additionalProperties().putAll(additionalProperties); + codegen.processOpts(); + String pythonSrcRoot = Objects.toString(codegen.additionalProperties().get(PYTHON_SRC_ROOT), null); + Assert.assertEquals(pythonSrcRoot, expectedValues.pythonSrcRoot); + Assert.assertEquals(codegen.apiPackage(), expectedValues.expectedApiPackage); + Assert.assertEquals(codegen.modelFileFolder(), expectedValues.expectedModelFileFolder); + Assert.assertEquals(codegen.apiFileFolder(), expectedValues.expectedApiFileFolder); + Assert.assertEquals(codegen.toModelImport(modelName), expectedValues.expectedImport); + } + + @DataProvider + public Object[][] data() { + return new Object[][]{ + new Object[]{ + "Default setup", + Collections.emptyMap(), + "TestModel", + new ExpectedValues("from openapi_server.models.test_model import TestModel", + "openapi_server.controllers", + platformAgnosticPath("generated-code", "connexion", "openapi_server", "models"), + platformAgnosticPath("generated-code", "connexion", "openapi_server", "controllers"), + null) + }, + new Object[]{ + "Default setup with Python src root", + ImmutableMap.of(PYTHON_SRC_ROOT, "test_root"), + "TestModel", + new ExpectedValues("from openapi_server.models.test_model import TestModel", + "openapi_server.controllers", + platformAgnosticPath("generated-code", "connexion", "test_root", "openapi_server", "models"), + platformAgnosticPath("generated-code", "connexion", "test_root", "openapi_server", "controllers"), + "test_root") + }, + new Object[]{ + "Python src in import", + ImmutableMap.of(PYTHON_SRC_ROOT, "test_root", USE_PYTHON_SRC_ROOT_IN_IMPORTS, "true"), + "TestModel", + new ExpectedValues("from test_root.openapi_server.models.test_model import TestModel", + "test_root.openapi_server.controllers", + platformAgnosticPath("generated-code", "connexion", "test_root", "openapi_server", "models"), + platformAgnosticPath("generated-code", "connexion", "test_root", "openapi_server", "controllers"), + null) + }, + new Object[]{ + "Python src in import with specified package", + ImmutableMap.of(PYTHON_SRC_ROOT, "test_root", + USE_PYTHON_SRC_ROOT_IN_IMPORTS, "true", + CodegenConstants.PACKAGE_NAME, "test_package"), + "TestModel", + new ExpectedValues("from test_root.test_package.models.test_model import TestModel", + "test_root.test_package.controllers", + platformAgnosticPath("generated-code", "connexion", "test_root", "test_package", "models"), + platformAgnosticPath("generated-code", "connexion", "test_root", "test_package", "controllers"), + null) + } + }; + } + + private static String platformAgnosticPath(String... nodes) { + return StringUtils.join(nodes, File.separatorChar); + } + + private static class MockAbstractPythonConnexionServerCodegen extends AbstractPythonConnexionServerCodegen { + public MockAbstractPythonConnexionServerCodegen(String templateDirectory, boolean fixBodyNameValue) { + super(templateDirectory, fixBodyNameValue); + } + } + + private static class ExpectedValues { + public final String expectedImport; + public final String expectedApiPackage; + public final String expectedModelFileFolder; + public final String expectedApiFileFolder; + public final String pythonSrcRoot; + + public ExpectedValues(String expectedImport, String expectedApiPackage, String expectedModelFileFolder, + String expectedApiFileFolder, String pythonSrcRoot) { + this.expectedImport = expectedImport; + this.expectedApiPackage = expectedApiPackage; + this.expectedModelFileFolder = expectedModelFileFolder; + this.expectedApiFileFolder = expectedApiFileFolder; + this.pythonSrcRoot = pythonSrcRoot != null ? pythonSrcRoot + File.separatorChar : null; + } + } + +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientOptionsTest.java index 8bec98892ef6..e423c6e85842 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientOptionsTest.java @@ -19,7 +19,7 @@ import org.openapitools.codegen.AbstractOptionsTest; import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.PythonLegacyClientCodegen; +import org.openapitools.codegen.languages.PythonClientCodegen; import org.openapitools.codegen.options.PythonClientOptionsProvider; import org.testng.Assert; @@ -29,7 +29,7 @@ import static org.mockito.Mockito.verify; public class PythonClientOptionsTest extends AbstractOptionsTest { - private PythonLegacyClientCodegen clientCodegen = mock(PythonLegacyClientCodegen.class, mockSettings); + private PythonClientCodegen clientCodegen = mock(PythonClientCodegen.class, mockSettings); public PythonClientOptionsTest() { super(new PythonClientOptionsProvider()); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonLegacyClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonLegacyClientOptionsTest.java new file mode 100644 index 000000000000..8c17cdbb2fd8 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonLegacyClientOptionsTest.java @@ -0,0 +1,54 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright 2018 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.python; + +import org.openapitools.codegen.AbstractOptionsTest; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.languages.PythonLegacyClientCodegen; +import org.openapitools.codegen.options.PythonLegacyClientOptionsProvider; +import org.testng.Assert; + +import java.io.File; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +public class PythonLegacyClientOptionsTest extends AbstractOptionsTest { + private PythonLegacyClientCodegen clientCodegen = mock(PythonLegacyClientCodegen.class, mockSettings); + + public PythonLegacyClientOptionsTest() { + super(new PythonLegacyClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @SuppressWarnings("unused") + @Override + protected void verifyOptions() { + Assert.assertEquals(clientCodegen.packagePath(), PythonLegacyClientOptionsProvider.PACKAGE_NAME_VALUE.replace('.', File.separatorChar)); + + verify(clientCodegen).setPackageName(PythonLegacyClientOptionsProvider.PACKAGE_NAME_VALUE); + verify(clientCodegen).setProjectName(PythonLegacyClientOptionsProvider.PROJECT_NAME_VALUE); + verify(clientCodegen).setPackageVersion(PythonLegacyClientOptionsProvider.PACKAGE_VERSION_VALUE); + verify(clientCodegen).setPackageUrl(PythonLegacyClientOptionsProvider.PACKAGE_URL_VALUE); + verify(clientCodegen).setUseNose(PythonLegacyClientOptionsProvider.USE_NOSE_VALUE); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientCodegenTest.java index 3981f3f60780..f50f20ac135d 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientCodegenTest.java @@ -677,4 +677,29 @@ public void exampleRegexParameterValidationOAS3Test() { // pattern_dont_escape_backslash '/^pattern\d{3}$/i' NOTE: the double \ is to escape \ in string but is read as single \ Assert.assertEquals(op.allParams.get(2).pattern, "/^pattern\\d{3}$/i"); } + + /** + * We want to make sure that the type mapping works as expect + */ + @Test(description = "test type mapping to handle special format, e.g. string+special") + public void typeMappingTest() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/type_mapping_test.yaml"); + final RubyClientCodegen codegen = new RubyClientCodegen(); + codegen.typeMapping().put("string+special", "VerySpecialStringInRuby"); + + codegen.setOpenAPI(openAPI); + final String path = "/animals"; + final Operation p = openAPI.getPaths().get(path).getGet(); + final CodegenOperation op = codegen.fromOperation(path, "get", p, null); + Assert.assertEquals(op.allParams.get(0).dataType, "VerySpecialStringInRuby"); + + final Schema schema = openAPI.getComponents().getSchemas().get("Animal"); + codegen.setOpenAPI(openAPI); + CodegenModel animal = codegen.fromModel("Animal", schema); + Assert.assertNotNull(animal); + CodegenProperty cp2 = animal.getVars().get(2); + Assert.assertEquals(cp2.name, "mapping_test"); + Assert.assertFalse(cp2.required); + Assert.assertEquals(cp2.dataType, "VerySpecialStringInRuby"); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/scala/SttpCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/scala/SttpCodegenTest.java new file mode 100644 index 000000000000..a48225430f00 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/scala/SttpCodegenTest.java @@ -0,0 +1,20 @@ +package org.openapitools.codegen.scala; + +import org.openapitools.codegen.languages.ScalaSttpClientCodegen; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class SttpCodegenTest { + + private final ScalaSttpClientCodegen codegen = new ScalaSttpClientCodegen(); + + @Test + public void encodePath() { + Assert.assertEquals(codegen.encodePath("{user_name}"), "${userName}"); + Assert.assertEquals(codegen.encodePath("{userName}"), "${userName}"); + Assert.assertEquals(codegen.encodePath("{UserName}"), "${userName}"); + Assert.assertEquals(codegen.encodePath("user_name"), "user_name"); + Assert.assertEquals(codegen.encodePath("before/{UserName}/after"), "before/${userName}/after"); + } + +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/scalaakka/ScalaAkkaClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/scalaakka/ScalaAkkaClientCodegenTest.java index d78b487d2860..4304e092bb16 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/scalaakka/ScalaAkkaClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/scalaakka/ScalaAkkaClientCodegenTest.java @@ -472,7 +472,7 @@ public void mainPackageTest() throws Exception { Generator gen = generator.opts(clientOptInput); List files = gen.generate(); - Assert.assertEquals(files.size(), 15); + Assert.assertEquals(files.size(), 16); TestUtils.ensureContainsFile(files, output, "src/main/scala/hello/world/model/SomeObj.scala"); TestUtils.ensureContainsFile(files, output, "src/main/scala/hello/world/core/ApiSettings.scala"); @@ -509,7 +509,7 @@ public void overridePackagesTest() throws Exception { Generator gen = generator.opts(clientOptInput); List files = gen.generate(); - Assert.assertEquals(files.size(), 15); + Assert.assertEquals(files.size(), 16); TestUtils.ensureContainsFile(files, output, "src/main/scala/hello/world/model/package/SomeObj.scala"); TestUtils.ensureContainsFile(files, output, "src/main/scala/hello/world/package/invoker/ApiSettings.scala"); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5OptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5OptionsTest.java index 65e97494cfa7..268d52bed289 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5OptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5OptionsTest.java @@ -48,5 +48,7 @@ protected void verifyOptions() { verify(clientCodegen).setLenientTypeCast(Boolean.parseBoolean(Swift5OptionsProvider.LENIENT_TYPE_CAST_VALUE)); verify(clientCodegen).setPrependFormOrBodyParameters(Boolean.valueOf(Swift5OptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)); verify(clientCodegen).setReadonlyProperties(Boolean.parseBoolean(Swift5OptionsProvider.READONLY_PROPERTIES_VALUE)); + verify(clientCodegen).setGenerateModelAdditionalProperties(Boolean.parseBoolean(Swift5OptionsProvider.GENERATE_MODEL_ADDITIONAL_PROPERTIES_VALUE)); + verify(clientCodegen).setHashableModels(Boolean.parseBoolean(Swift5OptionsProvider.HASHABLE_MODELS_VALUE)); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/wsdl/WsdlSchemaCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/wsdl/WsdlSchemaCodegenTest.java new file mode 100644 index 000000000000..6cb452dae1c2 --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/wsdl/WsdlSchemaCodegenTest.java @@ -0,0 +1,266 @@ +package org.openapitools.codegen.wsdl; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import org.apache.commons.io.FileUtils; +import org.openapitools.codegen.ClientOptInput; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.languages.WsdlSchemaCodegen; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.List; + +import static org.openapitools.codegen.TestUtils.assertFileContains; +import static org.openapitools.codegen.TestUtils.ensureContainsFile; + +public class WsdlSchemaCodegenTest { + private OpenAPI openAPI; + private File outputDirectory; + private String outputPath; + private List listOfFiles; + + @BeforeClass + public void setUp() throws IOException { + this.openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/wsdl/petstore.yaml"); + this.outputDirectory = Files.createTempDirectory("test").toFile().getCanonicalFile(); + this.outputPath = this.outputDirectory.getAbsolutePath().replace('\\', '/'); + + WsdlSchemaCodegen codegen = new WsdlSchemaCodegen(); + codegen.setOutputDir(this.outputDirectory.getAbsolutePath()); + + ClientOptInput input = new ClientOptInput() + .openAPI(this.openAPI) + .config(codegen); + + DefaultGenerator generator = new DefaultGenerator(); + this.listOfFiles = generator.opts(input).generate(); + } + + @Test(description = "ensure that the operationid has been generated correctly") + public void testOperationIdGeneration() { + final OpenAPI openAPI = this.openAPI; + WsdlSchemaCodegen codegen = new WsdlSchemaCodegen(); + codegen.setOpenAPI(openAPI); + + String requestPathWithId = "/store/order/{orderId}"; + Operation textOperationGet = openAPI.getPaths().get(requestPathWithId).getGet(); + CodegenOperation opGet = codegen.fromOperation(requestPathWithId, "get", textOperationGet, null); + String newOperationIdWithId = codegen.generateOperationId(opGet); + + String requestPathWithoutId = "/store/order"; + Operation textOperationPost = openAPI.getPaths().get(requestPathWithoutId).getPost(); + CodegenOperation opPost = codegen.fromOperation(requestPathWithoutId, "post", textOperationPost, null); + String newOperationIdWithoutId = codegen.generateOperationId(opPost); + + Assert.assertEquals(newOperationIdWithId, "GetStoreOrderByOrderid"); + Assert.assertEquals(newOperationIdWithoutId, "PostStoreOrder"); + } + + @Test(description = "Ensure that passed strings are processed correcly by this method") + public void testLowerCaseStringExceptFirstLetter() { + WsdlSchemaCodegen codegen = new WsdlSchemaCodegen(); + String value = codegen.lowerCaseStringExceptFirstLetter("uploadPetByPathId"); + + Assert.assertEquals(value, "Uploadpetbypathid"); + } + + @Test(description = "Check if element tags has been created for an operation ") + public void testIfElementTagsExist() { + String xsElementRequestMessage = + ""; + String xsElementResponseMessage = + ""; + String xsElementErrorResponse = + " \n" + + " \n" + + " Invalid input\n" + + " \n" + + " \n"; + + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), xsElementRequestMessage); + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), xsElementResponseMessage); + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), xsElementErrorResponse); + } + + @Test(description = "Check if complexType input- and output-message has been created for an operation ") + public void testIfInputAndResponseMessageExist() { + String complexTypeRequestMessage = + " \n" + + " \n" + + " \n" + + " \n" + + " ID of pet to return\n" + + " \n" + + " \n" + + " \n" + + " \n"; + + String complexTypeResponseMessage = + " \n" + + " \n" + + " \n" + + " \n" + + " successful operation\n" + + " \n" + + " \n" + + " \n" + + " \n"; + + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), complexTypeRequestMessage); + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), complexTypeResponseMessage); + } + + @Test(description = + "Check if complexType RequestMessage with minimum and maximum restriction has been created for an operation ") + public void testIfRequestMessageMinimumExists() { + String complexTypeRequestMessageMinimum = + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " ID of pet that needs to be fetched\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n"; + + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), complexTypeRequestMessageMinimum); + } + + @Test(description = "Check if complexType model has been created for an openapi model schema") + public void testIfComplexTypeModelExists() { + String complexTypeModel = + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " pet status in the store\n" + + " \n" + + " \n" + + " \n" + + " \n"; + + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), complexTypeModel); + } + + @Test(description = "Check if message and part tags has been created for an operation ") + public void testIfMessageTagsAndContentExist() { + String messageRequestMessage = + " \n" + + " \n" + + " "; + + String messageError = + " \n" + + " \n" + + " \n"; + + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), messageRequestMessage); + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), messageError); + } + + @Test(description = "Check if portType tag and portType operation has been generated") + public void testIfPorttypeOperationExists() { + String portType = ""; + + String portTypeOperation = + " \n" + + " Returns a single pet\n" + + " \n" + + " \n" + + " successful operation\n" + + " \n" + + " \n" + + " Invalid ID supplied\n" + + " \n" + + " \n" + + " Pet not found\n" + + " \n" + + " \n"; + + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), portType); + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), portTypeOperation); + } + + @Test(description = "Check if portType tag and portType operation has been generated") + public void testIfBindingOperationExists() { + String binding = ""; + + String bindingOperation = + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n"; + + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), binding); + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), bindingOperation); + } + + @Test(description = "Ensure that all files have been correctly generated") + public void testFileGeneration() throws Exception { + Assert.assertEquals(this.listOfFiles.size(), 5); + ensureContainsFile(this.listOfFiles, this.outputDirectory, ".openapi-generator-ignore"); + ensureContainsFile(this.listOfFiles, this.outputDirectory, ".openapi-generator/FILES"); + ensureContainsFile(this.listOfFiles, this.outputDirectory, ".openapi-generator/VERSION"); + ensureContainsFile(this.listOfFiles, this.outputDirectory, "service.wsdl"); + ensureContainsFile(this.listOfFiles, this.outputDirectory, "jaxb-customization.xml"); + } + + @Test(description = "Ensure that default description is set if it doesn't exist") + public void testOpenapiDescriptionWasNotProvided() throws IOException { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/ping.yaml"); + File outputDirectory = Files.createTempDirectory("test").toFile().getCanonicalFile(); + String outputPath = this.outputDirectory.getAbsolutePath().replace('\\', '/'); + + WsdlSchemaCodegen codegen = new WsdlSchemaCodegen(); + codegen.setOutputDir(this.outputDirectory.getAbsolutePath()); + + ClientOptInput input = new ClientOptInput().openAPI(openAPI).config(codegen); + + DefaultGenerator generator = new DefaultGenerator(); + generator.opts(input).generate(); + + String value = "No description provided"; + assertFileContains(Paths.get(outputPath + "/service.wsdl"), value); + + FileUtils.deleteDirectory(outputDirectory); + } + + + @AfterClass + public void cleanUp() throws Exception { + // Delete temp folder + FileUtils.deleteDirectory(this.outputDirectory); + } +} diff --git a/modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml index 9e9451dcc5be..097ae6768bb7 100644 --- a/modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml @@ -1373,8 +1373,6 @@ definitions: properties: breed: type: string - additionalProperties: false - additionalProperties: false Cat: allOf: - $ref: '#/definitions/Animal' @@ -1523,8 +1521,7 @@ definitions: type: object additionalProperties: type: array - items: - type: object + items: {} map_map_string: type: object additionalProperties: @@ -1535,14 +1532,15 @@ definitions: type: object additionalProperties: type: object - additionalProperties: - type: object - anytype_1: - type: object - anytype_2: {} + additionalProperties: {} + anytype_1: {} + anytype_2: + description: no type is set for this anytype_3: type: object properties: {} + description: 'because of a bug in swagger-parser, this should have values {str: (str, int, float...)} + but instead we get any type. See https://github.com/swagger-api/swagger-parser/issues/1378' AdditionalPropertiesString: type: object properties: @@ -2091,7 +2089,6 @@ definitions: properties: interNet: type: boolean - additionalProperties: false GrandparentAnimal: type: object required: diff --git a/modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml index 1cb539452dc2..6fa25c302182 100644 --- a/modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml @@ -1086,6 +1086,7 @@ definitions: xml: name: Order Category: + x-swift-hashable: true type: object required: - name @@ -1096,6 +1097,7 @@ definitions: name: type: string default: default-name + x-nullable: true xml: name: Category User: diff --git a/modules/openapi-generator/src/test/resources/2_0/templates/Java/ApiClient.mustache b/modules/openapi-generator/src/test/resources/2_0/templates/Java/ApiClient.mustache index 116f14c86503..d75e455961c5 100644 --- a/modules/openapi-generator/src/test/resources/2_0/templates/Java/ApiClient.mustache +++ b/modules/openapi-generator/src/test/resources/2_0/templates/Java/ApiClient.mustache @@ -1,28 +1,38 @@ -//overloaded main template file to add this comment - {{>licenseInfo}} package {{invokerPackage}}; +{{#threetenbp}} +import org.threeten.bp.*; + +{{/threetenbp}} import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; +{{#joda}} +import com.fasterxml.jackson.datatype.joda.JodaModule; +{{/joda}} {{#java8}} -import com.fasterxml.jackson.datatype.jsr310.*; -{{/java8}} -{{^java8}} -import com.fasterxml.jackson.datatype.joda.*; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +{{^threetenbp}} +import java.time.OffsetDateTime; +{{/threetenbp}} {{/java8}} +{{#threetenbp}} +import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; +{{/threetenbp}} import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.GenericType; import com.sun.jersey.api.client.config.DefaultClientConfig; +import com.sun.jersey.api.client.filter.GZIPContentEncodingFilter; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.api.client.WebResource.Builder; import com.sun.jersey.multipart.FormDataMultiPart; import com.sun.jersey.multipart.file.FileDataBodyPart; +import javax.ws.rs.core.Cookie; import javax.ws.rs.core.Response.Status.Family; import javax.ws.rs.core.MediaType; @@ -31,7 +41,9 @@ import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.HashMap; +import java.util.HashSet; import java.util.List; +import java.util.Arrays; import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; @@ -44,14 +56,51 @@ import java.io.UnsupportedEncodingException; import java.text.DateFormat; import {{invokerPackage}}.auth.Authentication; +{{#hasHttpBasicMethods}} import {{invokerPackage}}.auth.HttpBasicAuth; +{{/hasHttpBasicMethods}} +{{#hasHttpBearerMethods}} +import {{invokerPackage}}.auth.HttpBearerAuth; +{{/hasHttpBearerMethods}} +{{#hasApiKeyMethods}} import {{invokerPackage}}.auth.ApiKeyAuth; +{{/hasApiKeyMethods}} +{{#hasOAuthMethods}} import {{invokerPackage}}.auth.OAuth; +{{/hasOAuthMethods}} {{>generatedAnnotation}} -public class ApiClient { +public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { private Map defaultHeaderMap = new HashMap(); - private String basePath = "{{basePath}}"; + private Map defaultCookieMap = new HashMap(); + private String basePath = "{{{basePath}}}"; + protected List servers = new ArrayList({{#servers}}{{#-first}}Arrays.asList( +{{/-first}} new ServerConfiguration( + "{{{url}}}", + "{{{description}}}{{^description}}No description provided{{/description}}", + new HashMap(){{#variables}}{{#-first}} {{ +{{/-first}} put("{{{name}}}", new ServerVariable( + "{{{description}}}{{^description}}No description provided{{/description}}", + "{{{defaultValue}}}", + new HashSet( + {{#enumValues}} + {{#-first}} + Arrays.asList( + {{/-first}} + "{{{.}}}"{{^-last}},{{/-last}} + {{#-last}} + ) + {{/-last}} + {{/enumValues}} + ) + )); + {{#-last}} + }}{{/-last}}{{/variables}} + ){{^-last}},{{/-last}} + {{#-last}} + ){{/-last}}{{/servers}}); + protected Integer serverIndex = 0; + protected Map serverVariables = null; private boolean debugging = false; private int connectionTimeout = 0; @@ -69,15 +118,23 @@ public class ApiClient { objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + objectMapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + {{#joda}} + objectMapper.registerModule(new JodaModule()); + {{/joda}} {{#java8}} objectMapper.registerModule(new JavaTimeModule()); {{/java8}} - {{^java8}} - objectMapper.registerModule(new JodaModule()); - {{/java8}} + {{#threetenbp}} + ThreeTenModule module = new ThreeTenModule(); + module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT); + module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME); + module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME); + objectMapper.registerModule(module); + {{/threetenbp}} objectMapper.setDateFormat(ApiClient.buildDefaultDateFormat()); dateFormat = ApiClient.buildDefaultDateFormat(); @@ -86,8 +143,9 @@ public class ApiClient { setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{artifactVersion}}}/java{{/httpUserAgent}}"); // Setup authentications (key: authentication name, value: authentication). - authentications = new HashMap();{{#authMethods}}{{#isBasic}} - authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} + authentications = new HashMap();{{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + authentications.put("{{name}}", new HttpBasicAuth());{{/isBasicBasic}}{{^isBasicBasic}} + authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}"));{{/isBasicBasic}}{{/isBasic}}{{#isApiKey}} authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}} // Prevent the authentications from being modified. @@ -112,6 +170,7 @@ public class ApiClient { DefaultClientConfig conf = new DefaultClientConfig(); conf.getSingletons().add(jsonProvider); Client client = Client.create(conf); + client.addFilter(new GZIPContentEncodingFilter({{#useGzipFeature}}true{{/useGzipFeature}}{{^useGzipFeature}}false{{/useGzipFeature}})); if (debugging) { client.addFilter(new LoggingFilter()); } @@ -156,6 +215,33 @@ public class ApiClient { return this; } + public List getServers() { + return servers; + } + + public ApiClient setServers(List servers) { + this.servers = servers; + return this; + } + + public Integer getServerIndex() { + return serverIndex; + } + + public ApiClient setServerIndex(Integer serverIndex) { + this.serverIndex = serverIndex; + return this; + } + + public Map getServerVariables() { + return serverVariables; + } + + public ApiClient setServerVariables(Map serverVariables) { + this.serverVariables = serverVariables; + return this; + } + /** * Gets the status code of the previous request * @return Status code @@ -190,6 +276,24 @@ public class ApiClient { return authentications.get(authName); } + {{#hasHttpBearerMethods}} + /** + * Helper method to set access token for the first Bearer authentication. + * @param bearerToken Bearer token + */ + public void setBearerToken(String bearerToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(bearerToken); + return; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } + + {{/hasHttpBearerMethods}} + + {{#hasHttpBasicMethods}} /** * Helper method to set username for the first HTTP basic authentication. * @param username Username @@ -218,9 +322,12 @@ public class ApiClient { throw new RuntimeException("No HTTP basic authentication configured!"); } + {{/hasHttpBasicMethods}} + + {{#hasApiKeyMethods}} /** * Helper method to set API key value for the first API key authentication. - * @param apiKey API key + * @param apiKey the API key */ public void setApiKey(String apiKey) { for (Authentication auth : authentications.values()) { @@ -246,6 +353,9 @@ public class ApiClient { throw new RuntimeException("No API key authentication configured!"); } + {{/hasApiKeyMethods}} + + {{#hasOAuthMethods}} /** * Helper method to set access token for the first OAuth2 authentication. * @param accessToken Access token @@ -260,6 +370,8 @@ public class ApiClient { throw new RuntimeException("No OAuth2 authentication configured!"); } + {{/hasOAuthMethods}} + /** * Set the User-Agent header's value (by adding to the default header map). * @param userAgent User agent @@ -282,6 +394,18 @@ public class ApiClient { return this; } + /** + * Add a default cookie. + * + * @param key The cookie's key + * @param value The cookie's value + * @return API client + */ + public ApiClient addDefaultCookie(String key, String value) { + defaultCookieMap.put(key, value); + return this; + } + /** * Check that whether debugging is enabled for this API client. * @return True if debugging is on @@ -378,7 +502,9 @@ public class ApiClient { return ""; } else if (param instanceof Date) { return formatDate((Date) param); - } else if (param instanceof Collection) { + } {{#jsr310}}else if (param instanceof OffsetDateTime) { + return formatOffsetDateTime((OffsetDateTime) param); + } {{/jsr310}}else if (param instanceof Collection) { StringBuilder b = new StringBuilder(); for(Object o : (Collection)param) { if(b.length() > 0) { @@ -392,62 +518,71 @@ public class ApiClient { } } - /* - * Format to {@code Pair} objects. - * @param collectionFormat Collection format - * @param name Name - * @param value Value - * @return List of pair + /** + * Formats the specified query parameter to a list containing a single {@code Pair} object. + * + * Note that {@code value} must not be a collection. + * + * @param name The name of the parameter. + * @param value The value of the parameter. + * @return A list containing a single {@code Pair} object. */ - public List parameterToPairs(String collectionFormat, String name, Object value){ + public List parameterToPair(String name, Object value) { List params = new ArrayList(); // preconditions - if (name == null || name.isEmpty() || value == null) return params; + if (name == null || name.isEmpty() || value == null || value instanceof Collection) return params; - Collection valueCollection; - if (value instanceof Collection) { - valueCollection = (Collection) value; - } else { - params.add(new Pair(name, parameterToString(value))); - return params; - } + params.add(new Pair(name, parameterToString(value))); + return params; + } + + /** + * Formats the specified collection query parameters to a list of {@code Pair} objects. + * + * Note that the values of each of the returned Pair objects are percent-encoded. + * + * @param collectionFormat The collection format of the parameter. + * @param name The name of the parameter. + * @param value The value of the parameter. + * @return A list of {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Collection value) { + List params = new ArrayList(); - if (valueCollection.isEmpty()){ + // preconditions + if (name == null || name.isEmpty() || value == null) { return params; } - // get the collection format - String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - // create the params based on the collection format - if ("multi".equals(format)) { - for (Object item : valueCollection) { - params.add(new Pair(name, parameterToString(item))); + if ("multi".equals(collectionFormat)) { + for (Object item : value) { + params.add(new Pair(name, escapeString(parameterToString(item)))); } - return params; } + // collectionFormat is assumed to be "csv" by default String delimiter = ","; - if ("csv".equals(format)) { - delimiter = ","; - } else if ("ssv".equals(format)) { - delimiter = " "; - } else if ("tsv".equals(format)) { - delimiter = "\t"; - } else if ("pipes".equals(format)) { - delimiter = "|"; + // escape all delimiters except commas, which are URI reserved + // characters + if ("ssv".equals(collectionFormat)) { + delimiter = escapeString(" "); + } else if ("tsv".equals(collectionFormat)) { + delimiter = escapeString("\t"); + } else if ("pipes".equals(collectionFormat)) { + delimiter = escapeString("|"); } StringBuilder sb = new StringBuilder() ; - for (Object item : valueCollection) { + for (Object item : value) { sb.append(delimiter); - sb.append(parameterToString(item)); + sb.append(escapeString(parameterToString(item))); } - params.add(new Pair(name, sb.substring(1))); + params.add(new Pair(name, sb.substring(delimiter.length()))); return params; } @@ -458,11 +593,13 @@ public class ApiClient { * application/json * application/json; charset=UTF8 * APPLICATION/JSON + * application/vnd.company+json * @param mime MIME * @return True if MIME type is boolean */ public boolean isJsonMime(String mime) { - return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; + return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); } /** @@ -493,10 +630,10 @@ public class ApiClient { * * @param contentTypes The Content-Type array to select from * @return The Content-Type header to use. If the given array is empty, - * JSON will be used. + * or matches "any", JSON will be used. */ public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { + if (contentTypes.length == 0 || contentTypes[0].equals("*/*")) { return "application/json"; } for (String contentType : contentTypes) { @@ -561,11 +698,24 @@ public class ApiClient { * * @param path The sub path * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters * @return The full URL */ - private String buildUrl(String path, List queryParams) { + private String buildUrl(String path, List queryParams, List collectionQueryParams) { + String baseURL; + if (serverIndex != null) { + if (serverIndex < 0 || serverIndex >= servers.size()) { + throw new ArrayIndexOutOfBoundsException(String.format( + "Invalid index %d when selecting the host settings. Must be less than %d", serverIndex, servers.size() + )); + } + baseURL = servers.get(serverIndex).URL(serverVariables); + } else { + baseURL = basePath; + } + final StringBuilder url = new StringBuilder(); - url.append(basePath).append(path); + url.append(baseURL).append(path); if (queryParams != null && !queryParams.isEmpty()) { // support (constant) query string in `path`, e.g. "/posts?draft=1" @@ -584,17 +734,34 @@ public class ApiClient { } } + if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) { + String prefix = url.toString().contains("?") ? "&" : "?"; + for (Pair param : collectionQueryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + // collection query parameter value already escaped as part of parameterToPairs + url.append(escapeString(param.getName())).append("=").append(value); + } + } + } + return url.toString(); } - private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + private ClientResponse getAPIResponse(String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { if (body != null && !formParams.isEmpty()) { throw new ApiException(500, "Cannot have body and form params"); } - updateParamsForAuth(authNames, queryParams, headerParams); + updateParamsForAuth(authNames, queryParams, headerParams, cookieParams); - final String url = buildUrl(path, queryParams); + final String url = buildUrl(path, queryParams, collectionQueryParams); Builder builder; if (accept == null) { builder = httpClient.resource(url).getRequestBuilder(); @@ -602,12 +769,21 @@ public class ApiClient { builder = httpClient.resource(url).accept(accept); } - for (String key : headerParams.keySet()) { - builder = builder.header(key, headerParams.get(key)); + for (Entry keyValue : headerParams.entrySet()) { + builder = builder.header(keyValue.getKey(), keyValue.getValue()); } - for (String key : defaultHeaderMap.keySet()) { - if (!headerParams.containsKey(key)) { - builder = builder.header(key, defaultHeaderMap.get(key)); + for (Map.Entry keyValue : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(keyValue.getKey())) { + builder = builder.header(keyValue.getKey(), keyValue.getValue()); + } + } + + for (Entry keyValue : cookieParams.entrySet()) { + builder = builder.cookie(new Cookie(keyValue.getKey(), keyValue.getValue())); + } + for (Map.Entry keyValue : defaultCookieMap.entrySet()) { + if (!cookieParams.containsKey(keyValue.getKey())) { + builder = builder.cookie(new Cookie(keyValue.getKey(), keyValue.getValue())); } } @@ -623,8 +799,9 @@ public class ApiClient { response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams)); } else if ("PATCH".equals(method)) { response = builder.type(contentType).header("X-HTTP-Method-Override", "PATCH").post(ClientResponse.class, serialize(body, contentType, formParams)); - } - else { + } else if ("HEAD".equals(method)) { + response = builder.head(); + } else { throw new ApiException(500, "unknown method type " + method); } return response; @@ -637,8 +814,10 @@ public class ApiClient { * @param path The sub-path of the HTTP URL * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters * @param body The request body object - if it is not binary, otherwise null * @param headerParams The header parameters + * @param cookieParams The cookie parameters * @param formParams The form parameters * @param accept The request's Accept header * @param contentType The request's Content-Type header @@ -647,9 +826,9 @@ public class ApiClient { * @return The response body in type of string * @throws ApiException API exception */ - public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { + public T invokeAPI(String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { - ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames); + ClientResponse response = getAPIResponse(path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames); statusCode = response.getStatusInfo().getStatusCode(); responseHeaders = response.getHeaders(); @@ -686,12 +865,13 @@ public class ApiClient { * @param authNames The authentications to apply * @param queryParams Query parameters * @param headerParams Header parameters + * @param cookieParams Cookie parameters */ - private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams, Map cookieParams) { for (String authName : authNames) { Authentication auth = authentications.get(authName); if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); - auth.applyToParams(queryParams, headerParams); + auth.applyToParams(queryParams, headerParams, cookieParams); } } diff --git a/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/ApiClient.mustache b/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/ApiClient.mustache index 52c3c06e24cc..65494e8ea04a 100644 --- a/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/ApiClient.mustache +++ b/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/ApiClient.mustache @@ -1,5 +1,3 @@ -//overloaded template file within library folder to add this comment - package {{invokerPackage}}; import javax.ws.rs.client.Client; @@ -13,9 +11,12 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; +{{#hasOAuthMethods}} +import com.github.scribejava.core.model.OAuth2AccessToken; +{{/hasOAuthMethods}} import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; -import org.glassfish.jersey.filter.LoggingFilter; +import org.glassfish.jersey.client.HttpUrlConnectorProvider; import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.media.multipart.FormDataBodyPart; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; @@ -25,22 +26,38 @@ import org.glassfish.jersey.media.multipart.MultiPartFeature; import java.io.IOException; import java.io.InputStream; -{{^supportJava6}} +import java.net.URI; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.security.cert.X509Certificate; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; import java.nio.file.Files; +import java.nio.file.Paths; import java.nio.file.StandardCopyOption; -{{/supportJava6}} -{{#supportJava6}} -import org.apache.commons.io.FileUtils; -{{/supportJava6}} +import org.glassfish.jersey.logging.LoggingFeature; +import java.util.logging.Level; +import java.util.logging.Logger; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.HashMap; +import java.util.HashSet; import java.util.List; +import java.util.Arrays; import java.util.ArrayList; import java.util.Date; -import java.util.TimeZone; +{{#jsr310}} +{{#threetenbp}} +import org.threeten.bp.OffsetDateTime; +{{/threetenbp}} +{{^threetenbp}} +import java.time.OffsetDateTime; +{{/threetenbp}} +{{/jsr310}} import java.net.URLEncoder; @@ -53,30 +70,120 @@ import java.util.regex.Pattern; import {{invokerPackage}}.auth.Authentication; import {{invokerPackage}}.auth.HttpBasicAuth; +import {{invokerPackage}}.auth.HttpBearerAuth; +{{#hasHttpSignatureMethods}} +import {{invokerPackage}}.auth.HttpSignatureAuth; +{{/hasHttpSignatureMethods}} import {{invokerPackage}}.auth.ApiKeyAuth; +{{#hasOAuthMethods}} import {{invokerPackage}}.auth.OAuth; +{{/hasOAuthMethods}} {{>generatedAnnotation}} -public class ApiClient { - private Map defaultHeaderMap = new HashMap(); - private String basePath = "{{{basePath}}}"; - private boolean debugging = false; - private int connectionTimeout = 0; - - private Client httpClient; - private JSON json; - private String tempFolderPath = null; - - private Map authentications; - - private int statusCode; - private Map> responseHeaders; - - private DateFormat dateFormat; +public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { + protected Map defaultHeaderMap = new HashMap(); + protected Map defaultCookieMap = new HashMap(); + protected String basePath = "{{{basePath}}}"; + protected String userAgent; + private static final Logger log = Logger.getLogger(ApiClient.class.getName()); + + protected List servers = new ArrayList({{#servers}}{{#-first}}Arrays.asList( +{{/-first}} new ServerConfiguration( + "{{{url}}}", + "{{{description}}}{{^description}}No description provided{{/description}}", + new HashMap(){{#variables}}{{#-first}} {{ +{{/-first}} put("{{{name}}}", new ServerVariable( + "{{{description}}}{{^description}}No description provided{{/description}}", + "{{{defaultValue}}}", + new HashSet( + {{#enumValues}} + {{#-first}} + Arrays.asList( + {{/-first}} + "{{{.}}}"{{^-last}},{{/-last}} + {{#-last}} + ) + {{/-last}} + {{/enumValues}} + ) + )); + {{#-last}} + }}{{/-last}}{{/variables}} + ){{^-last}},{{/-last}} + {{#-last}} + ){{/-last}}{{/servers}}); + protected Integer serverIndex = 0; + protected Map serverVariables = null; + protected Map> operationServers = new HashMap>() {{ + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + {{#servers}} + {{#-first}} + put("{{{classname}}}.{{{operationId}}}", new ArrayList(Arrays.asList( + {{/-first}} + new ServerConfiguration( + "{{{url}}}", + "{{{description}}}{{^description}}No description provided{{/description}}", + new HashMap(){{#variables}}{{#-first}} {{ +{{/-first}} put("{{{name}}}", new ServerVariable( + "{{{description}}}{{^description}}No description provided{{/description}}", + "{{{defaultValue}}}", + new HashSet( + {{#enumValues}} + {{#-first}} + Arrays.asList( + {{/-first}} + "{{{.}}}"{{^-last}},{{/-last}} + {{#-last}} + ) + {{/-last}} + {{/enumValues}} + ) + )); + {{#-last}} + }}{{/-last}}{{/variables}} + ){{^-last}},{{/-last}} + {{#-last}} + )));{{/-last}} + {{/servers}} + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + }}; + protected Map operationServerIndex = new HashMap(); + protected Map> operationServerVariables = new HashMap>(); + protected boolean debugging = false; + protected ClientConfig clientConfig; + protected int connectionTimeout = 0; + private int readTimeout = 0; + + protected Client httpClient; + protected JSON json; + protected String tempFolderPath = null; + + protected Map authentications; + protected Map authenticationLookup; + + protected DateFormat dateFormat; + /** + * Constructs a new ApiClient with default parameters. + */ public ApiClient() { + this(null); + } + + /** + * Constructs a new ApiClient with the specified authentication parameters. + * + * @param authMap A hash map containing authentication parameters. + */ + public ApiClient(Map authMap) { json = new JSON(); - httpClient = buildHttpClient(debugging); + httpClient = buildHttpClient(); this.dateFormat = new RFC3339DateFormat(); @@ -84,16 +191,59 @@ public class ApiClient { setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{artifactVersion}}}/java{{/httpUserAgent}}"); // Setup authentications (key: authentication name, value: authentication). - authentications = new HashMap();{{#authMethods}}{{#isBasic}} - authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} - authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} - authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}} + authentications = new HashMap(); + Authentication auth = null; + {{#authMethods}} + if (authMap != null) { + auth = authMap.get("{{name}}"); + } + {{#isBasic}} + {{#isBasicBasic}} + if (auth instanceof HttpBasicAuth) { + authentications.put("{{name}}", auth); + } else { + authentications.put("{{name}}", new HttpBasicAuth()); + } + {{/isBasicBasic}} + {{#isBasicBearer}} + if (auth instanceof HttpBearerAuth) { + authentications.put("{{name}}", auth); + } else { + authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}")); + } + {{/isBasicBearer}} + {{#isHttpSignature}} + if (auth instanceof HttpSignatureAuth) { + authentications.put("{{name}}", auth); + } + {{/isHttpSignature}} + {{/isBasic}} + {{#isApiKey}} + if (auth instanceof ApiKeyAuth) { + authentications.put("{{name}}", auth); + } else { + authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}")); + } + {{/isApiKey}} + {{#isOAuth}} + if (auth instanceof OAuth) { + authentications.put("{{name}}", auth); + } else { + authentications.put("{{name}}", new OAuth(basePath, "{{tokenUrl}}")); + } + {{/isOAuth}} + {{/authMethods}} // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); + + // Setup authentication lookup (key: authentication alias, value: authentication name) + authenticationLookup = new HashMap();{{#authMethods}}{{#vendorExtensions.x-auth-id-alias}} + authenticationLookup.put("{{name}}", "{{.}}");{{/vendorExtensions.x-auth-id-alias}}{{/authMethods}} } /** * Gets the JSON instance to do JSON serialization and deserialization. + * * @return JSON */ public JSON getJSON() { @@ -109,33 +259,77 @@ public class ApiClient { return this; } + /** + * Returns the base URL to the location where the OpenAPI document is being served. + * + * @return The base URL to the target host. + */ public String getBasePath() { return basePath; } + /** + * Sets the base URL to the location where the OpenAPI document is being served. + * + * @param basePath The base URL to the target host. + */ public ApiClient setBasePath(String basePath) { this.basePath = basePath; + {{#hasOAuthMethods}} + setOauthBasePath(basePath); + {{/hasOAuthMethods}} return this; } - /** - * Gets the status code of the previous request - * @return Status code - */ - public int getStatusCode() { - return statusCode; + public List getServers() { + return servers; } - /** - * Gets the response headers of the previous request - * @return Response headers - */ - public Map> getResponseHeaders() { - return responseHeaders; + public ApiClient setServers(List servers) { + this.servers = servers; + updateBasePath(); + return this; + } + + public Integer getServerIndex() { + return serverIndex; + } + + public ApiClient setServerIndex(Integer serverIndex) { + this.serverIndex = serverIndex; + updateBasePath(); + return this; + } + + public Map getServerVariables() { + return serverVariables; + } + + public ApiClient setServerVariables(Map serverVariables) { + this.serverVariables = serverVariables; + updateBasePath(); + return this; + } + + private void updateBasePath() { + if (serverIndex != null) { + setBasePath(servers.get(serverIndex).URL(serverVariables)); + } } + {{#hasOAuthMethods}} + private void setOauthBasePath(String basePath) { + for(Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setBasePath(basePath); + } + } + } + + {{/hasOAuthMethods}} /** * Get authentications (key: authentication name, value: authentication). + * * @return Map of authentication object */ public Map getAuthentications() { @@ -154,13 +348,14 @@ public class ApiClient { /** * Helper method to set username for the first HTTP basic authentication. + * * @param username Username */ - public void setUsername(String username) { + public ApiClient setUsername(String username) { for (Authentication auth : authentications.values()) { if (auth instanceof HttpBasicAuth) { ((HttpBasicAuth) auth).setUsername(username); - return; + return this; } } throw new RuntimeException("No HTTP basic authentication configured!"); @@ -168,13 +363,14 @@ public class ApiClient { /** * Helper method to set password for the first HTTP basic authentication. + * * @param password Password */ - public void setPassword(String password) { + public ApiClient setPassword(String password) { for (Authentication auth : authentications.values()) { if (auth instanceof HttpBasicAuth) { ((HttpBasicAuth) auth).setPassword(password); - return; + return this; } } throw new RuntimeException("No HTTP basic authentication configured!"); @@ -182,56 +378,167 @@ public class ApiClient { /** * Helper method to set API key value for the first API key authentication. + * * @param apiKey API key */ - public void setApiKey(String apiKey) { + public ApiClient setApiKey(String apiKey) { for (Authentication auth : authentications.values()) { if (auth instanceof ApiKeyAuth) { ((ApiKeyAuth) auth).setApiKey(apiKey); - return; + return this; } } throw new RuntimeException("No API key authentication configured!"); } + /** + * Helper method to configure authentications which respects aliases of API keys. + * + * @param secrets Hash map from authentication name to its secret. + */ + public ApiClient configureApiKeys(Map secrets) { + for (Map.Entry authEntry : authentications.entrySet()) { + Authentication auth = authEntry.getValue(); + if (auth instanceof ApiKeyAuth) { + String name = authEntry.getKey(); + // respect x-auth-id-alias property + name = authenticationLookup.containsKey(name) ? authenticationLookup.get(name) : name; + if (secrets.containsKey(name)) { + ((ApiKeyAuth) auth).setApiKey(secrets.get(name)); + } + } + } + return this; + } + /** * Helper method to set API key prefix for the first API key authentication. + * * @param apiKeyPrefix API key prefix */ - public void setApiKeyPrefix(String apiKeyPrefix) { + public ApiClient setApiKeyPrefix(String apiKeyPrefix) { for (Authentication auth : authentications.values()) { if (auth instanceof ApiKeyAuth) { ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; + return this; } } throw new RuntimeException("No API key authentication configured!"); } + /** + * Helper method to set bearer token for the first Bearer authentication. + * + * @param bearerToken Bearer token + */ + public ApiClient setBearerToken(String bearerToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(bearerToken); + return this; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } + + + {{#hasOAuthMethods}} /** * Helper method to set access token for the first OAuth2 authentication. * @param accessToken Access token */ - public void setAccessToken(String accessToken) { + public ApiClient setAccessToken(String accessToken) { for (Authentication auth : authentications.values()) { if (auth instanceof OAuth) { ((OAuth) auth).setAccessToken(accessToken); - return; + return this; } } throw new RuntimeException("No OAuth2 authentication configured!"); } + /** + * Helper method to set the credentials for the first OAuth2 authentication. + * + * @param clientId the client ID + * @param clientSecret the client secret + */ + public ApiClient setOauthCredentials(String clientId, String clientSecret) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setCredentials(clientId, clientSecret, isDebugging()); + return this; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Helper method to set the password flow for the first OAuth2 authentication. + * + * @param username the user name + * @param password the user password + */ + public ApiClient setOauthPasswordFlow(String username, String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).usePasswordFlow(username, password); + return this; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Helper method to set the authorization code flow for the first OAuth2 authentication. + * + * @param code the authorization code + */ + public ApiClient setOauthAuthorizationCodeFlow(String code) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).useAuthorizationCodeFlow(code); + return this; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Helper method to set the scopes for the first OAuth2 authentication. + * + * @param scope the oauth scope + */ + public ApiClient setOauthScope(String scope) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setScope(scope); + return this; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + {{/hasOAuthMethods}} /** * Set the User-Agent header's value (by adding to the default header map). * @param userAgent Http user agent * @return API client */ public ApiClient setUserAgent(String userAgent) { + userAgent = userAgent; addDefaultHeader("User-Agent", userAgent); return this; } + /** + * Get the User-Agent header's value. + * @return User-Agent string + */ + public String getUserAgent(){ + return userAgent; + } + /** * Add a default header. * @@ -244,6 +551,39 @@ public class ApiClient { return this; } + /** + * Add a default cookie. + * + * @param key The cookie's key + * @param value The cookie's value + * @return API client + */ + public ApiClient addDefaultCookie(String key, String value) { + defaultCookieMap.put(key, value); + return this; + } + + /** + * Gets the client config. + * @return Client config + */ + public ClientConfig getClientConfig() { + return clientConfig; + } + + /** + * Set the client config. + * + * @param clientConfig Set the client config + * @return API client + */ + public ApiClient setClientConfig(ClientConfig clientConfig) { + this.clientConfig = clientConfig; + // Rebuild HTTP Client according to the new "clientConfig" value. + this.httpClient = buildHttpClient(); + return this; + } + /** * Check that whether debugging is enabled for this API client. * @return True if debugging is switched on @@ -261,7 +601,7 @@ public class ApiClient { public ApiClient setDebugging(boolean debugging) { this.debugging = debugging; // Rebuild HTTP Client according to the new "debugging" value. - this.httpClient = buildHttpClient(debugging); + this.httpClient = buildHttpClient(); return this; } @@ -307,6 +647,27 @@ public class ApiClient { return this; } + /** + * read timeout (in milliseconds). + * @return Read timeout + */ + public int getReadTimeout() { + return readTimeout; + } + + /** + * Set the read timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + * @param readTimeout Read timeout in milliseconds + * @return API client + */ + public ApiClient setReadTimeout(int readTimeout) { + this.readTimeout = readTimeout; + httpClient.property(ClientProperties.READ_TIMEOUT, readTimeout); + return this; + } + /** * Get the date format used to parse/format date parameters. * @return Date format @@ -359,7 +720,9 @@ public class ApiClient { return ""; } else if (param instanceof Date) { return formatDate((Date) param); - } else if (param instanceof Collection) { + } {{#jsr310}}else if (param instanceof OffsetDateTime) { + return formatOffsetDateTime((OffsetDateTime) param); + } {{/jsr310}}else if (param instanceof Collection) { StringBuilder b = new StringBuilder(); for(Object o : (Collection)param) { if(b.length() > 0) { @@ -439,11 +802,14 @@ public class ApiClient { * application/json * application/json; charset=UTF8 * APPLICATION/JSON + * application/vnd.company+json + * "* / *" is also default to JSON * @param mime MIME * @return True if the MIME type is JSON */ public boolean isJsonMime(String mime) { - return mime != null && mime.matches("(?i)application\\/json(;.*)?"); + String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; + return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); } /** @@ -510,7 +876,7 @@ public class ApiClient { * @return Entity * @throws ApiException API exception */ - public Entity serialize(Object obj, Map formParams, String contentType) throws ApiException { + public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); @@ -534,11 +900,60 @@ public class ApiClient { entity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); } else { // We let jersey handle the serialization - entity = Entity.entity(obj, contentType); + if (isBodyNullable) { // payload is nullable + if (obj instanceof String) { + entity = Entity.entity(obj == null ? "null" : "\"" + ((String)obj).replaceAll("\"", Matcher.quoteReplacement("\\\"")) + "\"", contentType); + } else { + entity = Entity.entity(obj == null ? "null" : obj, contentType); + } + } else { + if (obj instanceof String) { + entity = Entity.entity(obj == null ? "" : "\"" + ((String)obj).replaceAll("\"", Matcher.quoteReplacement("\\\"")) + "\"", contentType); + } else { + entity = Entity.entity(obj == null ? "" : obj, contentType); + } + } } return entity; } + /** + * Serialize the given Java object into string according the given + * Content-Type (only JSON, HTTP form is supported for now). + * @param obj Object + * @param formParams Form parameters + * @param contentType Context type + * @param isBodyNullable True if the body is nullable + * @return String + * @throws ApiException API exception + */ + public String serializeToString(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + try { + if (contentType.startsWith("multipart/form-data")) { + throw new ApiException("multipart/form-data not yet supported for serializeToString (http signature authentication)"); + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + String formString = ""; + for (Entry param : formParams.entrySet()) { + formString = param.getKey() + "=" + URLEncoder.encode(parameterToString(param.getValue()), "UTF-8") + "&"; + } + + if (formString.length() == 0) { // empty string + return formString; + } else { + return formString.substring(0, formString.length() - 1); + } + } else { + if (isBodyNullable) { + return obj == null ? "null" : json.getMapper().writeValueAsString(obj); + } else { + return obj == null ? "" : json.getMapper().writeValueAsString(obj); + } + } + } catch (Exception ex) { + throw new ApiException("Failed to perform serializeToString: " + ex.toString()); + } + } + /** * Deserialize response body to Java object according to the Content-Type. * @param Type @@ -566,8 +981,9 @@ public class ApiClient { List contentTypes = response.getHeaders().get("Content-Type"); if (contentTypes != null && !contentTypes.isEmpty()) contentType = String.valueOf(contentTypes.get(0)); - if (contentType == null) - throw new ApiException(500, "missing Content-Type in response"); + + // read the entity stream multiple times + response.bufferEntity(); return response.readEntity(returnType); } @@ -581,13 +997,7 @@ public class ApiClient { public File downloadFileFromResponse(Response response) throws ApiException { try { File file = prepareDownloadFile(response); -{{^supportJava6}} Files.copy(response.readEntity(InputStream.class), file.toPath(), StandardCopyOption.REPLACE_EXISTING); -{{/supportJava6}} -{{#supportJava6}} - // Java6 falls back to commons.io for file copying - FileUtils.copyToFile(response.readEntity(InputStream.class), file); -{{/supportJava6}} return file; } catch (IOException e) { throw new ApiException(e); @@ -618,132 +1028,286 @@ public class ApiClient { prefix = filename.substring(0, pos) + "-"; suffix = filename.substring(pos); } - // File.createTempFile requires the prefix to be at least three characters long + // Files.createTempFile requires the prefix to be at least three characters long if (prefix.length() < 3) prefix = "download-"; } if (tempFolderPath == null) - return File.createTempFile(prefix, suffix); + return Files.createTempFile(prefix, suffix).toFile(); else - return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile(); } /** * Invoke API by sending HTTP request with the given options. * * @param Type + * @param operation The qualified name of the operation * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" * @param queryParams The query parameters * @param body The request body object * @param headerParams The header parameters + * @param cookieParams The cookie parameters * @param formParams The form parameters * @param accept The request's Accept header * @param contentType The request's Content-Type header * @param authNames The authentications to apply * @param returnType The return type into which to deserialize the response + * @param isBodyNullable True if the body is nullable * @return The response body in type of string * @throws ApiException API exception */ - public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { - updateParamsForAuth(authNames, queryParams, headerParams); - - // Not using `.target(this.basePath).path(path)` below, + public ApiResponse invokeAPI( + String operation, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map cookieParams, + Map formParams, + String accept, + String contentType, + String[] authNames, + GenericType returnType, + boolean isBodyNullable) + throws ApiException { + + // Not using `.target(targetURL).path(path)` below, // to support (constant) query string in `path`, e.g. "/posts?draft=1" - WebTarget target = httpClient.target(this.basePath + path); + String targetURL; + if (serverIndex != null && operationServers.containsKey(operation)) { + Integer index = operationServerIndex.containsKey(operation) ? operationServerIndex.get(operation) : serverIndex; + Map variables = operationServerVariables.containsKey(operation) ? + operationServerVariables.get(operation) : serverVariables; + List serverConfigurations = operationServers.get(operation); + if (index < 0 || index >= serverConfigurations.size()) { + throw new ArrayIndexOutOfBoundsException( + String.format( + "Invalid index %d when selecting the host settings. Must be less than %d", + index, serverConfigurations.size())); + } + targetURL = serverConfigurations.get(index).URL(variables) + path; + } else { + targetURL = this.basePath + path; + } + WebTarget target = httpClient.target(targetURL); if (queryParams != null) { for (Pair queryParam : queryParams) { if (queryParam.getValue() != null) { - target = target.queryParam(queryParam.getName(), queryParam.getValue()); + target = target.queryParam(queryParam.getName(), escapeString(queryParam.getValue())); } } } Invocation.Builder invocationBuilder = target.request().accept(accept); - for (Entry entry : headerParams.entrySet()) { + for (Entry entry : cookieParams.entrySet()) { + String value = entry.getValue(); + if (value != null) { + invocationBuilder = invocationBuilder.cookie(entry.getKey(), value); + } + } + + for (Entry entry : defaultCookieMap.entrySet()) { + String value = entry.getValue(); + if (value != null) { + invocationBuilder = invocationBuilder.cookie(entry.getKey(), value); + } + } + + Entity entity = serialize(body, formParams, contentType, isBodyNullable); + + // put all headers in one place + Map allHeaderParams = new HashMap<>(defaultHeaderMap); + allHeaderParams.putAll(headerParams); + + // update different parameters (e.g. headers) for authentication + updateParamsForAuth( + authNames, + queryParams, + allHeaderParams, + cookieParams, + serializeToString(body, formParams, contentType, isBodyNullable), + method, + target.getUri()); + + for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); if (value != null) { invocationBuilder = invocationBuilder.header(entry.getKey(), value); } } - for (Entry entry : defaultHeaderMap.entrySet()) { - String key = entry.getKey(); - if (!headerParams.containsKey(key)) { - String value = entry.getValue(); - if (value != null) { - invocationBuilder = invocationBuilder.header(key, value); + Response response = null; + + try { + response = sendRequest(method, invocationBuilder, entity); + + {{#hasOAuthMethods}} + // If OAuth is used and a status 401 is received, renew the access token and retry the request + if (response.getStatusInfo() == Status.UNAUTHORIZED) { + for (String authName : authNames) { + Authentication authentication = authentications.get(authName); + if (authentication instanceof OAuth) { + OAuth2AccessToken accessToken = ((OAuth) authentication).renewAccessToken(); + if (accessToken != null) { + invocationBuilder.header("Authorization", null); + invocationBuilder.header("Authorization", "Bearer " + accessToken.getAccessToken()); + response = sendRequest(method, invocationBuilder, entity); + } + break; + } } } - } - Entity entity = serialize(body, formParams, contentType); + {{/hasOAuthMethods}} + int statusCode = response.getStatusInfo().getStatusCode(); + Map> responseHeaders = buildResponseHeaders(response); - Response response; + if (response.getStatusInfo() == Status.NO_CONTENT) { + return new ApiResponse(statusCode, responseHeaders); + } else if (response.getStatusInfo().getFamily() == Status.Family.SUCCESSFUL) { + if (returnType == null) { + return new ApiResponse(statusCode, responseHeaders); + } else { + return new ApiResponse(statusCode, responseHeaders, deserialize(response, returnType)); + } + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { + try { + respBody = String.valueOf(response.readEntity(String.class)); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + throw new ApiException( + response.getStatus(), message, buildResponseHeaders(response), respBody); + } + } finally { + try { + response.close(); + } catch (Exception e) { + // it's not critical, since the response object is local in method invokeAPI; that's fine, + // just continue + } + } + } - if ("GET".equals(method)) { - response = invocationBuilder.get(); - } else if ("POST".equals(method)) { + private Response sendRequest(String method, Invocation.Builder invocationBuilder, Entity entity) { + Response response; + if ("POST".equals(method)) { response = invocationBuilder.post(entity); } else if ("PUT".equals(method)) { response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { - response = invocationBuilder.delete(); + response = invocationBuilder.method("DELETE", entity); } else if ("PATCH".equals(method)) { - response = invocationBuilder.header("X-HTTP-Method-Override", "PATCH").post(entity); + response = invocationBuilder.method("PATCH", entity); } else { - throw new ApiException(500, "unknown method type " + method); + response = invocationBuilder.method(method); } + return response; + } - statusCode = response.getStatusInfo().getStatusCode(); - responseHeaders = buildResponseHeaders(response); - - if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { - return null; - } else if (response.getStatusInfo().getFamily() == Status.Family.SUCCESSFUL) { - if (returnType == null) - return null; - else - return deserialize(response, returnType); - } else { - String message = "error"; - String respBody = null; - if (response.hasEntity()) { - try { - respBody = String.valueOf(response.readEntity(String.class)); - message = respBody; - } catch (RuntimeException e) { - // e.printStackTrace(); - } - } - throw new ApiException( - response.getStatus(), - message, - buildResponseHeaders(response), - respBody); - } + /** + * @deprecated Add qualified name of the operation as a first parameter. + */ + @Deprecated + public ApiResponse invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType, boolean isBodyNullable) throws ApiException { + return invokeAPI(null, path, method, queryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType, isBodyNullable); } /** * Build the Client used to make HTTP requests. - * @param debugging Debug setting * @return Client */ - private Client buildHttpClient(boolean debugging) { - final ClientConfig clientConfig = new ClientConfig(); + protected Client buildHttpClient() { + // recreate the client config to pickup changes + clientConfig = getDefaultClientConfig(); + + ClientBuilder clientBuilder = ClientBuilder.newBuilder(); + customizeClientBuilder(clientBuilder); + clientBuilder = clientBuilder.withConfig(clientConfig); + return clientBuilder.build(); + } + + /** + * Get the default client config. + * @return Client config + */ + public ClientConfig getDefaultClientConfig() { + ClientConfig clientConfig = new ClientConfig(); clientConfig.register(MultiPartFeature.class); clientConfig.register(json); clientConfig.register(JacksonFeature.class); + clientConfig.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true); + // turn off compliance validation to be able to send payloads with DELETE calls + clientConfig.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); if (debugging) { - clientConfig.register(LoggingFilter.class); + clientConfig.register(new LoggingFeature(java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), java.util.logging.Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 1024*50 /* Log payloads up to 50K */)); + clientConfig.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY, LoggingFeature.Verbosity.PAYLOAD_ANY); + // Set logger to ALL + java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME).setLevel(java.util.logging.Level.ALL); + } else { + // suppress warnings for payloads with DELETE calls: + java.util.logging.Logger.getLogger("org.glassfish.jersey.client").setLevel(java.util.logging.Level.SEVERE); } - return ClientBuilder.newClient(clientConfig); + + return clientConfig; } - private Map> buildResponseHeaders(Response response) { + /** + * Customize the client builder. + * + * This method can be overriden to customize the API client. For example, this can be used to: + * 1. Set the hostname verifier to be used by the client to verify the endpoint's hostname + * against its identification information. + * 2. Set the client-side key store. + * 3. Set the SSL context that will be used when creating secured transport connections to + * server endpoints from web targets created by the client instance that is using this SSL context. + * 4. Set the client-side trust store. + * + * To completely disable certificate validation (at your own risk), you can + * override this method and invoke disableCertificateValidation(clientBuilder). + */ + protected void customizeClientBuilder(ClientBuilder clientBuilder) { + // No-op extension point + } + + /** + * Disable X.509 certificate validation in TLS connections. + * + * Please note that trusting all certificates is extremely risky. + * This may be useful in a development environment with self-signed certificates. + */ + protected void disableCertificateValidation(ClientBuilder clientBuilder) throws KeyManagementException, NoSuchAlgorithmException { + TrustManager[] trustAllCerts = new X509TrustManager[] { + new X509TrustManager() { + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + @Override + public void checkClientTrusted(X509Certificate[] certs, String authType) { + } + @Override + public void checkServerTrusted(X509Certificate[] certs, String authType) { + } + } + }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, trustAllCerts, new SecureRandom()); + clientBuilder.sslContext(sslContext); + } + + protected Map> buildResponseHeaders(Response response) { Map> responseHeaders = new HashMap>(); for (Entry> entry: response.getHeaders().entrySet()) { List values = entry.getValue(); @@ -760,12 +1324,20 @@ public class ApiClient { * Update query and header parameters based on authentication settings. * * @param authNames The authentications to apply + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + * @param cookieParams Map of cookie parameters + * @param method HTTP method (e.g. POST) + * @param uri HTTP URI */ - private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + protected void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams, + Map cookieParams, String payload, String method, URI uri) throws ApiException { for (String authName : authNames) { Authentication auth = authentications.get(authName); - if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); - auth.applyToParams(queryParams, headerParams); + if (auth == null) { + continue; + } + auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri); } } } diff --git a/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/JSON.mustache b/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/JSON.mustache index 52e94ec9326a..3297c77e49b2 100644 --- a/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/JSON.mustache +++ b/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/JSON.mustache @@ -1,18 +1,32 @@ -//overloaded template file within library folder to add this comment - package {{invokerPackage}}; +{{#threetenbp}} +import org.threeten.bp.*; +{{/threetenbp}} import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; +{{#openApiNullable}} +import org.openapitools.jackson.nullable.JsonNullableModule; +{{/openApiNullable}} {{#java8}} -import com.fasterxml.jackson.datatype.jsr310.*; -{{/java8}} -{{^java8}} -import com.fasterxml.jackson.datatype.joda.*; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; {{/java8}} +{{#joda}} +import com.fasterxml.jackson.datatype.joda.JodaModule; +{{/joda}} +{{#threetenbp}} +import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; +{{/threetenbp}} +{{#models.0}} +import {{modelPackage}}.*; +{{/models.0}} import java.text.DateFormat; - +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import javax.ws.rs.core.GenericType; import javax.ws.rs.ext.ContextResolver; {{>generatedAnnotation}} @@ -22,7 +36,9 @@ public class JSON implements ContextResolver { public JSON() { mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); + mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); @@ -30,9 +46,20 @@ public class JSON implements ContextResolver { {{#java8}} mapper.registerModule(new JavaTimeModule()); {{/java8}} - {{^java8}} + {{#joda}} mapper.registerModule(new JodaModule()); - {{/java8}} + {{/joda}} + {{#threetenbp}} + ThreeTenModule module = new ThreeTenModule(); + module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT); + module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME); + module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME); + mapper.registerModule(module); + {{/threetenbp}} + {{#openApiNullable}} + JsonNullableModule jnm = new JsonNullableModule(); + mapper.registerModule(jnm); + {{/openApiNullable}} } /** @@ -47,4 +74,204 @@ public class JSON implements ContextResolver { public ObjectMapper getContext(Class type) { return mapper; } + + /** + * Get the object mapper + * + * @return object mapper + */ + public ObjectMapper getMapper() { return mapper; } + + /** + * Returns the target model class that should be used to deserialize the input data. + * The discriminator mappings are used to determine the target model class. + * + * @param node The input data. + * @param modelClass The class that contains the discriminator mappings. + */ + public static Class getClassForElement(JsonNode node, Class modelClass) { + ClassDiscriminatorMapping cdm = modelDiscriminators.get(modelClass); + if (cdm != null) { + return cdm.getClassForElement(node, new HashSet>()); + } + return null; + } + + /** + * Helper class to register the discriminator mappings. + */ + private static class ClassDiscriminatorMapping { + // The model class name. + Class modelClass; + // The name of the discriminator property. + String discriminatorName; + // The discriminator mappings for a model class. + Map> discriminatorMappings; + + // Constructs a new class discriminator. + ClassDiscriminatorMapping(Class cls, String propertyName, Map> mappings) { + modelClass = cls; + discriminatorName = propertyName; + discriminatorMappings = new HashMap>(); + if (mappings != null) { + discriminatorMappings.putAll(mappings); + } + } + + // Return the name of the discriminator property for this model class. + String getDiscriminatorPropertyName() { + return discriminatorName; + } + + // Return the discriminator value or null if the discriminator is not + // present in the payload. + String getDiscriminatorValue(JsonNode node) { + // Determine the value of the discriminator property in the input data. + if (discriminatorName != null) { + // Get the value of the discriminator property, if present in the input payload. + node = node.get(discriminatorName); + if (node != null && node.isValueNode()) { + String discrValue = node.asText(); + if (discrValue != null) { + return discrValue; + } + } + } + return null; + } + + /** + * Returns the target model class that should be used to deserialize the input data. + * This function can be invoked for anyOf/oneOf composed models with discriminator mappings. + * The discriminator mappings are used to determine the target model class. + * + * @param node The input data. + * @param visitedClasses The set of classes that have already been visited. + */ + Class getClassForElement(JsonNode node, Set> visitedClasses) { + if (visitedClasses.contains(modelClass)) { + // Class has already been visited. + return null; + } + // Determine the value of the discriminator property in the input data. + String discrValue = getDiscriminatorValue(node); + if (discrValue == null) { + return null; + } + Class cls = discriminatorMappings.get(discrValue); + // It may not be sufficient to return this cls directly because that target class + // may itself be a composed schema, possibly with its own discriminator. + visitedClasses.add(modelClass); + for (Class childClass : discriminatorMappings.values()) { + ClassDiscriminatorMapping childCdm = modelDiscriminators.get(childClass); + if (childCdm == null) { + continue; + } + if (!discriminatorName.equals(childCdm.discriminatorName)) { + discrValue = getDiscriminatorValue(node); + if (discrValue == null) { + continue; + } + } + if (childCdm != null) { + // Recursively traverse the discriminator mappings. + Class childDiscr = childCdm.getClassForElement(node, visitedClasses); + if (childDiscr != null) { + return childDiscr; + } + } + } + return cls; + } + } + + /** + * Returns true if inst is an instance of modelClass in the OpenAPI model hierarchy. + * + * The Java class hierarchy is not implemented the same way as the OpenAPI model hierarchy, + * so it's not possible to use the instanceof keyword. + * + * @param modelClass A OpenAPI model class. + * @param inst The instance object. + */ + public static boolean isInstanceOf(Class modelClass, Object inst, Set> visitedClasses) { + if (modelClass.isInstance(inst)) { + // This handles the 'allOf' use case with single parent inheritance. + return true; + } + if (visitedClasses.contains(modelClass)) { + // This is to prevent infinite recursion when the composed schemas have + // a circular dependency. + return false; + } + visitedClasses.add(modelClass); + + // Traverse the oneOf/anyOf composed schemas. + Map descendants = modelDescendants.get(modelClass); + if (descendants != null) { + for (GenericType childType : descendants.values()) { + if (isInstanceOf(childType.getRawType(), inst, visitedClasses)) { + return true; + } + } + } + return false; + } + + /** + * A map of discriminators for all model classes. + */ + private static Map, ClassDiscriminatorMapping> modelDiscriminators = new HashMap, ClassDiscriminatorMapping>(); + + /** + * A map of oneOf/anyOf descendants for each model class. + */ + private static Map, Map> modelDescendants = new HashMap, Map>(); + + /** + * Register a model class discriminator. + * + * @param modelClass the model class + * @param discriminatorPropertyName the name of the discriminator property + * @param mappings a map with the discriminator mappings. + */ + public static void registerDiscriminator(Class modelClass, String discriminatorPropertyName, Map> mappings) { + ClassDiscriminatorMapping m = new ClassDiscriminatorMapping(modelClass, discriminatorPropertyName, mappings); + modelDiscriminators.put(modelClass, m); + } + + /** + * Register the oneOf/anyOf descendants of the modelClass. + * + * @param modelClass the model class + * @param descendants a map of oneOf/anyOf descendants. + */ + public static void registerDescendants(Class modelClass, Map descendants) { + modelDescendants.put(modelClass, descendants); + } + + private static JSON json; + + static + { + json = new JSON(); + } + + /** + * Get the default JSON instance. + * + * @return the default JSON instance + */ + public static JSON getDefault() { + return json; + } + + /** + * Set the default JSON instance. + * + * @param json JSON instance to be used + */ + public static void setDefault(JSON json) { + JSON.json = json; + } } diff --git a/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/api.mustache b/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/api.mustache index e6e83d3550b8..666430c834e1 100644 --- a/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/api.mustache +++ b/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/api.mustache @@ -1,9 +1,8 @@ -//overloaded template file within library folder to add this comment - package {{package}}; import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiClient; +import {{invokerPackage}}.ApiResponse; import {{invokerPackage}}.Configuration; import {{invokerPackage}}.Pair; @@ -17,8 +16,8 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -{{/fullJavaUtil}} +{{/fullJavaUtil}} {{>generatedAnnotation}} {{#operations}} public class {{classname}} { @@ -32,15 +31,26 @@ public class {{classname}} { this.apiClient = apiClient; } + /** + * Get the API cilent + * + * @return API client + */ public ApiClient getApiClient() { return apiClient; } + /** + * Set the API cilent + * + * @param apiClient an instance of API client + */ public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } {{#operation}} + {{^vendorExtensions.x-group-parameters}} /** * {{summary}} * {{notes}} @@ -51,8 +61,61 @@ public class {{classname}} { * @return {{returnType}} {{/returnType}} * @throws ApiException if fails to make API call + {{#responses.0}} + * @http.response.details + + + {{#responses}} + + {{/responses}} +
Status Code Description Response Headers
{{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}}
+ {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + {{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException { + {{#returnType}}return {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}){{#returnType}}.getData(){{/returnType}}; + } + {{/vendorExtensions.x-group-parameters}} + + {{^vendorExtensions.x-group-parameters}} + /** + * {{summary}} + * {{notes}} + {{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + * @return ApiResponse<{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}> + * @throws ApiException if fails to make API call + {{#responses.0}} + * @http.response.details + + + {{#responses}} + + {{/responses}} +
Status Code Description Response Headers
{{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}}
+ {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + {{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}} ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException { Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set @@ -61,12 +124,13 @@ public class {{classname}} { } {{/required}}{{/allParams}} // create path and map variables - String localVarPath = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}} + String localVarPath = "{{{path}}}"{{#pathParams}} .replaceAll("\\{" + "{{baseName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; // query params {{javaUtilPrefix}}List localVarQueryParams = new {{javaUtilPrefix}}ArrayList(); {{javaUtilPrefix}}Map localVarHeaderParams = new {{javaUtilPrefix}}HashMap(); + {{javaUtilPrefix}}Map localVarCookieParams = new {{javaUtilPrefix}}HashMap(); {{javaUtilPrefix}}Map localVarFormParams = new {{javaUtilPrefix}}HashMap(); {{#queryParams}} @@ -77,6 +141,10 @@ public class {{classname}} { localVarHeaderParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); {{/headerParams}} + {{#cookieParams}}if ({{paramName}} != null) + localVarCookieParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); + {{/cookieParams}} + {{#formParams}}if ({{paramName}} != null) localVarFormParams.put("{{baseName}}", {{paramName}}); {{/formParams}} @@ -95,11 +163,100 @@ public class {{classname}} { {{#returnType}} GenericType<{{{returnType}}}> localVarReturnType = new GenericType<{{{returnType}}}>() {}; - return apiClient.invokeAPI(localVarPath, "{{httpMethod}}", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - {{/returnType}}{{^returnType}} - apiClient.invokeAPI(localVarPath, "{{httpMethod}}", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + {{/returnType}} + return apiClient.invokeAPI("{{classname}}.{{operationId}}", localVarPath, "{{httpMethod}}", localVarQueryParams, localVarPostBody, + localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, + localVarAuthNames, {{#returnType}}localVarReturnType{{/returnType}}{{^returnType}}null{{/returnType}}, {{#bodyParam}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/bodyParam}}{{^bodyParam}}false{{/bodyParam}}); + } + {{#vendorExtensions.x-group-parameters}} + + public class API{{operationId}}Request { + {{#allParams}} + private {{#isRequired}}final {{/isRequired}}{{{dataType}}} {{paramName}}; + {{/allParams}} + + private API{{operationId}}Request({{#pathParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/pathParams}}) { + {{#pathParams}} + this.{{paramName}} = {{paramName}}; + {{/pathParams}} + } + {{#allParams}} + {{^isPathParam}} + + /** + * Set {{paramName}} + * @param {{paramName}} {{description}} ({{^required}}optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}{{/isContainer}}{{/required}}{{#required}}required{{/required}}) + * @return API{{operationId}}Request + */ + public API{{operationId}}Request {{paramName}}({{{dataType}}} {{paramName}}) { + this.{{paramName}} = {{paramName}}; + return this; + } + {{/isPathParam}} + {{/allParams}} + + /** + * Execute {{operationId}} request + {{#returnType}}* @return {{.}}{{/returnType}} + * @throws ApiException if fails to make API call + {{#responses.0}} + * @http.response.details + + + {{#responses}} + + {{/responses}} +
Status Code Description Response Headers
{{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}}
+ {{/responses.0}} + {{#isDeprecated}}* @deprecated{{/isDeprecated}} + */ + {{#isDeprecated}}@Deprecated{{/isDeprecated}} + public {{#returnType}}{{{.}}}{{/returnType}}{{^returnType}}void{{/returnType}} execute() throws ApiException { + {{#returnType}}return {{/returnType}}this.executeWithHttpInfo().getData(); + } + + /** + * Execute {{operationId}} request with HTTP info returned + * @return ApiResponse<{{#returnType}}{{.}}{{/returnType}}{{^returnType}}Void{{/returnType}}> + * @throws ApiException if fails to make API call + {{#responses.0}} + * @http.response.details + + + {{#responses}} + + {{/responses}} +
Status Code Description Response Headers
{{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}}
+ {{/responses.0}} + {{#isDeprecated}} + * @deprecated{{/isDeprecated}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public ApiResponse<{{#returnType}}{{{.}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> executeWithHttpInfo() throws ApiException { + return {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + } + } + + /** + * {{summary}} + * {{notes}}{{#pathParams}} + * @param {{paramName}} {{description}} (required){{/pathParams}} + * @return {{operationId}}Request + * @throws ApiException if fails to make API call + {{#isDeprecated}}* @deprecated{{/isDeprecated}} + {{#externalDocs}}* {{description}} + * @see {{summary}} Documentation{{/externalDocs}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public API{{operationId}}Request {{operationId}}({{#pathParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/pathParams}}) throws ApiException { + return new API{{operationId}}Request({{#pathParams}}{{paramName}}{{^-last}}, {{/-last}}{{/pathParams}}); } + {{/vendorExtensions.x-group-parameters}} {{/operation}} } {{/operations}} diff --git a/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/build.gradle.mustache b/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/build.gradle.mustache index c76ec3218088..378de9fb1e1f 100644 --- a/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/build.gradle.mustache +++ b/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/build.gradle.mustache @@ -1,5 +1,3 @@ -//overloaded template file within library folder to add this comment - apply plugin: 'idea' apply plugin: 'eclipse' @@ -8,11 +6,12 @@ version = '{{artifactVersion}}' buildscript { repositories { + maven { url "https://repo1.maven.org/maven2" } jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:1.5.+' - classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + classpath 'com.android.tools.build:gradle:2.3.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' } } @@ -27,18 +26,13 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'com.github.dcendents.android-maven' android { - compileSdkVersion 23 - buildToolsVersion '23.0.2' + compileSdkVersion 25 + buildToolsVersion '25.0.2' defaultConfig { minSdkVersion 14 - targetSdkVersion 23 + targetSdkVersion 25 } compileOptions { - {{#supportJava6}} - sourceCompatibility JavaVersion.VERSION_1_6 - targetCompatibility JavaVersion.VERSION_1_6 - {{/supportJava6}} - {{^supportJava6}} {{#java8}} sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 @@ -47,7 +41,6 @@ if(hasProperty('target') && target == 'android') { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 {{/java8}} - {{/supportJava6}} } // Rename the aar correctly @@ -91,11 +84,6 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - {{#supportJava6}} - sourceCompatibility = JavaVersion.VERSION_1_6 - targetCompatibility = JavaVersion.VERSION_1_6 - {{/supportJava6}} - {{^supportJava6}} {{#java8}} sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 @@ -104,7 +92,6 @@ if(hasProperty('target') && target == 'android') { sourceCompatibility = JavaVersion.VERSION_1_7 targetCompatibility = JavaVersion.VERSION_1_7 {{/java8}} - {{/supportJava6}} install { repositories.mavenInstaller { @@ -119,38 +106,61 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.5.8" - jackson_version = "2.7.5" - jersey_version = "2.22.2" - {{^java8}} - jodatime_version = "2.9.4" - {{/java8}} - {{#supportJava6}} - commons_io_version=2.5 - commons_lang3_version=3.5 - {{/supportJava6}} - junit_version = "4.13" + swagger_annotations_version = "1.5.22" + jackson_version = "2.10.5" + jackson_databind_version = "2.10.5.1" + {{#openApiNullable}} + jackson_databind_nullable_version = "0.2.1" + {{/openApiNullable}} + jersey_version = "2.27" + junit_version = "4.13.1" + {{#threetenbp}} + threetenbp_version = "2.9.10" + {{/threetenbp}} + {{#hasOAuthMethods}} + scribejava_apis_version = "6.9.0" + {{/hasOAuthMethods}} + {{#hasHttpSignatureMethods}} + tomitribe_http_signatures_version = "1.5" + {{/hasHttpSignatureMethods}} } dependencies { implementation "io.swagger:swagger-annotations:$swagger_annotations_version" + implementation "com.google.code.findbugs:jsr305:3.0.2" implementation "org.glassfish.jersey.core:jersey-client:$jersey_version" + implementation "org.glassfish.jersey.inject:jersey-hk2:$jersey_version" implementation "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version" implementation "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_version" + implementation "org.glassfish.jersey.connectors:jersey-apache-connector:$jersey_version" implementation "com.fasterxml.jackson.core:jackson-core:$jackson_version" implementation "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" - implementation "com.fasterxml.jackson.core:jackson-databind:$jackson_version" + implementation "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version" + {{#openApiNullable}} + implementation "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" + {{/openApiNullable}} + {{#joda}} + implementation "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" + {{/joda}} {{#java8}} implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" {{/java8}} + {{#hasOAuthMethods}} + implementation "com.github.scribejava:scribejava-apis:$scribejava_apis_version" + {{/hasOAuthMethods}} + {{#hasHttpSignatureMethods}} + implementation "org.tomitribe:tomitribe-http-signatures:$tomitribe_http_signatures_version" + {{/hasHttpSignatureMethods}} + {{#threetenbp}} + implementation "com.github.joschi.jackson:jackson-datatype-threetenbp:$threetenbp_version" + {{/threetenbp}} {{^java8}} - implementation "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" - implementation "joda-time:joda-time:$jodatime_version" implementation "com.brsanthu:migbase64:2.2" {{/java8}} - {{#supportJava6}} - implementation "commons-io:commons-io:$commons_io_version" - implementation "org.apache.commons:commons-lang3:$commons_lang3_version" - {{/supportJava6}} + implementation 'javax.annotation:javax.annotation-api:1.3.2' testImplementation "junit:junit:$junit_version" } + +javadoc { + options.tags = [ "http.response.details:a:Http Response Details" ] +} diff --git a/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/build.sbt.mustache b/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/build.sbt.mustache index 1049751cf3a4..9823c3c657e9 100644 --- a/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/build.sbt.mustache +++ b/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/build.sbt.mustache @@ -1,5 +1,3 @@ -//overloaded template file within library folder to add this comment - lazy val root = (project in file(".")). settings( organization := "{{groupId}}", @@ -11,26 +9,35 @@ lazy val root = (project in file(".")). publishArtifact in (Compile, packageDoc) := false, resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( - "io.swagger" % "swagger-annotations" % "1.5.8", - "org.glassfish.jersey.core" % "jersey-client" % "2.22.2", - "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.22.2", - "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.2", - "com.fasterxml.jackson.core" % "jackson-core" % "2.7.5", - "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5", - "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.5", + "io.swagger" % "swagger-annotations" % "1.5.22", + "org.glassfish.jersey.core" % "jersey-client" % "2.27", + "org.glassfish.jersey.inject" % "jersey-hk2" % "2.27", + "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.27", + "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.27", + "org.glassfish.jersey.connectors" % "jersey-apache-connector" % "2.27", + "com.fasterxml.jackson.core" % "jackson-core" % "2.10.5" % "compile", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.5.1" % "compile", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.5.1" % "compile", + {{#joda}} + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.10" % "compile", + {{/joda}} {{#java8}} - "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.7.5", - {{/java8}} - {{^java8}} - "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.7.5", - "joda-time" % "joda-time" % "2.9.4", + "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.9.10" % "compile", + {{/java8}} + {{#threetenbp}} + "com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.9.10" % "compile", + {{/threetenbp}} + {{#hasOAuthMethods}} + "com.github.scribejava" % "scribejava-apis" % "6.9.0" % "compile", + {{/hasOAuthMethods}} + {{#hasHttpSignatureMethods}} + "org.tomitribe" % "tomitribe-http-signatures" % "1.5" % "compile", + {{/hasHttpSignatureMethods}} + {{^java8}} "com.brsanthu" % "migbase64" % "2.2", {{/java8}} - {{#supportJava6}} - "org.apache.commons" % "commons-lang3" % "3.5", - "commons-io" % "commons-io" % "2.5", - {{/supportJava6}} - "junit" % "junit" % "4.13" % "test", + "javax.annotation" % "javax.annotation-api" % "1.3.2" % "compile", + "junit" % "junit" % "4.13.1" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" ) ) diff --git a/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/pom.mustache b/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/pom.mustache index 3e1a02651469..f36f0cd88178 100644 --- a/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/pom.mustache +++ b/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/pom.mustache @@ -1,5 +1,3 @@ -//overloaded template file within library folder to add this comment - 4.0.0 @@ -15,6 +13,13 @@ {{scmDeveloperConnection}} {{scmUrl}} +{{#parentOverridden}} + + {{{parentGroupId}}} + {{{parentArtifactId}}} + {{{parentVersion}}} + +{{/parentOverridden}} @@ -58,7 +63,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.12 + 3.0.0-M4 @@ -68,7 +73,8 @@ -Xms512m -Xmx1500m methods - pertest + 10 + false @@ -106,6 +112,7 @@ org.codehaus.mojo build-helper-maven-plugin + 1.10 add_sources @@ -115,8 +122,7 @@ - - src/main/java + src/main/java @@ -128,8 +134,7 @@ - - src/test/java + src/test/java @@ -138,7 +143,7 @@ org.apache.maven.plugins maven-compiler-plugin - 2.5.1 + 3.8.1 {{#java8}} 1.8 @@ -148,15 +153,19 @@ 1.7 1.7 {{/java8}} + true + 128m + 512m + + -Xlint:all + -J-Xss4m + org.apache.maven.plugins maven-javadoc-plugin 3.1.1 - - none - attach-javadocs @@ -165,6 +174,22 @@ + + none + {{#java8}} + 1.8 + {{/java8}} + {{^java8}} + 1.7 + {{/java8}} + + + http.response.details + a + Http Response Details: + + + org.apache.maven.plugins @@ -210,7 +235,14 @@ io.swagger swagger-annotations - ${swagger-core-version} + ${swagger-annotations-version} + + + + + com.google.code.findbugs + jsr305 + 3.0.2 @@ -219,6 +251,11 @@ jersey-client ${jersey-version} + + org.glassfish.jersey.inject + jersey-hk2 + ${jersey-version} + org.glassfish.jersey.media jersey-media-multipart @@ -244,49 +281,86 @@ com.fasterxml.jackson.core jackson-databind + ${jackson-databind-version} + + {{#openApiNullable}} + + org.openapitools + jackson-databind-nullable + ${jackson-databind-nullable-version} + + {{/openApiNullable}} + {{#withXml}} + + + org.glassfish.jersey.media + jersey-media-jaxb + ${jersey-version} + + {{/withXml}} + {{#joda}} + + com.fasterxml.jackson.datatype + jackson-datatype-joda ${jackson-version} + {{/joda}} {{#java8}} - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - ${jackson-version} - + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + {{/java8}} + {{#threetenbp}} + + com.github.joschi.jackson + jackson-datatype-threetenbp + ${threetenbp-version} + + {{/threetenbp}} {{^java8}} - - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson-version} - - - joda-time - joda-time - ${jodatime-version} - - - - - com.brsanthu - migbase64 - 2.2 - + + + com.brsanthu + migbase64 + 2.2 + {{/java8}} - - {{#supportJava6}} - - org.apache.commons - commons-lang3 - ${commons_lang3_version} - - - - commons-io - commons-io - ${commons_io_version} - - {{/supportJava6}} - + {{#hasHttpSignatureMethods}} + + org.tomitribe + tomitribe-http-signatures + ${http-signature-version} + + {{/hasHttpSignatureMethods}} + {{#hasOAuthMethods}} + + com.github.scribejava + scribejava-apis + ${scribejava-apis-version} + + {{/hasOAuthMethods}} + {{#useBeanValidation}} + + + javax.validation + validation-api + 1.1.0.Final + provided + + {{/useBeanValidation}} + + javax.annotation + javax.annotation-api + ${javax-annotation-version} + provided + + + org.glassfish.jersey.connectors + jersey-apache-connector + ${jersey-version} + junit @@ -297,17 +371,21 @@ UTF-8 - 1.5.18 - 2.22.2 - 2.8.9 - {{^java8}} - 2.9.4 - {{/java8}} - {{#supportJava6}} - 2.5 - 3.5 - {{/supportJava6}} - 1.0.0 - 4.13 + 1.6.1 + 2.30.1 + 2.10.5 + 2.10.5.1 + 0.2.1 + {{#threetenbp}} + 2.9.10 + {{/threetenbp}} + 1.3.2 + 4.13.1 + {{#hasHttpSignatureMethods}} + 1.5 + {{/hasHttpSignatureMethods}} + {{#hasOAuthMethods}} + 6.9.0 + {{/hasOAuthMethods}} diff --git a/modules/openapi-generator/src/test/resources/2_0/templates/Java/model.mustache b/modules/openapi-generator/src/test/resources/2_0/templates/Java/model.mustache index 07adf19139f6..8fd078eb3d62 100644 --- a/modules/openapi-generator/src/test/resources/2_0/templates/Java/model.mustache +++ b/modules/openapi-generator/src/test/resources/2_0/templates/Java/model.mustache @@ -1,31 +1,54 @@ -//overloaded main template file to add this comment - {{>licenseInfo}} package {{package}}; -{{^supportJava6}} +{{#useReflectionEqualsHashCode}} +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +{{/useReflectionEqualsHashCode}} import java.util.Objects; -{{/supportJava6}} -{{#supportJava6}} -import org.apache.commons.lang3.ObjectUtils; -{{/supportJava6}} +import java.util.Arrays; {{#imports}} import {{import}}; {{/imports}} {{#serializableModel}} import java.io.Serializable; {{/serializableModel}} +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +{{#withXml}} +import com.fasterxml.jackson.dataformat.xml.annotation.*; +{{/withXml}} +{{/jackson}} +{{#withXml}} +import javax.xml.bind.annotation.*; +{{/withXml}} +{{#jsonb}} +import java.lang.reflect.Type; +import javax.json.bind.annotation.JsonbTypeDeserializer; +import javax.json.bind.annotation.JsonbTypeSerializer; +import javax.json.bind.serializer.DeserializationContext; +import javax.json.bind.serializer.JsonbDeserializer; +import javax.json.bind.serializer.JsonbSerializer; +import javax.json.bind.serializer.SerializationContext; +import javax.json.stream.JsonGenerator; +import javax.json.stream.JsonParser; +import javax.json.bind.annotation.JsonbProperty; +{{/jsonb}} {{#parcelableModel}} import android.os.Parcelable; import android.os.Parcel; {{/parcelableModel}} {{#useBeanValidation}} import javax.validation.constraints.*; +import javax.validation.Valid; {{/useBeanValidation}} +{{#performBeanValidation}} +import org.hibernate.validator.constraints.*; +{{/performBeanValidation}} {{#models}} {{#model}} -{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>pojo}}{{/isEnum}} +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#vendorExtensions.x-is-one-of-interface}}{{>oneof_interface}}{{/vendorExtensions.x-is-one-of-interface}}{{^vendorExtensions.x-is-one-of-interface}}{{>pojo}}{{/vendorExtensions.x-is-one-of-interface}}{{/isEnum}} {{/model}} {{/models}} diff --git a/modules/openapi-generator/src/test/resources/3_0/issue_9447.yaml b/modules/openapi-generator/src/test/resources/3_0/issue_9447.yaml new file mode 100644 index 000000000000..7cfa010c37f8 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/issue_9447.yaml @@ -0,0 +1,106 @@ +openapi: 3.0.1 +info: + title: OpenAPI Petstore + description: "sample to vet integer handling" + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.0 +servers: + - url: http://petstore.swagger.io:80/v2 +tags: [] +paths: + /UnboundedInteger: + post: + operationId: UnboundedInteger + parameters: + - name: UnboundedInteger + in: path + required: true + schema: + type: integer + requestBody: + content: + application/json: + schema: + type: integer + required: true + responses: + 200: + description: success + content: + application/json: + schema: + type: integer + /Int64: + post: + operationId: Int64 + parameters: + - name: Int64 + in: path + required: true + schema: + type: integer + format: int64 + requestBody: + content: + application/json: + schema: + type: integer + format: int64 + required: true + responses: + 200: + description: success + content: + application/json: + schema: + type: integer + format: int64 + /Int32: + post: + operationId: Int32 + parameters: + - name: Int32 + in: path + required: true + schema: + type: integer + format: int32 + requestBody: + content: + application/json: + schema: + type: integer + format: int32 + required: true + responses: + 200: + description: success + content: + application/json: + schema: + type: integer + format: int32 +components: + schemas: + UnboundedInteger: + type: integer + Int32: + type: integer + format: int32 + Int64: + type: integer + format: int64 + ObjectModelWithIntegerProps: + type: object + properties: + UnboundedInteger: + type: integer + Int32: + type: integer + format: int32 + Int64: + type: integer + format: int64 + securitySchemes: {} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml index 431dd54b0310..9dac77c2fa41 100644 --- a/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -1008,7 +1008,7 @@ paths: tags: - fake description: >- - For this test, the body for this request much reference a schema named + For this test, the body for this request must reference a schema named `File`. operationId: testBodyWithFileSchema responses: @@ -1020,6 +1020,25 @@ paths: schema: $ref: '#/components/schemas/FileSchemaTestClass' required: true + /fake/body-with-binary: + put: + tags: + - fake + description: >- + For this test, the body has to be a binary file. + operationId: testBodyWithBinary + responses: + '200': + description: Success + requestBody: + content: + image/png: + schema: + type: string + nullable: true + format: binary + description: image to upload + required: true /fake/test-query-paramters: put: tags: @@ -1030,6 +1049,7 @@ paths: - name: pipe in: query required: true + style: pipeDelimited schema: type: array items: diff --git a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml index 9e6502ca756c..4efbc9cc0283 100644 --- a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml @@ -692,12 +692,14 @@ paths: type: number format: float maximum: 987.6 + exclusiveMaximum: true double: description: None type: number format: double minimum: 67.8 maximum: 123.4 + exclusiveMaximum: true string: description: None type: string @@ -1286,11 +1288,11 @@ paths: application/json: schema: $ref: '#/components/schemas/HealthCheckResult' - /fake/getInlineAdditionalPropertiesRefPayload: - get: + /fake/postInlineAdditionalPropertiesRefPayload: + post: tags: - fake - operationId: getInlineAdditionalPropertiesRefPayload + operationId: postInlineAdditionalPropertiesRefPayload responses: 200: description: InlineAdditionalPropertiesRefPayload @@ -1303,11 +1305,11 @@ paths: application/json: schema: $ref: '#/components/schemas/InlineAdditionalPropertiesRefPayload' - /fake/getInlineAdditionalPropertiesPayload: - get: + /fake/postInlineAdditionalPropertiesPayload: + post: tags: - fake - operationId: getInlineAdditionalPropertiesPayload + operationId: postInlineAdditionalPropertiesPayload responses: 200: description: InlineAdditionalPropertiesPayload @@ -1644,7 +1646,6 @@ components: Cat: allOf: - $ref: '#/components/schemas/Animal' - - $ref: '#/components/schemas/Address' - type: object properties: declawed: @@ -2002,6 +2003,8 @@ components: properties: my_number: $ref: '#/definitions/NumberWithValidations' + my_readonly: + $ref: '#/definitions/Readonly' my_string: $ref: '#/definitions/String' my_boolean: @@ -2010,6 +2013,12 @@ components: type: number minimum: 10 maximum: 20 + Readonly: + type: object + readOnly: true + properties: + name: + type: string ComposedOneOfNumberWithValidations: description: this is a model that allows payloads of type object or number oneOf: @@ -2097,6 +2106,9 @@ components: items: type: object nullable: true + object_nullable: + type: object + nullable: true object_nullable_prop: type: object nullable: true @@ -2114,18 +2126,27 @@ components: type: object nullable: true additionalProperties: - type: object nullable: true + ComposedSchemaWithPropsAndNoAddProps: + properties: + color: + type: string + allOf: + - $ref: '#/components/schemas/Tag' + # Below additionalProperties is set to false to validate the use + # case when a composed schema has additionalProperties set to false. + # This definition will only allow in object payloads that set color and no other properties because + # additionalProperties are evaluated at the schema level and do not include composed schema + # properties. Only color is defined here, all others are additional + additionalProperties: false fruit: + description: a schema that tests oneOf and includes a schema level property properties: color: type: string oneOf: - $ref: '#/components/schemas/apple' - $ref: '#/components/schemas/banana' - # Below additionalProperties is set to false to validate the use - # case when a composed schema has additionalProperties set to false. - additionalProperties: false apple: type: object properties: @@ -2135,12 +2156,16 @@ components: origin: type: string pattern: /^[A-Z\s]*$/i + required: + - cultivar nullable: true banana: type: object properties: lengthCm: type: number + required: + - lengthCm mammal: oneOf: - $ref: '#/components/schemas/whale' @@ -2200,13 +2225,13 @@ components: anyOf: - $ref: '#/components/schemas/apple' - $ref: '#/components/schemas/banana' - additionalProperties: false fruitReq: + description: a schema where additionalProperties is on in the composed schema and off in the oneOf object schemas + also, this schem accepts null as a value oneOf: - type: 'null' - $ref: '#/components/schemas/appleReq' - $ref: '#/components/schemas/bananaReq' - additionalProperties: false appleReq: type: object properties: @@ -2310,7 +2335,6 @@ components: allOf: - $ref: '#/components/schemas/ShapeInterface' - $ref: '#/components/schemas/TriangleInterface' - additionalProperties: false ScaleneTriangle: allOf: - $ref: '#/components/schemas/ShapeInterface' @@ -2398,3 +2422,26 @@ components: items: type: string nullable: true + Mole: + type: object + required: + - blind + - smell + - hearing + properties: + blind: + type: boolean + readOnly: true + smell: + type: string + readOnly: false + touch: + type: boolean + readOnly: true + taste: + type: string + readOnly: false + hearing: + type: boolean + seeingGhosts: + type: boolean \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/type_mapping_test.yaml b/modules/openapi-generator/src/test/resources/3_0/type_mapping_test.yaml new file mode 100644 index 000000000000..4954771e8948 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/type_mapping_test.yaml @@ -0,0 +1,38 @@ +openapi: 3.0.0 +info: + title: Sample API to test type mapping + description: API description in Markdown. + version: 1.0.0 +paths: + /animals: + get: + summary: Returns all animals. + description: Optional extended description in Markdown. + parameters: + - in: query + name: parameter_type_mapping + schema: + type: string + format: special + responses: + 200: + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/Animal' +components: + schemas: + Animal: + type: object + required: + - className + properties: + className: + type: string + color: + type: string + default: red + mapping_test: + type: string + format: special diff --git a/modules/openapi-generator/src/test/resources/3_0/wsdl/petstore.yaml b/modules/openapi-generator/src/test/resources/3_0/wsdl/petstore.yaml new file mode 100644 index 000000000000..83ccdf1c6112 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/wsdl/petstore.yaml @@ -0,0 +1,728 @@ +openapi: 3.0.1 +info: + title: Swagger Petstore + description: 'This is a sample server Petstore server. You can find out more about Swagger + at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For + this sample, you can use the api key `special-key` to test the authorization filters.' + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.0 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: +- url: https://petstore.swagger.io/v2 +- url: http://petstore.swagger.io/v2 +tags: +- name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io +- name: store + description: Access to Petstore orders +- name: user + description: Operations about user + externalDocs: + description: Find out more about our store + url: http://swagger.io +paths: + /pet: + put: + tags: + - pet + summary: Update an existing pet + operationId: updatePet + requestBody: + description: Pet object that needs to be added to the store + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + required: true + responses: + 400: + description: Invalid ID supplied + content: {} + 404: + description: Pet not found + content: {} + 405: + description: Validation exception + content: {} + security: + - petstore_auth: + - write:pets + - read:pets + x-codegen-request-body-name: body + post: + tags: + - pet + summary: Add a new pet to the store + operationId: addPet + requestBody: + description: Pet object that needs to be added to the store + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + required: true + responses: + 405: + description: Invalid input + content: {} + security: + - petstore_auth: + - write:pets + - read:pets + x-codegen-request-body-name: body + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: true + schema: + type: array + items: + type: string + default: available + enum: + - available + - pending + - sold + responses: + 200: + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + 400: + description: Invalid status value + content: {} + security: + - petstore_auth: + - write:pets + - read:pets + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: Muliple tags can be provided with comma separated strings. Use tag1, + tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: true + schema: + type: array + items: + type: string + responses: + 200: + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + 400: + description: Invalid tag value + content: {} + deprecated: true + security: + - petstore_auth: + - write:pets + - read:pets + /pet/{petId}: + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + 200: + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + 400: + description: Invalid ID supplied + content: {} + 404: + description: Pet not found + content: {} + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + requestBody: + content: + application/x-www-form-urlencoded: + schema: + properties: + name: + type: string + description: Updated name of the pet + status: + type: string + description: Updated status of the pet + responses: + 405: + description: Invalid input + content: {} + security: + - petstore_auth: + - write:pets + - read:pets + delete: + tags: + - pet + summary: Deletes a pet + operationId: deletePet + parameters: + - name: api_key + in: header + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + 400: + description: Invalid ID supplied + content: {} + 404: + description: Pet not found + content: {} + security: + - petstore_auth: + - write:pets + - read:pets + /pet/{petId}/uploadImage: + post: + tags: + - pet + summary: uploads an image + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + requestBody: + content: + multipart/form-data: + schema: + properties: + additionalMetadata: + type: string + description: Additional data to pass to server + file: + type: string + description: file to upload + format: binary + responses: + 200: + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - write:pets + - read:pets + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + 200: + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + operationId: placeOrder + requestBody: + description: order placed for purchasing the pet + content: + '*/*': + schema: + $ref: '#/components/schemas/Order' + required: true + responses: + 200: + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + 400: + description: Invalid Order + content: {} + x-codegen-request-body-name: body + /store/order/{orderId}: + get: + tags: + - store + summary: Find purchase order by ID + description: For valid response try integer IDs with value >= 1 and <= 10. Other + values will generated exceptions + operationId: getOrderById + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + schema: + maximum: 10.0 + minimum: 1.0 + type: integer + format: int64 + responses: + 200: + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + 400: + description: Invalid ID supplied + content: {} + 404: + description: Order not found + content: {} + delete: + tags: + - store + summary: Delete purchase order by ID + description: For valid response try integer IDs with positive integer value. Negative + or non-integer values will generate API errors + operationId: deleteOrder + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + minimum: 1.0 + type: integer + format: int64 + responses: + 400: + description: Invalid ID supplied + content: {} + 404: + description: Order not found + content: {} + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + requestBody: + description: Created user object + content: + '*/*': + schema: + $ref: '#/components/schemas/User' + required: true + responses: + default: + description: successful operation + content: {} + x-codegen-request-body-name: body + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + operationId: createUsersWithArrayInput + requestBody: + description: List of user object + content: + '*/*': + schema: + type: array + items: + $ref: '#/components/schemas/User' + required: true + responses: + default: + description: successful operation + content: {} + x-codegen-request-body-name: body + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + operationId: createUsersWithListInput + requestBody: + description: List of user object + content: + '*/*': + schema: + type: array + items: + $ref: '#/components/schemas/User' + required: true + responses: + default: + description: successful operation + content: {} + x-codegen-request-body-name: body + /user/login: + get: + tags: + - user + summary: Logs user into the system + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + 200: + description: successful operation + headers: + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when token expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + 400: + description: Invalid username/password supplied + content: {} + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + operationId: logoutUser + responses: + default: + description: successful operation + content: {} + /user/{username}: + get: + tags: + - user + summary: Get user by user name + operationId: getUserByName + parameters: + - name: username + in: path + description: 'The name that needs to be fetched. Use user1 for testing. ' + required: true + schema: + type: string + responses: + 200: + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + 400: + description: Invalid username supplied + content: {} + 404: + description: User not found + content: {} + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - name: username + in: path + description: name that need to be updated + required: true + schema: + type: string + requestBody: + description: Updated user object + content: + '*/*': + schema: + $ref: '#/components/schemas/User' + required: true + responses: + 400: + description: Invalid user supplied + content: {} + 404: + description: User not found + content: {} + x-codegen-request-body-name: body + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + 400: + description: Invalid username supplied + content: {} + 404: + description: User not found + content: {} +components: + schemas: + Order: + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Category + User: + type: object + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + description: User Status + format: int32 + xml: + name: User + Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + required: + - name + - photoUrls + type: object + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: http://petstore.swagger.io/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + api_key: + type: apiKey + name: api_key + in: header diff --git a/new.sh b/new.sh index 12cfec8cb579..7d33be840e55 100755 --- a/new.sh +++ b/new.sh @@ -178,7 +178,7 @@ public class ${lang_classname} extends DefaultCodegen implements CodegenConfig { outputFolder = "generated-code" + File.separator + "${gen_name_camel}"; modelTemplateFiles.put("model.mustache", ".zz"); apiTemplateFiles.put("api.mustache", ".zz"); - embeddedTemplateDir = templateDir = "${gen_name_camel}-${gen_type}"; + embeddedTemplateDir = templateDir = "${gen_name_camel}"; apiPackage = "Apis"; modelPackage = "Models"; supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); @@ -191,17 +191,17 @@ EOF echo -e "\norg.openapitools.codegen.languages.${lang_classname}" >> "${root}/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig" # Step 3: Create resource files -mkdir -p "${root}/modules/openapi-generator/src/main/resources/${gen_name_camel}-${gen_type}" -echo "Creating modules/openapi-generator/src/main/resources/${gen_name_camel}-${gen_type}/README.mustache" && \ - touch "${root}/modules/openapi-generator/src/main/resources/${gen_name_camel}-${gen_type}/README.mustache" -echo "Creating modules/openapi-generator/src/main/resources/${gen_name_camel}-${gen_type}/model.mustache" && \ - touch "${root}/modules/openapi-generator/src/main/resources/${gen_name_camel}-${gen_type}/model.mustache" -echo "Creating modules/openapi-generator/src/main/resources/${gen_name_camel}-${gen_type}/api.mustache" && \ - touch "${root}/modules/openapi-generator/src/main/resources/${gen_name_camel}-${gen_type}/api.mustache" +mkdir -p "${root}/modules/openapi-generator/src/main/resources/${gen_name_camel}" +echo "Creating modules/openapi-generator/src/main/resources/${gen_name_camel}/README.mustache" && \ + touch "${root}/modules/openapi-generator/src/main/resources/${gen_name_camel}/README.mustache" +echo "Creating modules/openapi-generator/src/main/resources/${gen_name_camel}/model.mustache" && \ + touch "${root}/modules/openapi-generator/src/main/resources/${gen_name_camel}/model.mustache" +echo "Creating modules/openapi-generator/src/main/resources/${gen_name_camel}/api.mustache" && \ + touch "${root}/modules/openapi-generator/src/main/resources/${gen_name_camel}/api.mustache" # Step 4: Create generation config scripts -echo "Creating bin/configs/${gen_name_camel}-${gen_type}-petstore-new.yaml" -cat > "${root}/bin/configs/${gen_name_camel}-${gen_type}-petstore-new.yaml"< "${root}/bin/configs/${gen_name_camel}-petstore-new.yaml"<pom openapi-generator-project - 5.1.1-SNAPSHOT + 5.2.0-SNAPSHOT https://github.com/openapitools/openapi-generator @@ -1188,17 +1188,20 @@ samples/server/petstore/python-aiohttp samples/server/petstore/python-aiohttp-srclayout samples/server/petstore/python-flask + samples/server/petstore/rust-server samples/client/petstore/ruby-faraday samples/client/petstore/ruby + + samples/client/petstore/cpp-qt samples/client/petstore/rust samples/client/petstore/rust/reqwest/petstore samples/client/petstore/rust/reqwest/petstore-async @@ -1206,6 +1209,7 @@ samples/client/petstore/javascript-flowtyped samples/client/petstore/python + samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent samples/client/petstore/python-legacy samples/client/petstore/python-asyncio samples/client/petstore/python-tornado @@ -1352,6 +1356,7 @@ samples/client/petstore/javascript-promise-es6 samples/server/petstore/go-api-server samples/server/petstore/go-gin-api-server + samples/server/petstore/go-echo-server @@ -1413,18 +1418,40 @@ - samples/openapi3/client/petstore/dart2/petstore_client_lib - samples/openapi3/client/petstore/dart2/petstore - samples/openapi3/client/petstore/dart-dio/petstore_client_lib - samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake - samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake - samples/client/petstore/R + + samples.dart-2.13 + + + env + samples.dart-2.13 + + + + samples/openapi3/client/petstore/dart2/petstore_client_lib + samples/openapi3/client/petstore/dart2/petstore + + samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake + + + + samples.dart-2.10 + + + env + samples.dart-2.10 + + + + samples/openapi3/client/petstore/dart-dio/petstore_client_lib + samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake + + samples.ios @@ -1470,15 +1497,24 @@ samples/client/petstore/objc/core-data/SwaggerClientTests--> + + openapi-generator + + true + + !integration-test + + + + modules/openapi-generator-core + modules/openapi-generator + modules/openapi-generator-cli + modules/openapi-generator-maven-plugin + modules/openapi-generator-gradle-plugin + modules/openapi-generator-online + + - - modules/openapi-generator-core - modules/openapi-generator - modules/openapi-generator-cli - modules/openapi-generator-maven-plugin - modules/openapi-generator-gradle-plugin - modules/openapi-generator-online - target/site diff --git a/samples/client/petstore/R/.openapi-generator/VERSION b/samples/client/petstore/R/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/R/.openapi-generator/VERSION +++ b/samples/client/petstore/R/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/R/R/category.R b/samples/client/petstore/R/R/category.R index 7c74320d1acf..059b64e37482 100644 --- a/samples/client/petstore/R/R/category.R +++ b/samples/client/petstore/R/R/category.R @@ -89,4 +89,3 @@ Category <- R6::R6Class( } ) ) - diff --git a/samples/client/petstore/R/R/model_api_response.R b/samples/client/petstore/R/R/model_api_response.R index c7cdbb76c2a4..a1c16133557b 100644 --- a/samples/client/petstore/R/R/model_api_response.R +++ b/samples/client/petstore/R/R/model_api_response.R @@ -111,4 +111,3 @@ ModelApiResponse <- R6::R6Class( } ) ) - diff --git a/samples/client/petstore/R/R/order.R b/samples/client/petstore/R/R/order.R index 3218835cc35c..d3e2e46b4937 100644 --- a/samples/client/petstore/R/R/order.R +++ b/samples/client/petstore/R/R/order.R @@ -62,6 +62,7 @@ Order <- R6::R6Class( self$`status` <- `status` } if (!is.null(`complete`)) { + stopifnot(is.logical(`complete`), length(`complete`) == 1) self$`complete` <- `complete` } }, @@ -156,9 +157,9 @@ Order <- R6::R6Class( if (!is.null(self$`complete`)) { sprintf( '"complete": - "%s" + %s ', - self$`complete` + tolower(self$`complete`) )} ) jsoncontent <- paste(jsoncontent, collapse = ",") @@ -176,4 +177,3 @@ Order <- R6::R6Class( } ) ) - diff --git a/samples/client/petstore/R/R/pet.R b/samples/client/petstore/R/R/pet.R index 509d16934e1f..1960b16906a0 100644 --- a/samples/client/petstore/R/R/pet.R +++ b/samples/client/petstore/R/R/pet.R @@ -181,4 +181,3 @@ Pet <- R6::R6Class( } ) ) - diff --git a/samples/client/petstore/R/R/tag.R b/samples/client/petstore/R/R/tag.R index 56b89c6b4254..ba2def34c43b 100644 --- a/samples/client/petstore/R/R/tag.R +++ b/samples/client/petstore/R/R/tag.R @@ -89,4 +89,3 @@ Tag <- R6::R6Class( } ) ) - diff --git a/samples/client/petstore/R/R/user.R b/samples/client/petstore/R/R/user.R index bf88bee40277..47ffaea0d88f 100644 --- a/samples/client/petstore/R/R/user.R +++ b/samples/client/petstore/R/R/user.R @@ -221,4 +221,3 @@ User <- R6::R6Class( } ) ) - diff --git a/samples/client/petstore/apex/.openapi-generator/VERSION b/samples/client/petstore/apex/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/apex/.openapi-generator/VERSION +++ b/samples/client/petstore/apex/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/bash/.openapi-generator/FILES b/samples/client/petstore/bash/.openapi-generator/FILES new file mode 100644 index 000000000000..918b7a49c26a --- /dev/null +++ b/samples/client/petstore/bash/.openapi-generator/FILES @@ -0,0 +1,59 @@ +Dockerfile +README.md +_petstore-cli +docs/$special[modelName].md +docs/200Response.md +docs/AdditionalPropertiesAnyType.md +docs/AdditionalPropertiesArray.md +docs/AdditionalPropertiesBoolean.md +docs/AdditionalPropertiesClass.md +docs/AdditionalPropertiesInteger.md +docs/AdditionalPropertiesNumber.md +docs/AdditionalPropertiesObject.md +docs/AdditionalPropertiesString.md +docs/Animal.md +docs/AnotherFakeApi.md +docs/ApiResponse.md +docs/ArrayOfArrayOfNumberOnly.md +docs/ArrayOfNumberOnly.md +docs/ArrayTest.md +docs/BigCat.md +docs/BigCatAllOf.md +docs/Capitalization.md +docs/Cat.md +docs/CatAllOf.md +docs/Category.md +docs/ClassModel.md +docs/Client.md +docs/Dog.md +docs/DogAllOf.md +docs/EnumArrays.md +docs/EnumClass.md +docs/EnumTest.md +docs/FakeApi.md +docs/FakeClassnameTags123Api.md +docs/File.md +docs/FileSchemaTestClass.md +docs/FormatTest.md +docs/HasOnlyReadOnly.md +docs/List.md +docs/MapTest.md +docs/MixedPropertiesAndAdditionalPropertiesClass.md +docs/Name.md +docs/NumberOnly.md +docs/Order.md +docs/OuterComposite.md +docs/OuterEnum.md +docs/Pet.md +docs/PetApi.md +docs/ReadOnlyFirst.md +docs/Return.md +docs/StoreApi.md +docs/Tag.md +docs/TypeHolderDefault.md +docs/TypeHolderExample.md +docs/User.md +docs/UserApi.md +docs/XmlItem.md +petstore-cli +petstore-cli.bash-completion diff --git a/samples/client/petstore/bash/.openapi-generator/VERSION b/samples/client/petstore/bash/.openapi-generator/VERSION index e4955748d3e7..6555596f9311 100644 --- a/samples/client/petstore/bash/.openapi-generator/VERSION +++ b/samples/client/petstore/bash/.openapi-generator/VERSION @@ -1 +1 @@ -4.2.2-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/bash/Dockerfile b/samples/client/petstore/bash/Dockerfile index 77df27f36614..451c6a916f96 100644 --- a/samples/client/petstore/bash/Dockerfile +++ b/samples/client/petstore/bash/Dockerfile @@ -1,7 +1,6 @@ -FROM ubuntu:16.10 +FROM alpine:3.12.0 -RUN apt-get update -y && apt-get full-upgrade -y -RUN apt-get install -y bash-completion zsh curl cowsay git vim bsdmainutils +RUN apk add --update --no-cache curl ca-certificates bash bash-completion zsh curl git vim ncurses util-linux ADD petstore-cli /usr/bin/petstore-cli ADD _petstore-cli /usr/local/share/zsh/site-functions/_petstore-cli @@ -30,7 +29,7 @@ RUN echo 'export PROMPT="[OpenAPI Petstore] \$ "' >> ~/.zshrc # # Setup a welcome message with basic instruction # -RUN echo 'cat << EOF\n\ +RUN echo -e 'echo "\ \n\ This Docker provides preconfigured environment for running the command\n\ line REST client for $(tput setaf 6)OpenAPI Petstore$(tput sgr0).\n\ @@ -41,7 +40,6 @@ $(tput setaf 3)PETSTORE_HOST$(tput sgr0) - server URL, e.g. https://example.com: $(tput setaf 3)PETSTORE_API_KEY$(tput sgr0) - access token, e.g. "ASDASHJDG63456asdASSD"\n\ $(tput setaf 3)PETSTORE_API_KEY$(tput sgr0) - access token, e.g. "ASDASHJDG63456asdASSD"\n\ $(tput setaf 3)PETSTORE_BASIC_AUTH$(tput sgr0) - basic authentication credentials, e.g.: "username:password"\n\ -$(tput setaf 3)PETSTORE_BASIC_AUTH$(tput sgr0) - basic authentication credentials, e.g.: "username:password"\n\ \n\ $(tput setaf 7)Basic usage:$(tput sgr0)\n\ \n\ @@ -57,7 +55,14 @@ $ petstore-cli -h\n\ By default you are logged into Zsh with full autocompletion for your REST API,\n\ but you can switch to Bash, where basic autocompletion is also supported.\n\ \n\ -EOF\n\ +"\ ' | tee -a ~/.bashrc ~/.zshrc -ENTRYPOINT ["zsh"] +# +# Poormans chsh & cleanup to make image as compact as possible +# + +RUN sed -i 's/root:x:0:0:root:\/root:\/bin\/ash/root:x:0:0:root:\/root:\/bin\/zsh/' /etc/passwd +RUN apk del git vim && rm -f /var/cache/apk/* + +ENTRYPOINT ["/bin/zsh"] diff --git a/samples/client/petstore/bash/README.md b/samples/client/petstore/bash/README.md index 8179fa5a2a91..a89e54917f43 100644 --- a/samples/client/petstore/bash/README.md +++ b/samples/client/petstore/bash/README.md @@ -101,8 +101,7 @@ All URIs are relative to */v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *AnotherFakeApi* | [**call123TestSpecialTags**](docs/AnotherFakeApi.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags -*DefaultApi* | [**fooGet**](docs/DefaultApi.md#fooget) | **GET** /foo | -*FakeApi* | [**fakeHealthGet**](docs/FakeApi.md#fakehealthget) | **GET** /fake/health | Health check endpoint +*FakeApi* | [**createXmlItem**](docs/FakeApi.md#createxmlitem) | **POST** /fake/create_xml_item | creates an XmlItem *FakeApi* | [**fakeOuterBooleanSerialize**](docs/FakeApi.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | *FakeApi* | [**fakeOuterCompositeSerialize**](docs/FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | *FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | @@ -111,9 +110,9 @@ Class | Method | HTTP request | Description *FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**testClientModel**](docs/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model *FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters -假端點 -偽のエンドポイント -가짜 엔드 포인트 + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 *FakeApi* | [**testEnumParameters**](docs/FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters *FakeApi* | [**testGroupParameters**](docs/FakeApi.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) *FakeApi* | [**testInlineAdditionalProperties**](docs/FakeApi.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties @@ -145,13 +144,23 @@ Class | Method | HTTP request | Description ## Documentation For Models + - [$special[modelName]](docs/$special[modelName].md) - [200Response](docs/200Response.md) + - [AdditionalPropertiesAnyType](docs/AdditionalPropertiesAnyType.md) + - [AdditionalPropertiesArray](docs/AdditionalPropertiesArray.md) + - [AdditionalPropertiesBoolean](docs/AdditionalPropertiesBoolean.md) - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [AdditionalPropertiesInteger](docs/AdditionalPropertiesInteger.md) + - [AdditionalPropertiesNumber](docs/AdditionalPropertiesNumber.md) + - [AdditionalPropertiesObject](docs/AdditionalPropertiesObject.md) + - [AdditionalPropertiesString](docs/AdditionalPropertiesString.md) - [Animal](docs/Animal.md) - [ApiResponse](docs/ApiResponse.md) - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [ArrayTest](docs/ArrayTest.md) + - [BigCat](docs/BigCat.md) + - [BigCatAllOf](docs/BigCatAllOf.md) - [Capitalization](docs/Capitalization.md) - [Cat](docs/Cat.md) - [CatAllOf](docs/CatAllOf.md) @@ -163,35 +172,26 @@ Class | Method | HTTP request | Description - [EnumArrays](docs/EnumArrays.md) - [EnumClass](docs/EnumClass.md) - [EnumTest](docs/EnumTest.md) + - [File](docs/File.md) - [FileSchemaTestClass](docs/FileSchemaTestClass.md) - - [Foo](docs/Foo.md) - [FormatTest](docs/FormatTest.md) - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) - - [HealthCheckResult](docs/HealthCheckResult.md) - - [InlineObject](docs/InlineObject.md) - - [InlineObject1](docs/InlineObject1.md) - - [InlineObject2](docs/InlineObject2.md) - - [InlineObject3](docs/InlineObject3.md) - - [InlineObject4](docs/InlineObject4.md) - - [InlineObject5](docs/InlineObject5.md) - - [InlineResponseDefault](docs/InlineResponseDefault.md) + - [List](docs/List.md) - [MapTest](docs/MapTest.md) - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Name](docs/Name.md) - - [NullableClass](docs/NullableClass.md) - [NumberOnly](docs/NumberOnly.md) - [Order](docs/Order.md) - [OuterComposite](docs/OuterComposite.md) - [OuterEnum](docs/OuterEnum.md) - - [OuterEnumDefaultValue](docs/OuterEnumDefaultValue.md) - - [OuterEnumInteger](docs/OuterEnumInteger.md) - - [OuterEnumIntegerDefaultValue](docs/OuterEnumIntegerDefaultValue.md) - [Pet](docs/Pet.md) - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - [Return](docs/Return.md) - - [SpecialModelName](docs/SpecialModelName.md) - [Tag](docs/Tag.md) + - [TypeHolderDefault](docs/TypeHolderDefault.md) + - [TypeHolderExample](docs/TypeHolderExample.md) - [User](docs/User.md) + - [XmlItem](docs/XmlItem.md) ## Documentation For Authorization @@ -211,10 +211,6 @@ Class | Method | HTTP request | Description - **API key parameter name**: api_key_query - **Location**: URL query string -## bearer_test - -- **Type**: HTTP basic authentication - ## http_basic_test - **Type**: HTTP basic authentication diff --git a/samples/client/petstore/bash/_petstore-cli b/samples/client/petstore/bash/_petstore-cli index 323b934de071..b5dfdf2084f0 100644 --- a/samples/client/petstore/bash/_petstore-cli +++ b/samples/client/petstore/bash/_petstore-cli @@ -296,7 +296,7 @@ case $state in ops) # Operations _values "Operations" \ - "call123TestSpecialTags[To test special tags]" "fooGet[]" "fakeHealthGet[Health check endpoint]" \ + "call123TestSpecialTags[To test special tags]" "createXmlItem[creates an XmlItem]" \ "fakeOuterBooleanSerialize[]" \ "fakeOuterCompositeSerialize[]" \ "fakeOuterNumberSerialize[]" \ @@ -305,9 +305,9 @@ case $state in "testBodyWithQueryParams[]" \ "testClientModel[To test \"client\" model]" \ "testEndpointParameters[Fake endpoint for testing various parameters -假端點 -偽のエンドポイント -가짜 엔드 포인트]" \ + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트]" \ "testEnumParameters[To test enum parameters]" \ "testGroupParameters[Fake endpoint to test group parameters (optional)]" \ "testInlineAdditionalProperties[test inline additionalProperties]" \ @@ -330,7 +330,8 @@ case $state in "getUserByName[Get user by user name]" \ "loginUser[Logs user into the system]" \ "logoutUser[Logs out current logged in user session]" \ - "updateUser[Updated user]" + "updateUser[Updated user]" \ + _arguments "(--help)--help[Print information about operation]" ret=0 @@ -343,13 +344,7 @@ case $state in ) _describe -t actions 'operations' _op_arguments -S '' && ret=0 ;; - fooGet) - local -a _op_arguments - _op_arguments=( - ) - _describe -t actions 'operations' _op_arguments -S '' && ret=0 - ;; - fakeHealthGet) + createXmlItem) local -a _op_arguments _op_arguments=( ) diff --git a/samples/client/petstore/bash/docs/AdditionalPropertiesClass.md b/samples/client/petstore/bash/docs/AdditionalPropertiesClass.md index 0b452819e9e1..4ae0a677ac93 100644 --- a/samples/client/petstore/bash/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/bash/docs/AdditionalPropertiesClass.md @@ -3,8 +3,17 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapUnderscoreproperty** | **map[String, string]** | | [optional] [default to null] -**mapUnderscoreofUnderscoremapUnderscoreproperty** | **map[String, map[String, string]]** | | [optional] [default to null] +**mapUnderscorestring** | **map[String, string]** | | [optional] [default to null] +**mapUnderscorenumber** | **map[String, integer]** | | [optional] [default to null] +**mapUnderscoreinteger** | **map[String, integer]** | | [optional] [default to null] +**mapUnderscoreboolean** | **map[String, boolean]** | | [optional] [default to null] +**mapUnderscorearrayUnderscoreinteger** | **map[String, array[integer]]** | | [optional] [default to null] +**mapUnderscorearrayUnderscoreanytype** | **map[String, array[map]]** | | [optional] [default to null] +**mapUnderscoremapUnderscorestring** | **map[String, map[String, string]]** | | [optional] [default to null] +**mapUnderscoremapUnderscoreanytype** | **map[String, map[String, map]]** | | [optional] [default to null] +**anytypeUnderscore1** | **map** | | [optional] [default to null] +**anytypeUnderscore2** | **map** | | [optional] [default to null] +**anytypeUnderscore3** | **map** | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/bash/docs/AnotherFakeApi.md b/samples/client/petstore/bash/docs/AnotherFakeApi.md index 8eda10a25080..e17a9e75d006 100644 --- a/samples/client/petstore/bash/docs/AnotherFakeApi.md +++ b/samples/client/petstore/bash/docs/AnotherFakeApi.md @@ -25,7 +25,7 @@ petstore-cli call123TestSpecialTags Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **client** | [**Client**](Client.md) | client model | + **body** | [**Client**](Client.md) | client model | ### Return type diff --git a/samples/client/petstore/bash/docs/BigCat.md b/samples/client/petstore/bash/docs/BigCat.md new file mode 100644 index 000000000000..5bb6378f0770 --- /dev/null +++ b/samples/client/petstore/bash/docs/BigCat.md @@ -0,0 +1,13 @@ +# BigCat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **string** | | [default to null] +**color** | **string** | | [optional] [default to red] +**declawed** | **boolean** | | [optional] [default to null] +**kind** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/bash/docs/BigCatAllOf.md b/samples/client/petstore/bash/docs/BigCatAllOf.md new file mode 100644 index 000000000000..644efd8d6794 --- /dev/null +++ b/samples/client/petstore/bash/docs/BigCatAllOf.md @@ -0,0 +1,10 @@ +# BigCat_allOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/bash/docs/EnumTest.md b/samples/client/petstore/bash/docs/EnumTest.md index 3f70a0a0667a..30b30efa7307 100644 --- a/samples/client/petstore/bash/docs/EnumTest.md +++ b/samples/client/petstore/bash/docs/EnumTest.md @@ -8,9 +8,6 @@ Name | Type | Description | Notes **enumUnderscoreinteger** | **integer** | | [optional] [default to null] **enumUnderscorenumber** | **float** | | [optional] [default to null] **outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] [default to null] -**outerEnumInteger** | [**OuterEnumInteger**](OuterEnumInteger.md) | | [optional] [default to null] -**outerEnumDefaultValue** | [**OuterEnumDefaultValue**](OuterEnumDefaultValue.md) | | [optional] [default to null] -**outerEnumIntegerDefaultValue** | [**OuterEnumIntegerDefaultValue**](OuterEnumIntegerDefaultValue.md) | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/bash/docs/FakeApi.md b/samples/client/petstore/bash/docs/FakeApi.md index 905f6e2cd088..075407dede6d 100644 --- a/samples/client/petstore/bash/docs/FakeApi.md +++ b/samples/client/petstore/bash/docs/FakeApi.md @@ -4,7 +4,7 @@ All URIs are relative to */v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**fakeHealthGet**](FakeApi.md#fakeHealthGet) | **GET** /fake/health | Health check endpoint +[**createXmlItem**](FakeApi.md#createXmlItem) | **POST** /fake/create_xml_item | creates an XmlItem [**fakeOuterBooleanSerialize**](FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | [**fakeOuterCompositeSerialize**](FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | @@ -13,9 +13,9 @@ Method | HTTP request | Description [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters -假端點 -偽のエンドポイント -가짜 엔드 포인트 + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters [**testGroupParameters**](FakeApi.md#testGroupParameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) [**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties @@ -24,23 +24,28 @@ Method | HTTP request | Description -## fakeHealthGet +## createXmlItem -Health check endpoint +creates an XmlItem + +this route creates an XmlItem ### Example ```bash -petstore-cli fakeHealthGet +petstore-cli createXmlItem ``` ### Parameters -This endpoint does not need any parameter. + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **xmlItem** | [**XmlItem**](XmlItem.md) | XmlItem Body | ### Return type -[**HealthCheckResult**](HealthCheckResult.md) +(empty response body) ### Authorization @@ -48,8 +53,8 @@ No authorization required ### HTTP request headers -- **Content-Type**: Not Applicable -- **Accept**: application/json +- **Content-Type**: application/xml, application/xml; charset=utf-8, application/xml; charset=utf-16, text/xml, text/xml; charset=utf-8, text/xml; charset=utf-16 +- **Accept**: Not Applicable [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -83,7 +88,7 @@ No authorization required ### HTTP request headers -- **Content-Type**: application/json +- **Content-Type**: Not Applicable - **Accept**: */* [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -106,7 +111,7 @@ petstore-cli fakeOuterCompositeSerialize Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **outerComposite** | [**OuterComposite**](OuterComposite.md) | Input composite as post body | [optional] + **body** | [**OuterComposite**](OuterComposite.md) | Input composite as post body | [optional] ### Return type @@ -118,7 +123,7 @@ No authorization required ### HTTP request headers -- **Content-Type**: application/json +- **Content-Type**: Not Applicable - **Accept**: */* [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -153,7 +158,7 @@ No authorization required ### HTTP request headers -- **Content-Type**: application/json +- **Content-Type**: Not Applicable - **Accept**: */* [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -188,7 +193,7 @@ No authorization required ### HTTP request headers -- **Content-Type**: application/json +- **Content-Type**: Not Applicable - **Accept**: */* [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -211,7 +216,7 @@ petstore-cli testBodyWithFileSchema Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **fileSchemaTestClass** | [**FileSchemaTestClass**](FileSchemaTestClass.md) | | + **body** | [**FileSchemaTestClass**](FileSchemaTestClass.md) | | ### Return type @@ -245,7 +250,7 @@ petstore-cli testBodyWithQueryParams query=value Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **query** | **string** | | [default to null] - **user** | [**User**](User.md) | | + **body** | [**User**](User.md) | | ### Return type @@ -280,7 +285,7 @@ petstore-cli testClientModel Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **client** | [**Client**](Client.md) | client model | + **body** | [**Client**](Client.md) | client model | ### Return type @@ -301,14 +306,14 @@ No authorization required ## testEndpointParameters Fake endpoint for testing various parameters -假端點 -偽のエンドポイント -가짜 엔드 포인트 + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 Fake endpoint for testing various parameters -假端點 -偽のエンドポイント -가짜 엔드 포인트 + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 ### Example @@ -361,7 +366,7 @@ To test enum parameters ### Example ```bash -petstore-cli testEnumParameters enum_header_string_array:value enum_header_string:value Specify as: enum_query_string_array=value1 enum_query_string_array=value2 enum_query_string_array=... enum_query_string=value enum_query_integer=value enum_query_double=value +petstore-cli testEnumParameters enum_header_string_array:value enum_header_string:value Specify as: enum_query_string_array="value1,value2,..." enum_query_string=value enum_query_integer=value enum_query_double=value ``` ### Parameters @@ -424,7 +429,7 @@ Name | Type | Description | Notes ### Authorization -[bearer_test](../README.md#bearer_test) +No authorization required ### HTTP request headers @@ -449,7 +454,7 @@ petstore-cli testInlineAdditionalProperties Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **requestBody** | [**map[String, string]**](string.md) | request body | + **param** | [**map[String, string]**](string.md) | request body | ### Return type @@ -510,7 +515,7 @@ To test the collection format in query parameters ### Example ```bash -petstore-cli testQueryParameterCollectionFormat Specify as: pipe=value1 pipe=value2 pipe=... Specify as: ioutil="value1,value2,..." Specify as: Specify as: url="value1,value2,..." Specify as: context=value1 context=value2 context=... +petstore-cli testQueryParameterCollectionFormat Specify as: pipe="value1,value2,..." Specify as: ioutil="value1,value2,..." Specify as: http="value1 value2 ..." Specify as: url="value1,value2,..." Specify as: context=value1 context=value2 context=... ``` ### Parameters diff --git a/samples/client/petstore/bash/docs/FakeClassnameTags123Api.md b/samples/client/petstore/bash/docs/FakeClassnameTags123Api.md index f670ef5f7b9a..19b3d386d383 100644 --- a/samples/client/petstore/bash/docs/FakeClassnameTags123Api.md +++ b/samples/client/petstore/bash/docs/FakeClassnameTags123Api.md @@ -25,7 +25,7 @@ petstore-cli testClassname Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **client** | [**Client**](Client.md) | client model | + **body** | [**Client**](Client.md) | client model | ### Return type diff --git a/samples/client/petstore/bash/docs/File.md b/samples/client/petstore/bash/docs/File.md new file mode 100644 index 000000000000..17f714698588 --- /dev/null +++ b/samples/client/petstore/bash/docs/File.md @@ -0,0 +1,10 @@ +# File + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**sourceURI** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/bash/docs/FormatTest.md b/samples/client/petstore/bash/docs/FormatTest.md index 8fe26118a9dd..8c182123a627 100644 --- a/samples/client/petstore/bash/docs/FormatTest.md +++ b/samples/client/petstore/bash/docs/FormatTest.md @@ -16,8 +16,7 @@ Name | Type | Description | Notes **dateTime** | **string** | | [optional] [default to null] **uuid** | **string** | | [optional] [default to null] **password** | **string** | | [default to null] -**patternUnderscorewithUnderscoredigits** | **string** | | [optional] [default to null] -**patternUnderscorewithUnderscoredigitsUnderscoreandUnderscoredelimiter** | **string** | | [optional] [default to null] +**BigDecimal** | [**Decimal**](Decimal.md) | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/bash/docs/List.md b/samples/client/petstore/bash/docs/List.md new file mode 100644 index 000000000000..c73851d7f7b1 --- /dev/null +++ b/samples/client/petstore/bash/docs/List.md @@ -0,0 +1,10 @@ +# List + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**123Minuslist** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/bash/docs/Pet.md b/samples/client/petstore/bash/docs/Pet.md index b86df96bb598..5dc9328bd911 100644 --- a/samples/client/petstore/bash/docs/Pet.md +++ b/samples/client/petstore/bash/docs/Pet.md @@ -6,7 +6,7 @@ Name | Type | Description | Notes **id** | **integer** | | [optional] [default to null] **category** | [**Category**](Category.md) | | [optional] [default to null] **name** | **string** | | [default to null] -**photoUrls** | **array[string]** | | [default to null] +**photoUrls** | **Set[string]** | | [default to null] **tags** | [**array[Tag]**](Tag.md) | | [optional] [default to null] **status** | **string** | | [optional] [default to null] diff --git a/samples/client/petstore/bash/docs/PetApi.md b/samples/client/petstore/bash/docs/PetApi.md index ddc4f21bffcd..f59b24393606 100644 --- a/samples/client/petstore/bash/docs/PetApi.md +++ b/samples/client/petstore/bash/docs/PetApi.md @@ -31,7 +31,7 @@ petstore-cli addPet Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | + **body** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | ### Return type @@ -135,11 +135,11 @@ petstore-cli findPetsByTags Specify as: tags="value1,value2,..." Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **tags** | [**array[string]**](string.md) | Tags to filter by | [default to null] + **tags** | [**Set[string]**](string.md) | Tags to filter by | [default to null] ### Return type -[**array[Pet]**](Pet.md) +[**Set[Pet]**](Pet.md) ### Authorization @@ -203,7 +203,7 @@ petstore-cli updatePet Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | + **body** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | ### Return type diff --git a/samples/client/petstore/bash/docs/StoreApi.md b/samples/client/petstore/bash/docs/StoreApi.md index 58ee002b7b86..56b2934562b5 100644 --- a/samples/client/petstore/bash/docs/StoreApi.md +++ b/samples/client/petstore/bash/docs/StoreApi.md @@ -128,7 +128,7 @@ petstore-cli placeOrder Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **order** | [**Order**](Order.md) | order placed for purchasing the pet | + **body** | [**Order**](Order.md) | order placed for purchasing the pet | ### Return type @@ -140,7 +140,7 @@ No authorization required ### HTTP request headers -- **Content-Type**: application/json +- **Content-Type**: Not Applicable - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore/bash/docs/UserApi.md b/samples/client/petstore/bash/docs/UserApi.md index f36e39d38ee6..9663a425b732 100644 --- a/samples/client/petstore/bash/docs/UserApi.md +++ b/samples/client/petstore/bash/docs/UserApi.md @@ -32,7 +32,7 @@ petstore-cli createUser Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **user** | [**User**](User.md) | Created user object | + **body** | [**User**](User.md) | Created user object | ### Return type @@ -44,7 +44,7 @@ No authorization required ### HTTP request headers -- **Content-Type**: application/json +- **Content-Type**: Not Applicable - **Accept**: Not Applicable [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -65,7 +65,7 @@ petstore-cli createUsersWithArrayInput Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **user** | [**array[User]**](User.md) | List of user object | + **body** | [**array[User]**](User.md) | List of user object | ### Return type @@ -77,7 +77,7 @@ No authorization required ### HTTP request headers -- **Content-Type**: application/json +- **Content-Type**: Not Applicable - **Accept**: Not Applicable [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -98,7 +98,7 @@ petstore-cli createUsersWithListInput Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **user** | [**array[User]**](User.md) | List of user object | + **body** | [**array[User]**](User.md) | List of user object | ### Return type @@ -110,7 +110,7 @@ No authorization required ### HTTP request headers -- **Content-Type**: application/json +- **Content-Type**: Not Applicable - **Accept**: Not Applicable [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -266,7 +266,7 @@ petstore-cli updateUser username=value Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **string** | name that need to be deleted | [default to null] - **user** | [**User**](User.md) | Updated user object | + **body** | [**User**](User.md) | Updated user object | ### Return type @@ -278,7 +278,7 @@ No authorization required ### HTTP request headers -- **Content-Type**: application/json +- **Content-Type**: Not Applicable - **Accept**: Not Applicable [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore/bash/petstore-cli b/samples/client/petstore/bash/petstore-cli index 7e496f60eeca..80386fb0ebe0 100755 --- a/samples/client/petstore/bash/petstore-cli +++ b/samples/client/petstore/bash/petstore-cli @@ -95,15 +95,16 @@ declare -a result_color_table=( "$WHITE" "$WHITE" "$GREEN" "$YELLOW" "$WHITE" "$ # 0 - optional # 1 - required declare -A operation_parameters_minimum_occurrences -operation_parameters_minimum_occurrences["call123TestSpecialTags:::Client"]=1 +operation_parameters_minimum_occurrences["call123TestSpecialTags:::body"]=1 +operation_parameters_minimum_occurrences["createXmlItem:::XmlItem"]=1 operation_parameters_minimum_occurrences["fakeOuterBooleanSerialize:::body"]=0 -operation_parameters_minimum_occurrences["fakeOuterCompositeSerialize:::OuterComposite"]=0 +operation_parameters_minimum_occurrences["fakeOuterCompositeSerialize:::body"]=0 operation_parameters_minimum_occurrences["fakeOuterNumberSerialize:::body"]=0 operation_parameters_minimum_occurrences["fakeOuterStringSerialize:::body"]=0 -operation_parameters_minimum_occurrences["testBodyWithFileSchema:::FileSchemaTestClass"]=1 +operation_parameters_minimum_occurrences["testBodyWithFileSchema:::body"]=1 operation_parameters_minimum_occurrences["testBodyWithQueryParams:::query"]=1 -operation_parameters_minimum_occurrences["testBodyWithQueryParams:::User"]=1 -operation_parameters_minimum_occurrences["testClientModel:::Client"]=1 +operation_parameters_minimum_occurrences["testBodyWithQueryParams:::body"]=1 +operation_parameters_minimum_occurrences["testClientModel:::body"]=1 operation_parameters_minimum_occurrences["testEndpointParameters:::number"]=1 operation_parameters_minimum_occurrences["testEndpointParameters:::double"]=1 operation_parameters_minimum_occurrences["testEndpointParameters:::pattern_without_delimiter"]=1 @@ -132,7 +133,7 @@ operation_parameters_minimum_occurrences["testGroupParameters:::required_int64_g operation_parameters_minimum_occurrences["testGroupParameters:::string_group"]=0 operation_parameters_minimum_occurrences["testGroupParameters:::boolean_group"]=0 operation_parameters_minimum_occurrences["testGroupParameters:::int64_group"]=0 -operation_parameters_minimum_occurrences["testInlineAdditionalProperties:::request_body"]=1 +operation_parameters_minimum_occurrences["testInlineAdditionalProperties:::param"]=1 operation_parameters_minimum_occurrences["testJsonFormData:::param"]=1 operation_parameters_minimum_occurrences["testJsonFormData:::param2"]=1 operation_parameters_minimum_occurrences["testQueryParameterCollectionFormat:::pipe"]=1 @@ -140,14 +141,14 @@ operation_parameters_minimum_occurrences["testQueryParameterCollectionFormat:::i operation_parameters_minimum_occurrences["testQueryParameterCollectionFormat:::http"]=1 operation_parameters_minimum_occurrences["testQueryParameterCollectionFormat:::url"]=1 operation_parameters_minimum_occurrences["testQueryParameterCollectionFormat:::context"]=1 -operation_parameters_minimum_occurrences["testClassname:::Client"]=1 -operation_parameters_minimum_occurrences["addPet:::Pet"]=1 +operation_parameters_minimum_occurrences["testClassname:::body"]=1 +operation_parameters_minimum_occurrences["addPet:::body"]=1 operation_parameters_minimum_occurrences["deletePet:::petId"]=1 operation_parameters_minimum_occurrences["deletePet:::api_key"]=0 operation_parameters_minimum_occurrences["findPetsByStatus:::status"]=1 operation_parameters_minimum_occurrences["findPetsByTags:::tags"]=1 operation_parameters_minimum_occurrences["getPetById:::petId"]=1 -operation_parameters_minimum_occurrences["updatePet:::Pet"]=1 +operation_parameters_minimum_occurrences["updatePet:::body"]=1 operation_parameters_minimum_occurrences["updatePetWithForm:::petId"]=1 operation_parameters_minimum_occurrences["updatePetWithForm:::name"]=0 operation_parameters_minimum_occurrences["updatePetWithForm:::status"]=0 @@ -159,16 +160,16 @@ operation_parameters_minimum_occurrences["uploadFileWithRequiredFile:::requiredF operation_parameters_minimum_occurrences["uploadFileWithRequiredFile:::additionalMetadata"]=0 operation_parameters_minimum_occurrences["deleteOrder:::order_id"]=1 operation_parameters_minimum_occurrences["getOrderById:::order_id"]=1 -operation_parameters_minimum_occurrences["placeOrder:::Order"]=1 -operation_parameters_minimum_occurrences["createUser:::User"]=1 -operation_parameters_minimum_occurrences["createUsersWithArrayInput:::User"]=1 -operation_parameters_minimum_occurrences["createUsersWithListInput:::User"]=1 +operation_parameters_minimum_occurrences["placeOrder:::body"]=1 +operation_parameters_minimum_occurrences["createUser:::body"]=1 +operation_parameters_minimum_occurrences["createUsersWithArrayInput:::body"]=1 +operation_parameters_minimum_occurrences["createUsersWithListInput:::body"]=1 operation_parameters_minimum_occurrences["deleteUser:::username"]=1 operation_parameters_minimum_occurrences["getUserByName:::username"]=1 operation_parameters_minimum_occurrences["loginUser:::username"]=1 operation_parameters_minimum_occurrences["loginUser:::password"]=1 operation_parameters_minimum_occurrences["updateUser:::username"]=1 -operation_parameters_minimum_occurrences["updateUser:::User"]=1 +operation_parameters_minimum_occurrences["updateUser:::body"]=1 ## # This array stores the maximum number of allowed occurrences for parameter @@ -177,15 +178,16 @@ operation_parameters_minimum_occurrences["updateUser:::User"]=1 # N - N values # 0 - unlimited declare -A operation_parameters_maximum_occurrences -operation_parameters_maximum_occurrences["call123TestSpecialTags:::Client"]=0 +operation_parameters_maximum_occurrences["call123TestSpecialTags:::body"]=0 +operation_parameters_maximum_occurrences["createXmlItem:::XmlItem"]=0 operation_parameters_maximum_occurrences["fakeOuterBooleanSerialize:::body"]=0 -operation_parameters_maximum_occurrences["fakeOuterCompositeSerialize:::OuterComposite"]=0 +operation_parameters_maximum_occurrences["fakeOuterCompositeSerialize:::body"]=0 operation_parameters_maximum_occurrences["fakeOuterNumberSerialize:::body"]=0 operation_parameters_maximum_occurrences["fakeOuterStringSerialize:::body"]=0 -operation_parameters_maximum_occurrences["testBodyWithFileSchema:::FileSchemaTestClass"]=0 +operation_parameters_maximum_occurrences["testBodyWithFileSchema:::body"]=0 operation_parameters_maximum_occurrences["testBodyWithQueryParams:::query"]=0 -operation_parameters_maximum_occurrences["testBodyWithQueryParams:::User"]=0 -operation_parameters_maximum_occurrences["testClientModel:::Client"]=0 +operation_parameters_maximum_occurrences["testBodyWithQueryParams:::body"]=0 +operation_parameters_maximum_occurrences["testClientModel:::body"]=0 operation_parameters_maximum_occurrences["testEndpointParameters:::number"]=0 operation_parameters_maximum_occurrences["testEndpointParameters:::double"]=0 operation_parameters_maximum_occurrences["testEndpointParameters:::pattern_without_delimiter"]=0 @@ -214,7 +216,7 @@ operation_parameters_maximum_occurrences["testGroupParameters:::required_int64_g operation_parameters_maximum_occurrences["testGroupParameters:::string_group"]=0 operation_parameters_maximum_occurrences["testGroupParameters:::boolean_group"]=0 operation_parameters_maximum_occurrences["testGroupParameters:::int64_group"]=0 -operation_parameters_maximum_occurrences["testInlineAdditionalProperties:::request_body"]=0 +operation_parameters_maximum_occurrences["testInlineAdditionalProperties:::param"]=0 operation_parameters_maximum_occurrences["testJsonFormData:::param"]=0 operation_parameters_maximum_occurrences["testJsonFormData:::param2"]=0 operation_parameters_maximum_occurrences["testQueryParameterCollectionFormat:::pipe"]=0 @@ -222,14 +224,14 @@ operation_parameters_maximum_occurrences["testQueryParameterCollectionFormat:::i operation_parameters_maximum_occurrences["testQueryParameterCollectionFormat:::http"]=0 operation_parameters_maximum_occurrences["testQueryParameterCollectionFormat:::url"]=0 operation_parameters_maximum_occurrences["testQueryParameterCollectionFormat:::context"]=0 -operation_parameters_maximum_occurrences["testClassname:::Client"]=0 -operation_parameters_maximum_occurrences["addPet:::Pet"]=0 +operation_parameters_maximum_occurrences["testClassname:::body"]=0 +operation_parameters_maximum_occurrences["addPet:::body"]=0 operation_parameters_maximum_occurrences["deletePet:::petId"]=0 operation_parameters_maximum_occurrences["deletePet:::api_key"]=0 operation_parameters_maximum_occurrences["findPetsByStatus:::status"]=0 operation_parameters_maximum_occurrences["findPetsByTags:::tags"]=0 operation_parameters_maximum_occurrences["getPetById:::petId"]=0 -operation_parameters_maximum_occurrences["updatePet:::Pet"]=0 +operation_parameters_maximum_occurrences["updatePet:::body"]=0 operation_parameters_maximum_occurrences["updatePetWithForm:::petId"]=0 operation_parameters_maximum_occurrences["updatePetWithForm:::name"]=0 operation_parameters_maximum_occurrences["updatePetWithForm:::status"]=0 @@ -241,30 +243,31 @@ operation_parameters_maximum_occurrences["uploadFileWithRequiredFile:::requiredF operation_parameters_maximum_occurrences["uploadFileWithRequiredFile:::additionalMetadata"]=0 operation_parameters_maximum_occurrences["deleteOrder:::order_id"]=0 operation_parameters_maximum_occurrences["getOrderById:::order_id"]=0 -operation_parameters_maximum_occurrences["placeOrder:::Order"]=0 -operation_parameters_maximum_occurrences["createUser:::User"]=0 -operation_parameters_maximum_occurrences["createUsersWithArrayInput:::User"]=0 -operation_parameters_maximum_occurrences["createUsersWithListInput:::User"]=0 +operation_parameters_maximum_occurrences["placeOrder:::body"]=0 +operation_parameters_maximum_occurrences["createUser:::body"]=0 +operation_parameters_maximum_occurrences["createUsersWithArrayInput:::body"]=0 +operation_parameters_maximum_occurrences["createUsersWithListInput:::body"]=0 operation_parameters_maximum_occurrences["deleteUser:::username"]=0 operation_parameters_maximum_occurrences["getUserByName:::username"]=0 operation_parameters_maximum_occurrences["loginUser:::username"]=0 operation_parameters_maximum_occurrences["loginUser:::password"]=0 operation_parameters_maximum_occurrences["updateUser:::username"]=0 -operation_parameters_maximum_occurrences["updateUser:::User"]=0 +operation_parameters_maximum_occurrences["updateUser:::body"]=0 ## # The type of collection for specifying multiple values for parameter: # - multi, csv, ssv, tsv declare -A operation_parameters_collection_type -operation_parameters_collection_type["call123TestSpecialTags:::Client"]="" +operation_parameters_collection_type["call123TestSpecialTags:::body"]="" +operation_parameters_collection_type["createXmlItem:::XmlItem"]="" operation_parameters_collection_type["fakeOuterBooleanSerialize:::body"]="" -operation_parameters_collection_type["fakeOuterCompositeSerialize:::OuterComposite"]="" +operation_parameters_collection_type["fakeOuterCompositeSerialize:::body"]="" operation_parameters_collection_type["fakeOuterNumberSerialize:::body"]="" operation_parameters_collection_type["fakeOuterStringSerialize:::body"]="" -operation_parameters_collection_type["testBodyWithFileSchema:::FileSchemaTestClass"]="" +operation_parameters_collection_type["testBodyWithFileSchema:::body"]="" operation_parameters_collection_type["testBodyWithQueryParams:::query"]="" -operation_parameters_collection_type["testBodyWithQueryParams:::User"]="" -operation_parameters_collection_type["testClientModel:::Client"]="" +operation_parameters_collection_type["testBodyWithQueryParams:::body"]="" +operation_parameters_collection_type["testClientModel:::body"]="" operation_parameters_collection_type["testEndpointParameters:::number"]="" operation_parameters_collection_type["testEndpointParameters:::double"]="" operation_parameters_collection_type["testEndpointParameters:::pattern_without_delimiter"]="" @@ -281,7 +284,7 @@ operation_parameters_collection_type["testEndpointParameters:::password"]="" operation_parameters_collection_type["testEndpointParameters:::callback"]="" operation_parameters_collection_type["testEnumParameters:::enum_header_string_array"]="csv" operation_parameters_collection_type["testEnumParameters:::enum_header_string"]="" -operation_parameters_collection_type["testEnumParameters:::enum_query_string_array"]="multi" +operation_parameters_collection_type["testEnumParameters:::enum_query_string_array"]="csv" operation_parameters_collection_type["testEnumParameters:::enum_query_string"]="" operation_parameters_collection_type["testEnumParameters:::enum_query_integer"]="" operation_parameters_collection_type["testEnumParameters:::enum_query_double"]="" @@ -293,22 +296,22 @@ operation_parameters_collection_type["testGroupParameters:::required_int64_group operation_parameters_collection_type["testGroupParameters:::string_group"]="" operation_parameters_collection_type["testGroupParameters:::boolean_group"]="" operation_parameters_collection_type["testGroupParameters:::int64_group"]="" -operation_parameters_collection_type["testInlineAdditionalProperties:::request_body"]= +operation_parameters_collection_type["testInlineAdditionalProperties:::param"]= operation_parameters_collection_type["testJsonFormData:::param"]="" operation_parameters_collection_type["testJsonFormData:::param2"]="" -operation_parameters_collection_type["testQueryParameterCollectionFormat:::pipe"]="multi" +operation_parameters_collection_type["testQueryParameterCollectionFormat:::pipe"]="csv" operation_parameters_collection_type["testQueryParameterCollectionFormat:::ioutil"]="csv" -operation_parameters_collection_type["testQueryParameterCollectionFormat:::http"]= +operation_parameters_collection_type["testQueryParameterCollectionFormat:::http"]="ssv" operation_parameters_collection_type["testQueryParameterCollectionFormat:::url"]="csv" operation_parameters_collection_type["testQueryParameterCollectionFormat:::context"]="multi" -operation_parameters_collection_type["testClassname:::Client"]="" -operation_parameters_collection_type["addPet:::Pet"]="" +operation_parameters_collection_type["testClassname:::body"]="" +operation_parameters_collection_type["addPet:::body"]="" operation_parameters_collection_type["deletePet:::petId"]="" operation_parameters_collection_type["deletePet:::api_key"]="" operation_parameters_collection_type["findPetsByStatus:::status"]="csv" operation_parameters_collection_type["findPetsByTags:::tags"]="csv" operation_parameters_collection_type["getPetById:::petId"]="" -operation_parameters_collection_type["updatePet:::Pet"]="" +operation_parameters_collection_type["updatePet:::body"]="" operation_parameters_collection_type["updatePetWithForm:::petId"]="" operation_parameters_collection_type["updatePetWithForm:::name"]="" operation_parameters_collection_type["updatePetWithForm:::status"]="" @@ -320,16 +323,16 @@ operation_parameters_collection_type["uploadFileWithRequiredFile:::requiredFile" operation_parameters_collection_type["uploadFileWithRequiredFile:::additionalMetadata"]="" operation_parameters_collection_type["deleteOrder:::order_id"]="" operation_parameters_collection_type["getOrderById:::order_id"]="" -operation_parameters_collection_type["placeOrder:::Order"]="" -operation_parameters_collection_type["createUser:::User"]="" -operation_parameters_collection_type["createUsersWithArrayInput:::User"]= -operation_parameters_collection_type["createUsersWithListInput:::User"]= +operation_parameters_collection_type["placeOrder:::body"]="" +operation_parameters_collection_type["createUser:::body"]="" +operation_parameters_collection_type["createUsersWithArrayInput:::body"]= +operation_parameters_collection_type["createUsersWithListInput:::body"]= operation_parameters_collection_type["deleteUser:::username"]="" operation_parameters_collection_type["getUserByName:::username"]="" operation_parameters_collection_type["loginUser:::username"]="" operation_parameters_collection_type["loginUser:::password"]="" operation_parameters_collection_type["updateUser:::username"]="" -operation_parameters_collection_type["updateUser:::User"]="" +operation_parameters_collection_type["updateUser:::body"]="" ## @@ -425,7 +428,7 @@ url_escape() { -e 's/(/%28/g' \ -e 's/)/%29/g' \ -e 's/:/%3A/g' \ - -e 's/\t/%09/g' \ + -e 's/\\t/%09/g' \ -e 's/?/%3F/g' <<<"$raw_url"); echo "$value" @@ -722,8 +725,6 @@ EOF echo -e " or export ${RED}PETSTORE_API_KEY=''${OFF}" echo -e " - ${BLUE}Basic AUTH${OFF} - add '-u :' before ${YELLOW}${OFF}" echo -e " or export ${RED}PETSTORE_BASIC_AUTH=':'${OFF}" - echo -e " - ${BLUE}Basic AUTH${OFF} - add '-u :' before ${YELLOW}${OFF}" - echo -e " or export ${RED}PETSTORE_BASIC_AUTH=':'${OFF}" echo -e " - ${MAGENTA}OAuth2 (flow: implicit)${OFF}" echo -e " Authorization URL: " echo -e " * http://petstore.swagger.io/api/oauth/dialog" @@ -737,17 +738,11 @@ EOF read -r -d '' ops < -g cpp-qt5-client -o +java -jar target/openapi-generator-cli.jar generate -i -g cpp-qt-client -o ``` ## Getting Started diff --git a/samples/client/petstore/cpp-qt5/build-and-test.bash b/samples/client/petstore/cpp-qt/build-and-test.bash similarity index 100% rename from samples/client/petstore/cpp-qt5/build-and-test.bash rename to samples/client/petstore/cpp-qt/build-and-test.bash diff --git a/samples/client/petstore/cpp-qt5/client/CMakeLists.txt b/samples/client/petstore/cpp-qt/client/CMakeLists.txt similarity index 100% rename from samples/client/petstore/cpp-qt5/client/CMakeLists.txt rename to samples/client/petstore/cpp-qt/client/CMakeLists.txt diff --git a/samples/client/petstore/cpp-qt5/client/PFXApiResponse.cpp b/samples/client/petstore/cpp-qt/client/PFXApiResponse.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXApiResponse.cpp rename to samples/client/petstore/cpp-qt/client/PFXApiResponse.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXApiResponse.h b/samples/client/petstore/cpp-qt/client/PFXApiResponse.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXApiResponse.h rename to samples/client/petstore/cpp-qt/client/PFXApiResponse.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXCategory.cpp b/samples/client/petstore/cpp-qt/client/PFXCategory.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXCategory.cpp rename to samples/client/petstore/cpp-qt/client/PFXCategory.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXCategory.h b/samples/client/petstore/cpp-qt/client/PFXCategory.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXCategory.h rename to samples/client/petstore/cpp-qt/client/PFXCategory.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXEnum.h b/samples/client/petstore/cpp-qt/client/PFXEnum.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXEnum.h rename to samples/client/petstore/cpp-qt/client/PFXEnum.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXHelpers.cpp b/samples/client/petstore/cpp-qt/client/PFXHelpers.cpp similarity index 70% rename from samples/client/petstore/cpp-qt5/client/PFXHelpers.cpp rename to samples/client/petstore/cpp-qt/client/PFXHelpers.cpp index b3b36c83be8b..7245de9007fe 100644 --- a/samples/client/petstore/cpp-qt5/client/PFXHelpers.cpp +++ b/samples/client/petstore/cpp-qt/client/PFXHelpers.cpp @@ -17,47 +17,83 @@ namespace test_namespace { class PFXSerializerSettings { public: - static void setDateTimeFormat(const QString & dtFormat){ - getInstance()->dateTimeFormat = dtFormat; + struct CustomDateTimeFormat{ + bool isStringSet = false; + QString formatString; + bool isEnumSet = false; + Qt::DateFormat formatEnum; + }; + + static CustomDateTimeFormat getCustomDateTimeFormat() { + return getInstance()->customDateTimeFormat; } - static QString getDateTimeFormat() { - return getInstance()->dateTimeFormat; + + static void setDateTimeFormatString(const QString &dtFormat){ + getInstance()->customDateTimeFormat.isStringSet = true; + getInstance()->customDateTimeFormat.isEnumSet = false; + getInstance()->customDateTimeFormat.formatString = dtFormat; + } + + static void setDateTimeFormatEnum(const Qt::DateFormat &dtFormat){ + getInstance()->customDateTimeFormat.isEnumSet = true; + getInstance()->customDateTimeFormat.isStringSet = false; + getInstance()->customDateTimeFormat.formatEnum = dtFormat; } + static PFXSerializerSettings *getInstance(){ if(instance == nullptr){ instance = new PFXSerializerSettings(); } return instance; } + private: explicit PFXSerializerSettings(){ instance = this; - dateTimeFormat.clear(); + customDateTimeFormat.isStringSet = false; + customDateTimeFormat.isEnumSet = false; } static PFXSerializerSettings *instance; - QString dateTimeFormat; + CustomDateTimeFormat customDateTimeFormat; }; PFXSerializerSettings * PFXSerializerSettings::instance = nullptr; -bool setDateTimeFormat(const QString& dateTimeFormat){ +bool setDateTimeFormat(const QString &dateTimeFormat){ bool success = false; auto dt = QDateTime::fromString(QDateTime::currentDateTime().toString(dateTimeFormat), dateTimeFormat); - if(dt.isValid()){ + if (dt.isValid()) { success = true; - PFXSerializerSettings::setDateTimeFormat(dateTimeFormat); + PFXSerializerSettings::setDateTimeFormatString(dateTimeFormat); } return success; } +bool setDateTimeFormat(const Qt::DateFormat &dateTimeFormat){ + bool success = false; + auto dt = QDateTime::fromString(QDateTime::currentDateTime().toString(dateTimeFormat), dateTimeFormat); + if (dt.isValid()) { + success = true; + PFXSerializerSettings::setDateTimeFormatEnum(dateTimeFormat); + } + return success; +} QString toStringValue(const QString &value) { return value; } QString toStringValue(const QDateTime &value) { + if (PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().isStringSet) { + return value.toString(PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().formatString); + } + + if (PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().isEnumSet) { + return value.toString(PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().formatEnum); + } + // ISO 8601 - return PFXSerializerSettings::getInstance()->getDateTimeFormat().isEmpty()? value.toString(Qt::ISODate):value.toString(PFXSerializerSettings::getInstance()->getDateTimeFormat()); + return value.toString(Qt::ISODate); } QString toStringValue(const QByteArray &value) { @@ -106,7 +142,16 @@ QJsonValue toJsonValue(const QString &value) { } QJsonValue toJsonValue(const QDateTime &value) { - return QJsonValue(value.toString(PFXSerializerSettings::getInstance()->getDateTimeFormat().isEmpty()?value.toString(Qt::ISODate):value.toString(PFXSerializerSettings::getInstance()->getDateTimeFormat()))); + if (PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().isStringSet) { + return QJsonValue(value.toString(PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().formatString)); + } + + if (PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().isEnumSet) { + return QJsonValue(value.toString(PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().formatEnum)); + } + + // ISO 8601 + return QJsonValue(value.toString(Qt::ISODate)); } QJsonValue toJsonValue(const QByteArray &value) { @@ -159,7 +204,15 @@ bool fromStringValue(const QString &inStr, QDateTime &value) { if (inStr.isEmpty()) { return false; } else { - auto dateTime = PFXSerializerSettings::getInstance()->getDateTimeFormat().isEmpty()?QDateTime::fromString(inStr, Qt::ISODate) :QDateTime::fromString(inStr, PFXSerializerSettings::getInstance()->getDateTimeFormat()); + QDateTime dateTime; + if (PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().isStringSet) { + dateTime = QDateTime::fromString(inStr, PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().formatString); + } else if (PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().isEnumSet) { + dateTime = QDateTime::fromString(inStr, PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().formatEnum); + } else { + dateTime = QDateTime::fromString(inStr, Qt::ISODate); + } + if (dateTime.isValid()) { value.setDate(dateTime.date()); value.setTime(dateTime.time()); @@ -264,7 +317,13 @@ bool fromJsonValue(QString &value, const QJsonValue &jval) { bool fromJsonValue(QDateTime &value, const QJsonValue &jval) { bool ok = true; if (!jval.isUndefined() && !jval.isNull() && jval.isString()) { - value = PFXSerializerSettings::getInstance()->getDateTimeFormat().isEmpty()?QDateTime::fromString(jval.toString(), Qt::ISODate): QDateTime::fromString(jval.toString(), PFXSerializerSettings::getInstance()->getDateTimeFormat()); + if (PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().isStringSet) { + value = QDateTime::fromString(jval.toString(), PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().formatString); + } else if (PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().isEnumSet) { + value = QDateTime::fromString(jval.toString(), PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().formatEnum); + } else { + value = QDateTime::fromString(jval.toString(), Qt::ISODate); + } ok = value.isValid(); } else { ok = false; diff --git a/samples/client/petstore/cpp-qt5/client/PFXHelpers.h b/samples/client/petstore/cpp-qt/client/PFXHelpers.h similarity index 98% rename from samples/client/petstore/cpp-qt5/client/PFXHelpers.h rename to samples/client/petstore/cpp-qt/client/PFXHelpers.h index bebd7b94690d..3980b8ac2f16 100644 --- a/samples/client/petstore/cpp-qt5/client/PFXHelpers.h +++ b/samples/client/petstore/cpp-qt/client/PFXHelpers.h @@ -50,7 +50,8 @@ class OptionalParam { } }; -bool setDateTimeFormat(const QString&); +bool setDateTimeFormat(const QString &format); +bool setDateTimeFormat(const Qt::DateFormat &format); template QString toStringValue(const QList &val); diff --git a/samples/client/petstore/cpp-qt5/client/PFXHttpFileElement.cpp b/samples/client/petstore/cpp-qt/client/PFXHttpFileElement.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXHttpFileElement.cpp rename to samples/client/petstore/cpp-qt/client/PFXHttpFileElement.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXHttpFileElement.h b/samples/client/petstore/cpp-qt/client/PFXHttpFileElement.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXHttpFileElement.h rename to samples/client/petstore/cpp-qt/client/PFXHttpFileElement.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXHttpRequest.cpp b/samples/client/petstore/cpp-qt/client/PFXHttpRequest.cpp similarity index 99% rename from samples/client/petstore/cpp-qt5/client/PFXHttpRequest.cpp rename to samples/client/petstore/cpp-qt/client/PFXHttpRequest.cpp index ec16ac8e9166..b05c2c19219a 100644 --- a/samples/client/petstore/cpp-qt5/client/PFXHttpRequest.cpp +++ b/samples/client/petstore/cpp-qt/client/PFXHttpRequest.cpp @@ -335,7 +335,7 @@ void PFXHttpRequestWorker::execute(PFXHttpRequestInput *input) { if (PFXHttpRequestWorker::sslDefaultConfiguration != nullptr) { request.setSslConfiguration(*PFXHttpRequestWorker::sslDefaultConfiguration); } - request.setRawHeader("User-Agent", "OpenAPI-Generator/1.0.0/cpp-qt5"); + request.setRawHeader("User-Agent", "OpenAPI-Generator/1.0.0/cpp-qt"); foreach (QString key, input->headers.keys()) { request.setRawHeader(key.toStdString().c_str(), input->headers.value(key).toStdString().c_str()); } if (request_content.size() > 0 && !isFormData && (input->var_layout != MULTIPART)) { diff --git a/samples/client/petstore/cpp-qt5/client/PFXHttpRequest.h b/samples/client/petstore/cpp-qt/client/PFXHttpRequest.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXHttpRequest.h rename to samples/client/petstore/cpp-qt/client/PFXHttpRequest.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXObject.h b/samples/client/petstore/cpp-qt/client/PFXObject.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXObject.h rename to samples/client/petstore/cpp-qt/client/PFXObject.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXOrder.cpp b/samples/client/petstore/cpp-qt/client/PFXOrder.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXOrder.cpp rename to samples/client/petstore/cpp-qt/client/PFXOrder.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXOrder.h b/samples/client/petstore/cpp-qt/client/PFXOrder.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXOrder.h rename to samples/client/petstore/cpp-qt/client/PFXOrder.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXPet.cpp b/samples/client/petstore/cpp-qt/client/PFXPet.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXPet.cpp rename to samples/client/petstore/cpp-qt/client/PFXPet.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXPet.h b/samples/client/petstore/cpp-qt/client/PFXPet.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXPet.h rename to samples/client/petstore/cpp-qt/client/PFXPet.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXPetApi.cpp b/samples/client/petstore/cpp-qt/client/PFXPetApi.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXPetApi.cpp rename to samples/client/petstore/cpp-qt/client/PFXPetApi.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXPetApi.h b/samples/client/petstore/cpp-qt/client/PFXPetApi.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXPetApi.h rename to samples/client/petstore/cpp-qt/client/PFXPetApi.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXServerConfiguration.h b/samples/client/petstore/cpp-qt/client/PFXServerConfiguration.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXServerConfiguration.h rename to samples/client/petstore/cpp-qt/client/PFXServerConfiguration.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXServerVariable.h b/samples/client/petstore/cpp-qt/client/PFXServerVariable.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXServerVariable.h rename to samples/client/petstore/cpp-qt/client/PFXServerVariable.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXStoreApi.cpp b/samples/client/petstore/cpp-qt/client/PFXStoreApi.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXStoreApi.cpp rename to samples/client/petstore/cpp-qt/client/PFXStoreApi.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXStoreApi.h b/samples/client/petstore/cpp-qt/client/PFXStoreApi.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXStoreApi.h rename to samples/client/petstore/cpp-qt/client/PFXStoreApi.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXTag.cpp b/samples/client/petstore/cpp-qt/client/PFXTag.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXTag.cpp rename to samples/client/petstore/cpp-qt/client/PFXTag.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXTag.h b/samples/client/petstore/cpp-qt/client/PFXTag.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXTag.h rename to samples/client/petstore/cpp-qt/client/PFXTag.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXUser.cpp b/samples/client/petstore/cpp-qt/client/PFXUser.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXUser.cpp rename to samples/client/petstore/cpp-qt/client/PFXUser.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXUser.h b/samples/client/petstore/cpp-qt/client/PFXUser.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXUser.h rename to samples/client/petstore/cpp-qt/client/PFXUser.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXUserApi.cpp b/samples/client/petstore/cpp-qt/client/PFXUserApi.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXUserApi.cpp rename to samples/client/petstore/cpp-qt/client/PFXUserApi.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXUserApi.h b/samples/client/petstore/cpp-qt/client/PFXUserApi.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXUserApi.h rename to samples/client/petstore/cpp-qt/client/PFXUserApi.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXclient.pri b/samples/client/petstore/cpp-qt/client/PFXclient.pri similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXclient.pri rename to samples/client/petstore/cpp-qt/client/PFXclient.pri diff --git a/samples/client/petstore/cpp-qt5/pom.xml b/samples/client/petstore/cpp-qt/pom.xml similarity index 100% rename from samples/client/petstore/cpp-qt5/pom.xml rename to samples/client/petstore/cpp-qt/pom.xml diff --git a/samples/client/petstore/cpp-qt5/.openapi-generator/VERSION b/samples/client/petstore/cpp-qt5/.openapi-generator/VERSION deleted file mode 100644 index d509cc92aa80..000000000000 --- a/samples/client/petstore/cpp-qt5/.openapi-generator/VERSION +++ /dev/null @@ -1 +0,0 @@ -5.1.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/cpp-restsdk/client/.openapi-generator/VERSION b/samples/client/petstore/cpp-restsdk/client/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/cpp-restsdk/client/.openapi-generator/VERSION +++ b/samples/client/petstore/cpp-restsdk/client/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/cpp-restsdk/client/ApiClient.cpp b/samples/client/petstore/cpp-restsdk/client/ApiClient.cpp index ed3804a63930..cb51123c894d 100644 --- a/samples/client/petstore/cpp-restsdk/client/ApiClient.cpp +++ b/samples/client/petstore/cpp-restsdk/client/ApiClient.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/ApiClient.h b/samples/client/petstore/cpp-restsdk/client/ApiClient.h index 3fe71f4fec92..46e2f100ef29 100644 --- a/samples/client/petstore/cpp-restsdk/client/ApiClient.h +++ b/samples/client/petstore/cpp-restsdk/client/ApiClient.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/ApiConfiguration.cpp b/samples/client/petstore/cpp-restsdk/client/ApiConfiguration.cpp index 728a0ccdc584..52554ff63c7b 100644 --- a/samples/client/petstore/cpp-restsdk/client/ApiConfiguration.cpp +++ b/samples/client/petstore/cpp-restsdk/client/ApiConfiguration.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/ApiConfiguration.h b/samples/client/petstore/cpp-restsdk/client/ApiConfiguration.h index 6251627ba436..74c298a5a94c 100644 --- a/samples/client/petstore/cpp-restsdk/client/ApiConfiguration.h +++ b/samples/client/petstore/cpp-restsdk/client/ApiConfiguration.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/ApiException.cpp b/samples/client/petstore/cpp-restsdk/client/ApiException.cpp index cb21e1298177..bfae070986ee 100644 --- a/samples/client/petstore/cpp-restsdk/client/ApiException.cpp +++ b/samples/client/petstore/cpp-restsdk/client/ApiException.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/ApiException.h b/samples/client/petstore/cpp-restsdk/client/ApiException.h index ec28c60f25b0..cd7915e04e0d 100644 --- a/samples/client/petstore/cpp-restsdk/client/ApiException.h +++ b/samples/client/petstore/cpp-restsdk/client/ApiException.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/HttpContent.cpp b/samples/client/petstore/cpp-restsdk/client/HttpContent.cpp index 8a5d29f45bb2..9de06a9eea1e 100644 --- a/samples/client/petstore/cpp-restsdk/client/HttpContent.cpp +++ b/samples/client/petstore/cpp-restsdk/client/HttpContent.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/HttpContent.h b/samples/client/petstore/cpp-restsdk/client/HttpContent.h index 05cac432a0df..ffba49f782a8 100644 --- a/samples/client/petstore/cpp-restsdk/client/HttpContent.h +++ b/samples/client/petstore/cpp-restsdk/client/HttpContent.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/IHttpBody.h b/samples/client/petstore/cpp-restsdk/client/IHttpBody.h index b54af3c2097f..1a1b0a55e908 100644 --- a/samples/client/petstore/cpp-restsdk/client/IHttpBody.h +++ b/samples/client/petstore/cpp-restsdk/client/IHttpBody.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/JsonBody.cpp b/samples/client/petstore/cpp-restsdk/client/JsonBody.cpp index 91626b210597..658ef28191c8 100644 --- a/samples/client/petstore/cpp-restsdk/client/JsonBody.cpp +++ b/samples/client/petstore/cpp-restsdk/client/JsonBody.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/JsonBody.h b/samples/client/petstore/cpp-restsdk/client/JsonBody.h index 90b3eb906dbc..f9717b9c9bea 100644 --- a/samples/client/petstore/cpp-restsdk/client/JsonBody.h +++ b/samples/client/petstore/cpp-restsdk/client/JsonBody.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/ModelBase.cpp b/samples/client/petstore/cpp-restsdk/client/ModelBase.cpp index fcc6a2cd6d8a..8c02ac7c40d5 100644 --- a/samples/client/petstore/cpp-restsdk/client/ModelBase.cpp +++ b/samples/client/petstore/cpp-restsdk/client/ModelBase.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -260,13 +260,13 @@ bool ModelBase::fromJson( const web::json::value& val, bool & outVal ) } bool ModelBase::fromJson( const web::json::value& val, float & outVal ) { - outVal = !val.is_double() ? std::numeric_limits::quiet_NaN(): static_cast(val.as_double()); - return val.is_double(); + outVal = (!val.is_double() && !val.is_integer()) ? std::numeric_limits::quiet_NaN(): static_cast(val.as_double()); + return val.is_double() || val.is_integer(); } bool ModelBase::fromJson( const web::json::value& val, double & outVal ) { - outVal = !val.is_double() ? std::numeric_limits::quiet_NaN(): val.as_double(); - return val.is_double() ; + outVal = (!val.is_double() && !val.is_integer()) ? std::numeric_limits::quiet_NaN(): val.as_double(); + return val.is_double() || val.is_integer(); } bool ModelBase::fromJson( const web::json::value& val, int32_t & outVal ) { diff --git a/samples/client/petstore/cpp-restsdk/client/ModelBase.h b/samples/client/petstore/cpp-restsdk/client/ModelBase.h index 228969e55c0f..417c04a69e0c 100644 --- a/samples/client/petstore/cpp-restsdk/client/ModelBase.h +++ b/samples/client/petstore/cpp-restsdk/client/ModelBase.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/MultipartFormData.cpp b/samples/client/petstore/cpp-restsdk/client/MultipartFormData.cpp index b979bc4af517..c6c22d581856 100644 --- a/samples/client/petstore/cpp-restsdk/client/MultipartFormData.cpp +++ b/samples/client/petstore/cpp-restsdk/client/MultipartFormData.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/MultipartFormData.h b/samples/client/petstore/cpp-restsdk/client/MultipartFormData.h index 8d1dc908666a..ea1f59b31a41 100644 --- a/samples/client/petstore/cpp-restsdk/client/MultipartFormData.h +++ b/samples/client/petstore/cpp-restsdk/client/MultipartFormData.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/Object.cpp b/samples/client/petstore/cpp-restsdk/client/Object.cpp index 5e5e3fb1ddf4..0c05fe80e4bb 100644 --- a/samples/client/petstore/cpp-restsdk/client/Object.cpp +++ b/samples/client/petstore/cpp-restsdk/client/Object.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/Object.h b/samples/client/petstore/cpp-restsdk/client/Object.h index 38eb4031c4df..fcb51a1da3b4 100644 --- a/samples/client/petstore/cpp-restsdk/client/Object.h +++ b/samples/client/petstore/cpp-restsdk/client/Object.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/api/PetApi.cpp b/samples/client/petstore/cpp-restsdk/client/api/PetApi.cpp index 83a11eec83d2..fe9bcacf4582 100644 --- a/samples/client/petstore/cpp-restsdk/client/api/PetApi.cpp +++ b/samples/client/petstore/cpp-restsdk/client/api/PetApi.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/api/PetApi.h b/samples/client/petstore/cpp-restsdk/client/api/PetApi.h index fc1dbb645afe..694cde1512cc 100644 --- a/samples/client/petstore/cpp-restsdk/client/api/PetApi.h +++ b/samples/client/petstore/cpp-restsdk/client/api/PetApi.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/api/StoreApi.cpp b/samples/client/petstore/cpp-restsdk/client/api/StoreApi.cpp index b16721b01fd6..b60e41cfcfce 100644 --- a/samples/client/petstore/cpp-restsdk/client/api/StoreApi.cpp +++ b/samples/client/petstore/cpp-restsdk/client/api/StoreApi.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/api/StoreApi.h b/samples/client/petstore/cpp-restsdk/client/api/StoreApi.h index 2e14f86c1c57..c5241a6e2d8d 100644 --- a/samples/client/petstore/cpp-restsdk/client/api/StoreApi.h +++ b/samples/client/petstore/cpp-restsdk/client/api/StoreApi.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/api/UserApi.cpp b/samples/client/petstore/cpp-restsdk/client/api/UserApi.cpp index 1f882a6404bf..4927b6785ecb 100644 --- a/samples/client/petstore/cpp-restsdk/client/api/UserApi.cpp +++ b/samples/client/petstore/cpp-restsdk/client/api/UserApi.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/api/UserApi.h b/samples/client/petstore/cpp-restsdk/client/api/UserApi.h index ac86e5a99111..c4aa9ed60249 100644 --- a/samples/client/petstore/cpp-restsdk/client/api/UserApi.h +++ b/samples/client/petstore/cpp-restsdk/client/api/UserApi.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/ApiResponse.cpp b/samples/client/petstore/cpp-restsdk/client/model/ApiResponse.cpp index 5d7b3e3c70c0..e43dcecded18 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/ApiResponse.cpp +++ b/samples/client/petstore/cpp-restsdk/client/model/ApiResponse.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/ApiResponse.h b/samples/client/petstore/cpp-restsdk/client/model/ApiResponse.h index 08e5ae881d1f..f892cedb7f87 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/ApiResponse.h +++ b/samples/client/petstore/cpp-restsdk/client/model/ApiResponse.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/Category.cpp b/samples/client/petstore/cpp-restsdk/client/model/Category.cpp index 07cc8c4795e9..38ee7a831309 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/Category.cpp +++ b/samples/client/petstore/cpp-restsdk/client/model/Category.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/Category.h b/samples/client/petstore/cpp-restsdk/client/model/Category.h index 5dffad3f8181..5aab92bf04d4 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/Category.h +++ b/samples/client/petstore/cpp-restsdk/client/model/Category.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/Order.cpp b/samples/client/petstore/cpp-restsdk/client/model/Order.cpp index 07bc660c60e3..17f40a62a73d 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/Order.cpp +++ b/samples/client/petstore/cpp-restsdk/client/model/Order.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/Order.h b/samples/client/petstore/cpp-restsdk/client/model/Order.h index 952662b984f2..dbe4b2cb7745 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/Order.h +++ b/samples/client/petstore/cpp-restsdk/client/model/Order.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/Pet.cpp b/samples/client/petstore/cpp-restsdk/client/model/Pet.cpp index 63eeecb446de..e7e6228a95f7 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/Pet.cpp +++ b/samples/client/petstore/cpp-restsdk/client/model/Pet.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/Pet.h b/samples/client/petstore/cpp-restsdk/client/model/Pet.h index 37027d2960ae..543a4fed12e5 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/Pet.h +++ b/samples/client/petstore/cpp-restsdk/client/model/Pet.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/Tag.cpp b/samples/client/petstore/cpp-restsdk/client/model/Tag.cpp index 1bcc796db30b..401b81b68931 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/Tag.cpp +++ b/samples/client/petstore/cpp-restsdk/client/model/Tag.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/Tag.h b/samples/client/petstore/cpp-restsdk/client/model/Tag.h index 96efc9b42bbc..f183c7adf9d8 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/Tag.h +++ b/samples/client/petstore/cpp-restsdk/client/model/Tag.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/User.cpp b/samples/client/petstore/cpp-restsdk/client/model/User.cpp index 7a742815920a..3065eb0b5542 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/User.cpp +++ b/samples/client/petstore/cpp-restsdk/client/model/User.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/User.h b/samples/client/petstore/cpp-restsdk/client/model/User.h index 92ab01e42ac4..731b2517d6d1 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/User.h +++ b/samples/client/petstore/cpp-restsdk/client/model/User.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 5.1.1-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 5.2.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/.openapi-generator-ignore b/samples/client/petstore/cpp-tiny/.openapi-generator-ignore similarity index 100% rename from samples/openapi3/server/petstore/php-mezzio-ph/.openapi-generator-ignore rename to samples/client/petstore/cpp-tiny/.openapi-generator-ignore diff --git a/samples/client/petstore/cpp-tiny/.openapi-generator/FILES b/samples/client/petstore/cpp-tiny/.openapi-generator/FILES new file mode 100644 index 000000000000..1024d9450644 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/.openapi-generator/FILES @@ -0,0 +1,30 @@ +README.md +README.md +lib/Models/ApiResponse.cpp +lib/Models/ApiResponse.h +lib/Models/Category.cpp +lib/Models/Category.h +lib/Models/Helpers.cpp +lib/Models/Helpers.h +lib/Models/Order.cpp +lib/Models/Order.h +lib/Models/Pet.cpp +lib/Models/Pet.h +lib/Models/Tag.cpp +lib/Models/Tag.h +lib/Models/User.cpp +lib/Models/User.h +lib/service/AbstractService.cpp +lib/service/AbstractService.h +lib/service/PetApi.cpp +lib/service/PetApi.h +lib/service/Response.h +lib/service/StoreApi.cpp +lib/service/StoreApi.h +lib/service/UserApi.cpp +lib/service/UserApi.h +platformio.ini +pre_compiling_bourne.py +root.cert +src/main.cpp +test/RunTests.cpp diff --git a/samples/client/petstore/cpp-tiny/.openapi-generator/VERSION b/samples/client/petstore/cpp-tiny/.openapi-generator/VERSION new file mode 100644 index 000000000000..6555596f9311 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/cpp-tiny/README.md b/samples/client/petstore/cpp-tiny/README.md new file mode 100644 index 000000000000..e8bf721275b5 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/README.md @@ -0,0 +1,73 @@ +# Documentation for OpenAPI Petstore +This is a client generator for microcontrollers on the Espressif32 platform and the Arduino framework +After the client have been generated, you have to change these following variablies: +- root.cert | Provide your service root certificate. +- src/main.cpp | Change wifi name +- src/main.cpp | Change wifi password +- lib/service/AbstractService.h | Change to your url + +# Documentation for OpenAPI Petstore 1.0.0 Tiny client cpp (Arduino) + +The project is structured like this: +``` +samples/client/petstore/tiny/cpp/ +├── lib +│ ├── Models +│ ├── service +│ └── TestFiles +├── platformio.ini +├── pre_compiling_bourne.py +├── README.md +├── root.cert +├── src +│ └── main.cpp +└── test + └── RunTests.cpp +``` + +All URIs are relative to http://petstore.swagger.iohttp://petstore.swagger.io/v2 + +### PetApi +|Method | HTTP request | Description| +|------------- | ------------- | -------------| +|*addPet* | *POST* /pet | Add a new pet to the store.| +|*deletePet* | *DELETE* /pet/{petId} | Deletes a pet.| +|*findPetsByStatus* | *GET* /pet/findByStatus | Finds Pets by status.| +|*findPetsByTags* | *GET* /pet/findByTags | Finds Pets by tags.| +|*getPetById* | *GET* /pet/{petId} | Find pet by ID.| +|*updatePet* | *PUT* /pet | Update an existing pet.| +|*updatePetWithForm* | *POST* /pet/{petId} | Updates a pet in the store with form data.| +|*uploadFile* | *POST* /pet/{petId}/uploadImage | uploads an image.| + +### StoreApi +|Method | HTTP request | Description| +|------------- | ------------- | -------------| +|*deleteOrder* | *DELETE* /store/order/{orderId} | Delete purchase order by ID.| +|*getInventory* | *GET* /store/inventory | Returns pet inventories by status.| +|*getOrderById* | *GET* /store/order/{orderId} | Find purchase order by ID.| +|*placeOrder* | *POST* /store/order | Place an order for a pet.| + +### UserApi +|Method | HTTP request | Description| +|------------- | ------------- | -------------| +|*createUser* | *POST* /user | Create user.| +|*createUsersWithArrayInput* | *POST* /user/createWithArray | Creates list of users with given input array.| +|*createUsersWithListInput* | *POST* /user/createWithList | Creates list of users with given input array.| +|*deleteUser* | *DELETE* /user/{username} | Delete user.| +|*getUserByName* | *GET* /user/{username} | Get user by user name.| +|*loginUser* | *GET* /user/login | Logs user into the system.| +|*logoutUser* | *GET* /user/logout | Logs out current logged in user session.| +|*updateUser* | *PUT* /user/{username} | Updated user.| + + +## What are the Model files for the data structures/objects? +|Class | Description| +|------------- | -------------| +|*ApiResponse* | Describes the result of uploading an image resource| +|*Category* | A category for a pet| +|*Order* | An order for a pets from the pet store| +|*Pet* | A pet for sale in the pet store| +|*Tag* | A tag for a pet| +|*User* | A User who is purchasing from the pet store| + + diff --git a/samples/client/petstore/cpp-tiny/lib/Models/ApiResponse.cpp b/samples/client/petstore/cpp-tiny/lib/Models/ApiResponse.cpp new file mode 100644 index 000000000000..e9be9e2b6187 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/ApiResponse.cpp @@ -0,0 +1,139 @@ + + +#include "ApiResponse.h" + +using namespace Tiny; + +ApiResponse::ApiResponse() +{ + code = int(0); + type = std::string(); + message = std::string(); +} + +ApiResponse::ApiResponse(std::string jsonString) +{ + this->fromJson(jsonString); +} + +ApiResponse::~ApiResponse() +{ + +} + +void +ApiResponse::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *codeKey = "code"; + + if(object.has_key(codeKey)) + { + bourne::json value = object[codeKey]; + + + + jsonToValue(&code, value, "int"); + + + } + + const char *typeKey = "type"; + + if(object.has_key(typeKey)) + { + bourne::json value = object[typeKey]; + + + + jsonToValue(&type, value, "std::string"); + + + } + + const char *messageKey = "message"; + + if(object.has_key(messageKey)) + { + bourne::json value = object[messageKey]; + + + + jsonToValue(&message, value, "std::string"); + + + } + + +} + +bourne::json +ApiResponse::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["code"] = getCode(); + + + + + + + object["type"] = getType(); + + + + + + + object["message"] = getMessage(); + + + + return object; + +} + +int +ApiResponse::getCode() +{ + return code; +} + +void +ApiResponse::setCode(int code) +{ + this->code = code; +} + +std::string +ApiResponse::getType() +{ + return type; +} + +void +ApiResponse::setType(std::string type) +{ + this->type = type; +} + +std::string +ApiResponse::getMessage() +{ + return message; +} + +void +ApiResponse::setMessage(std::string message) +{ + this->message = message; +} + + + diff --git a/samples/client/petstore/cpp-tiny/lib/Models/ApiResponse.h b/samples/client/petstore/cpp-tiny/lib/Models/ApiResponse.h new file mode 100644 index 000000000000..dbaf8abcaf38 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/ApiResponse.h @@ -0,0 +1,78 @@ + +/* + * ApiResponse.h + * + * Describes the result of uploading an image resource + */ + +#ifndef TINY_CPP_CLIENT_ApiResponse_H_ +#define TINY_CPP_CLIENT_ApiResponse_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief Describes the result of uploading an image resource + * + * \ingroup Models + * + */ + +class ApiResponse{ +public: + + /*! \brief Constructor. + */ + ApiResponse(); + ApiResponse(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~ApiResponse(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + int getCode(); + + /*! \brief Set + */ + void setCode(int code); + /*! \brief Get + */ + std::string getType(); + + /*! \brief Set + */ + void setType(std::string type); + /*! \brief Get + */ + std::string getMessage(); + + /*! \brief Set + */ + void setMessage(std::string message); + + + private: + int code{}; + std::string type{}; + std::string message{}; +}; +} + +#endif /* TINY_CPP_CLIENT_ApiResponse_H_ */ diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Category.cpp b/samples/client/petstore/cpp-tiny/lib/Models/Category.cpp new file mode 100644 index 000000000000..950b06ffd44a --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Category.cpp @@ -0,0 +1,106 @@ + + +#include "Category.h" + +using namespace Tiny; + +Category::Category() +{ + id = long(0); + name = std::string(); +} + +Category::Category(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Category::~Category() +{ + +} + +void +Category::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *nameKey = "name"; + + if(object.has_key(nameKey)) + { + bourne::json value = object[nameKey]; + + + + jsonToValue(&name, value, "std::string"); + + + } + + +} + +bourne::json +Category::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["name"] = getName(); + + + + return object; + +} + +long +Category::getId() +{ + return id; +} + +void +Category::setId(long id) +{ + this->id = id; +} + +std::string +Category::getName() +{ + return name; +} + +void +Category::setName(std::string name) +{ + this->name = name; +} + + + diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Category.h b/samples/client/petstore/cpp-tiny/lib/Models/Category.h new file mode 100644 index 000000000000..9c90e3dd4160 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Category.h @@ -0,0 +1,70 @@ + +/* + * Category.h + * + * A category for a pet + */ + +#ifndef TINY_CPP_CLIENT_Category_H_ +#define TINY_CPP_CLIENT_Category_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief A category for a pet + * + * \ingroup Models + * + */ + +class Category{ +public: + + /*! \brief Constructor. + */ + Category(); + Category(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Category(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + std::string getName(); + + /*! \brief Set + */ + void setName(std::string name); + + + private: + long id{}; + std::string name{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Category_H_ */ diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Helpers.cpp b/samples/client/petstore/cpp-tiny/lib/Models/Helpers.cpp new file mode 100644 index 000000000000..c3935b37cde9 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Helpers.cpp @@ -0,0 +1,102 @@ +#include "Helpers.h" +#include +#include + +bool isprimitive(std::string type){ + if(type == "std::string" || + type == "int" || + type == "float" || + type == "long" || + type == "double" || + type == "bool" || + type == "std::map" || + type == "std::list") + { + return true; + } + return false; +} + + +void +jsonToValue(void* target, bourne::json value, std::string type) +{ + if (target == NULL || value.is_null()) { + return; + } + + else if (type.compare("bool") == 0) + { + bool* val = static_cast (target); + *val = value.to_bool(); + } + + else if (type.compare("int") == 0) + { + int* val = static_cast (target); + *val = value.to_int(); + } + + else if (type.compare("float") == 0) + { + float* val = static_cast (target); + *val = (float)(value.to_float()); + } + + else if (type.compare("long") == 0) + { + long* val = static_cast (target); + *val = (long)(value.to_int()); + } + + else if (type.compare("double") == 0) + { + double* val = static_cast (target); + *val = value.to_float(); + } + + else if (type.compare("std::string") == 0) + { + std::string* val = static_cast (target); + *val = value.to_string(); + } + else { + return; + } +} + +std::string +stringify(long input){ + std::stringstream stream; + stream << input; + return stream.str(); + +}; + +std::string +stringify(int input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(double input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(float input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(std::string input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Helpers.h b/samples/client/petstore/cpp-tiny/lib/Models/Helpers.h new file mode 100644 index 000000000000..5ef7d9afdf77 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Helpers.h @@ -0,0 +1,22 @@ +#ifndef TINY_CPP_CLIENT_HELPERS_H_ +#define TINY_CPP_CLIENT_HELPERS_H_ + +#include +#include "bourne/json.hpp" + +bool isprimitive(std::string type); + +void jsonToValue(void* target, bourne::json value, std::string type); + +std::string stringify(long input); + +std::string stringify(int input); + +std::string stringify(double input); + +std::string stringify(float input); + +std::string stringify(std::string input); + +#endif /* TINY_CPP_CLIENT_HELPERS_H_ */ + diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Order.cpp b/samples/client/petstore/cpp-tiny/lib/Models/Order.cpp new file mode 100644 index 000000000000..b8b7e00d3fc8 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Order.cpp @@ -0,0 +1,238 @@ + + +#include "Order.h" + +using namespace Tiny; + +Order::Order() +{ + id = long(0); + petId = long(0); + quantity = int(0); + shipDate = std::string(); + status = std::string(); + complete = bool(false); +} + +Order::Order(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Order::~Order() +{ + +} + +void +Order::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *petIdKey = "petId"; + + if(object.has_key(petIdKey)) + { + bourne::json value = object[petIdKey]; + + + + jsonToValue(&petId, value, "long"); + + + } + + const char *quantityKey = "quantity"; + + if(object.has_key(quantityKey)) + { + bourne::json value = object[quantityKey]; + + + + jsonToValue(&quantity, value, "int"); + + + } + + const char *shipDateKey = "shipDate"; + + if(object.has_key(shipDateKey)) + { + bourne::json value = object[shipDateKey]; + + + + jsonToValue(&shipDate, value, "std::string"); + + + } + + const char *statusKey = "status"; + + if(object.has_key(statusKey)) + { + bourne::json value = object[statusKey]; + + + + jsonToValue(&status, value, "std::string"); + + + } + + const char *completeKey = "complete"; + + if(object.has_key(completeKey)) + { + bourne::json value = object[completeKey]; + + + + jsonToValue(&complete, value, "bool"); + + + } + + +} + +bourne::json +Order::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["petId"] = getPetId(); + + + + + + + object["quantity"] = getQuantity(); + + + + + + + object["shipDate"] = getShipDate(); + + + + + + + object["status"] = getStatus(); + + + + + + + object["complete"] = isComplete(); + + + + return object; + +} + +long +Order::getId() +{ + return id; +} + +void +Order::setId(long id) +{ + this->id = id; +} + +long +Order::getPetId() +{ + return petId; +} + +void +Order::setPetId(long petId) +{ + this->petId = petId; +} + +int +Order::getQuantity() +{ + return quantity; +} + +void +Order::setQuantity(int quantity) +{ + this->quantity = quantity; +} + +std::string +Order::getShipDate() +{ + return shipDate; +} + +void +Order::setShipDate(std::string shipDate) +{ + this->shipDate = shipDate; +} + +std::string +Order::getStatus() +{ + return status; +} + +void +Order::setStatus(std::string status) +{ + this->status = status; +} + +bool +Order::isComplete() +{ + return complete; +} + +void +Order::setComplete(bool complete) +{ + this->complete = complete; +} + + + diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Order.h b/samples/client/petstore/cpp-tiny/lib/Models/Order.h new file mode 100644 index 000000000000..6f36404f959a --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Order.h @@ -0,0 +1,102 @@ + +/* + * Order.h + * + * An order for a pets from the pet store + */ + +#ifndef TINY_CPP_CLIENT_Order_H_ +#define TINY_CPP_CLIENT_Order_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief An order for a pets from the pet store + * + * \ingroup Models + * + */ + +class Order{ +public: + + /*! \brief Constructor. + */ + Order(); + Order(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Order(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + long getPetId(); + + /*! \brief Set + */ + void setPetId(long petId); + /*! \brief Get + */ + int getQuantity(); + + /*! \brief Set + */ + void setQuantity(int quantity); + /*! \brief Get + */ + std::string getShipDate(); + + /*! \brief Set + */ + void setShipDate(std::string shipDate); + /*! \brief Get Order Status + */ + std::string getStatus(); + + /*! \brief Set Order Status + */ + void setStatus(std::string status); + /*! \brief Get + */ + bool isComplete(); + + /*! \brief Set + */ + void setComplete(bool complete); + + + private: + long id{}; + long petId{}; + int quantity{}; + std::string shipDate{}; + std::string status{}; + bool complete{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Order_H_ */ diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Pet.cpp b/samples/client/petstore/cpp-tiny/lib/Models/Pet.cpp new file mode 100644 index 000000000000..57f7781aef2a --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Pet.cpp @@ -0,0 +1,274 @@ + + +#include "Pet.h" + +using namespace Tiny; + +Pet::Pet() +{ + id = long(0); + category = Category(); + name = std::string(); + photoUrls = std::list(); + tags = std::list(); + status = std::string(); +} + +Pet::Pet(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Pet::~Pet() +{ + +} + +void +Pet::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *categoryKey = "category"; + + if(object.has_key(categoryKey)) + { + bourne::json value = object[categoryKey]; + + + + + Category* obj = &category; + obj->fromJson(value.dump()); + + } + + const char *nameKey = "name"; + + if(object.has_key(nameKey)) + { + bourne::json value = object[nameKey]; + + + + jsonToValue(&name, value, "std::string"); + + + } + + const char *photoUrlsKey = "photoUrls"; + + if(object.has_key(photoUrlsKey)) + { + bourne::json value = object[photoUrlsKey]; + + + std::list photoUrls_list; + std::string element; + for(auto& var : value.array_range()) + { + + jsonToValue(&element, var, "std::string"); + + + photoUrls_list.push_back(element); + } + photoUrls = photoUrls_list; + + + } + + const char *tagsKey = "tags"; + + if(object.has_key(tagsKey)) + { + bourne::json value = object[tagsKey]; + + + std::list tags_list; + Tag element; + for(auto& var : value.array_range()) + { + + + element.fromJson(var.dump()); + + tags_list.push_back(element); + } + tags = tags_list; + + + } + + const char *statusKey = "status"; + + if(object.has_key(statusKey)) + { + bourne::json value = object[statusKey]; + + + + jsonToValue(&status, value, "std::string"); + + + } + + +} + +bourne::json +Pet::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + + object["category"] = getCategory().toJson(); + + + + + + object["name"] = getName(); + + + + + + std::list photoUrls_list = getPhotoUrls(); + bourne::json photoUrls_arr = bourne::json::array(); + + for(auto& var : photoUrls_list) + { + photoUrls_arr.append(var); + } + object["photoUrls"] = photoUrls_arr; + + + + + + + + + std::list tags_list = getTags(); + bourne::json tags_arr = bourne::json::array(); + + for(auto& var : tags_list) + { + Tag obj = var; + tags_arr.append(obj.toJson()); + } + object["tags"] = tags_arr; + + + + + + + + object["status"] = getStatus(); + + + + return object; + +} + +long +Pet::getId() +{ + return id; +} + +void +Pet::setId(long id) +{ + this->id = id; +} + +Category +Pet::getCategory() +{ + return category; +} + +void +Pet::setCategory(Category category) +{ + this->category = category; +} + +std::string +Pet::getName() +{ + return name; +} + +void +Pet::setName(std::string name) +{ + this->name = name; +} + +std::list +Pet::getPhotoUrls() +{ + return photoUrls; +} + +void +Pet::setPhotoUrls(std::list photoUrls) +{ + this->photoUrls = photoUrls; +} + +std::list +Pet::getTags() +{ + return tags; +} + +void +Pet::setTags(std::list tags) +{ + this->tags = tags; +} + +std::string +Pet::getStatus() +{ + return status; +} + +void +Pet::setStatus(std::string status) +{ + this->status = status; +} + + + diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Pet.h b/samples/client/petstore/cpp-tiny/lib/Models/Pet.h new file mode 100644 index 000000000000..3329735f8a16 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Pet.h @@ -0,0 +1,105 @@ + +/* + * Pet.h + * + * A pet for sale in the pet store + */ + +#ifndef TINY_CPP_CLIENT_Pet_H_ +#define TINY_CPP_CLIENT_Pet_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" +#include "Category.h" +#include "Tag.h" +#include + +namespace Tiny { + + +/*! \brief A pet for sale in the pet store + * + * \ingroup Models + * + */ + +class Pet{ +public: + + /*! \brief Constructor. + */ + Pet(); + Pet(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Pet(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + Category getCategory(); + + /*! \brief Set + */ + void setCategory(Category category); + /*! \brief Get + */ + std::string getName(); + + /*! \brief Set + */ + void setName(std::string name); + /*! \brief Get + */ + std::list getPhotoUrls(); + + /*! \brief Set + */ + void setPhotoUrls(std::list photoUrls); + /*! \brief Get + */ + std::list getTags(); + + /*! \brief Set + */ + void setTags(std::list tags); + /*! \brief Get pet status in the store + */ + std::string getStatus(); + + /*! \brief Set pet status in the store + */ + void setStatus(std::string status); + + + private: + long id{}; + Category category; + std::string name{}; + std::list photoUrls; + std::list tags; + std::string status{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Pet_H_ */ diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Tag.cpp b/samples/client/petstore/cpp-tiny/lib/Models/Tag.cpp new file mode 100644 index 000000000000..e46d94258a1d --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Tag.cpp @@ -0,0 +1,106 @@ + + +#include "Tag.h" + +using namespace Tiny; + +Tag::Tag() +{ + id = long(0); + name = std::string(); +} + +Tag::Tag(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Tag::~Tag() +{ + +} + +void +Tag::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *nameKey = "name"; + + if(object.has_key(nameKey)) + { + bourne::json value = object[nameKey]; + + + + jsonToValue(&name, value, "std::string"); + + + } + + +} + +bourne::json +Tag::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["name"] = getName(); + + + + return object; + +} + +long +Tag::getId() +{ + return id; +} + +void +Tag::setId(long id) +{ + this->id = id; +} + +std::string +Tag::getName() +{ + return name; +} + +void +Tag::setName(std::string name) +{ + this->name = name; +} + + + diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Tag.h b/samples/client/petstore/cpp-tiny/lib/Models/Tag.h new file mode 100644 index 000000000000..e05bcdc92900 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Tag.h @@ -0,0 +1,70 @@ + +/* + * Tag.h + * + * A tag for a pet + */ + +#ifndef TINY_CPP_CLIENT_Tag_H_ +#define TINY_CPP_CLIENT_Tag_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief A tag for a pet + * + * \ingroup Models + * + */ + +class Tag{ +public: + + /*! \brief Constructor. + */ + Tag(); + Tag(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Tag(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + std::string getName(); + + /*! \brief Set + */ + void setName(std::string name); + + + private: + long id{}; + std::string name{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Tag_H_ */ diff --git a/samples/client/petstore/cpp-tiny/lib/Models/User.cpp b/samples/client/petstore/cpp-tiny/lib/Models/User.cpp new file mode 100644 index 000000000000..ac84c40205a9 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/User.cpp @@ -0,0 +1,304 @@ + + +#include "User.h" + +using namespace Tiny; + +User::User() +{ + id = long(0); + username = std::string(); + firstName = std::string(); + lastName = std::string(); + email = std::string(); + password = std::string(); + phone = std::string(); + userStatus = int(0); +} + +User::User(std::string jsonString) +{ + this->fromJson(jsonString); +} + +User::~User() +{ + +} + +void +User::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *usernameKey = "username"; + + if(object.has_key(usernameKey)) + { + bourne::json value = object[usernameKey]; + + + + jsonToValue(&username, value, "std::string"); + + + } + + const char *firstNameKey = "firstName"; + + if(object.has_key(firstNameKey)) + { + bourne::json value = object[firstNameKey]; + + + + jsonToValue(&firstName, value, "std::string"); + + + } + + const char *lastNameKey = "lastName"; + + if(object.has_key(lastNameKey)) + { + bourne::json value = object[lastNameKey]; + + + + jsonToValue(&lastName, value, "std::string"); + + + } + + const char *emailKey = "email"; + + if(object.has_key(emailKey)) + { + bourne::json value = object[emailKey]; + + + + jsonToValue(&email, value, "std::string"); + + + } + + const char *passwordKey = "password"; + + if(object.has_key(passwordKey)) + { + bourne::json value = object[passwordKey]; + + + + jsonToValue(&password, value, "std::string"); + + + } + + const char *phoneKey = "phone"; + + if(object.has_key(phoneKey)) + { + bourne::json value = object[phoneKey]; + + + + jsonToValue(&phone, value, "std::string"); + + + } + + const char *userStatusKey = "userStatus"; + + if(object.has_key(userStatusKey)) + { + bourne::json value = object[userStatusKey]; + + + + jsonToValue(&userStatus, value, "int"); + + + } + + +} + +bourne::json +User::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["username"] = getUsername(); + + + + + + + object["firstName"] = getFirstName(); + + + + + + + object["lastName"] = getLastName(); + + + + + + + object["email"] = getEmail(); + + + + + + + object["password"] = getPassword(); + + + + + + + object["phone"] = getPhone(); + + + + + + + object["userStatus"] = getUserStatus(); + + + + return object; + +} + +long +User::getId() +{ + return id; +} + +void +User::setId(long id) +{ + this->id = id; +} + +std::string +User::getUsername() +{ + return username; +} + +void +User::setUsername(std::string username) +{ + this->username = username; +} + +std::string +User::getFirstName() +{ + return firstName; +} + +void +User::setFirstName(std::string firstName) +{ + this->firstName = firstName; +} + +std::string +User::getLastName() +{ + return lastName; +} + +void +User::setLastName(std::string lastName) +{ + this->lastName = lastName; +} + +std::string +User::getEmail() +{ + return email; +} + +void +User::setEmail(std::string email) +{ + this->email = email; +} + +std::string +User::getPassword() +{ + return password; +} + +void +User::setPassword(std::string password) +{ + this->password = password; +} + +std::string +User::getPhone() +{ + return phone; +} + +void +User::setPhone(std::string phone) +{ + this->phone = phone; +} + +int +User::getUserStatus() +{ + return userStatus; +} + +void +User::setUserStatus(int userStatus) +{ + this->userStatus = userStatus; +} + + + diff --git a/samples/client/petstore/cpp-tiny/lib/Models/User.h b/samples/client/petstore/cpp-tiny/lib/Models/User.h new file mode 100644 index 000000000000..84de5204ced8 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/User.h @@ -0,0 +1,118 @@ + +/* + * User.h + * + * A User who is purchasing from the pet store + */ + +#ifndef TINY_CPP_CLIENT_User_H_ +#define TINY_CPP_CLIENT_User_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief A User who is purchasing from the pet store + * + * \ingroup Models + * + */ + +class User{ +public: + + /*! \brief Constructor. + */ + User(); + User(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~User(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + std::string getUsername(); + + /*! \brief Set + */ + void setUsername(std::string username); + /*! \brief Get + */ + std::string getFirstName(); + + /*! \brief Set + */ + void setFirstName(std::string firstName); + /*! \brief Get + */ + std::string getLastName(); + + /*! \brief Set + */ + void setLastName(std::string lastName); + /*! \brief Get + */ + std::string getEmail(); + + /*! \brief Set + */ + void setEmail(std::string email); + /*! \brief Get + */ + std::string getPassword(); + + /*! \brief Set + */ + void setPassword(std::string password); + /*! \brief Get + */ + std::string getPhone(); + + /*! \brief Set + */ + void setPhone(std::string phone); + /*! \brief Get User Status + */ + int getUserStatus(); + + /*! \brief Set User Status + */ + void setUserStatus(int userStatus); + + + private: + long id{}; + std::string username{}; + std::string firstName{}; + std::string lastName{}; + std::string email{}; + std::string password{}; + std::string phone{}; + int userStatus{}; +}; +} + +#endif /* TINY_CPP_CLIENT_User_H_ */ diff --git a/samples/client/petstore/cpp-tiny/lib/TestFiles/ApiResponseTest.cpp b/samples/client/petstore/cpp-tiny/lib/TestFiles/ApiResponseTest.cpp new file mode 100644 index 000000000000..160f4217f5df --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/TestFiles/ApiResponseTest.cpp @@ -0,0 +1,139 @@ + +#include "ApiResponse.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_ApiResponse_code_is_assigned_from_json() +{ + bourne::json input = + { + "code", 1 + }; + + ApiResponse obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getCode()); + + + + + + + + +} + + +void test_ApiResponse_type_is_assigned_from_json() +{ + + + bourne::json input = + { + "type", "hello" + }; + + ApiResponse obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getType().c_str()); + + + + + + +} + + +void test_ApiResponse_message_is_assigned_from_json() +{ + + + bourne::json input = + { + "message", "hello" + }; + + ApiResponse obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getMessage().c_str()); + + + + + + +} + + + +void test_ApiResponse_code_is_converted_to_json() +{ + bourne::json input = + { + "code", 1 + }; + + ApiResponse obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["code"] == output["code"]); + + + + +} + + +void test_ApiResponse_type_is_converted_to_json() +{ + + bourne::json input = + { + "type", "hello" + }; + + ApiResponse obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["type"] == output["type"]); + + + +} + + +void test_ApiResponse_message_is_converted_to_json() +{ + + bourne::json input = + { + "message", "hello" + }; + + ApiResponse obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["message"] == output["message"]); + + + +} + + diff --git a/samples/client/petstore/cpp-tiny/lib/TestFiles/CategoryTest.cpp b/samples/client/petstore/cpp-tiny/lib/TestFiles/CategoryTest.cpp new file mode 100644 index 000000000000..2951856e6a58 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/TestFiles/CategoryTest.cpp @@ -0,0 +1,97 @@ + +#include "Category.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Category_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Category obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_Category_name_is_assigned_from_json() +{ + + + bourne::json input = + { + "name", "hello" + }; + + Category obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getName().c_str()); + + + + + + +} + + + +void test_Category_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Category obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_Category_name_is_converted_to_json() +{ + + bourne::json input = + { + "name", "hello" + }; + + Category obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["name"] == output["name"]); + + + +} + + diff --git a/samples/client/petstore/cpp-tiny/lib/TestFiles/OrderTest.cpp b/samples/client/petstore/cpp-tiny/lib/TestFiles/OrderTest.cpp new file mode 100644 index 000000000000..13125fc8fc5a --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/TestFiles/OrderTest.cpp @@ -0,0 +1,245 @@ + +#include "Order.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Order_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_Order_petId_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "petId", 1 + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getPetId()); + + +} + + +void test_Order_quantity_is_assigned_from_json() +{ + bourne::json input = + { + "quantity", 1 + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getQuantity()); + + + + + + + + +} + + +void test_Order_shipDate_is_assigned_from_json() +{ + + + + + + + + +} + + +void test_Order_status_is_assigned_from_json() +{ + + + bourne::json input = + { + "status", "hello" + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getStatus().c_str()); + + + + + + +} + + +void test_Order_complete_is_assigned_from_json() +{ + + + + + bourne::json input = + { + "complete", true + }; + + Order obj(input.dump()); + + TEST_ASSERT(true == obj.isComplete()); + + + + +} + + + +void test_Order_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_Order_petId_is_converted_to_json() +{ + + + + bourne::json input = + { + "petId", 1 + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["petId"] == output["petId"]); + +} + + +void test_Order_quantity_is_converted_to_json() +{ + bourne::json input = + { + "quantity", 1 + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["quantity"] == output["quantity"]); + + + + +} + + +void test_Order_shipDate_is_converted_to_json() +{ + + + + +} + + +void test_Order_status_is_converted_to_json() +{ + + bourne::json input = + { + "status", "hello" + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["status"] == output["status"]); + + + +} + + +void test_Order_complete_is_converted_to_json() +{ + + + bourne::json input = + { + "complete", true + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["complete"] == output["complete"]); + + +} + + diff --git a/samples/client/petstore/cpp-tiny/lib/TestFiles/PetTest.cpp b/samples/client/petstore/cpp-tiny/lib/TestFiles/PetTest.cpp new file mode 100644 index 000000000000..04dad4640939 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/TestFiles/PetTest.cpp @@ -0,0 +1,145 @@ + +#include "Pet.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Pet_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Pet obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + + +void test_Pet_name_is_assigned_from_json() +{ + + + bourne::json input = + { + "name", "hello" + }; + + Pet obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getName().c_str()); + + + + + + +} + + + + +void test_Pet_status_is_assigned_from_json() +{ + + + bourne::json input = + { + "status", "hello" + }; + + Pet obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getStatus().c_str()); + + + + + + +} + + + +void test_Pet_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Pet obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + + +void test_Pet_name_is_converted_to_json() +{ + + bourne::json input = + { + "name", "hello" + }; + + Pet obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["name"] == output["name"]); + + + +} + + + + +void test_Pet_status_is_converted_to_json() +{ + + bourne::json input = + { + "status", "hello" + }; + + Pet obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["status"] == output["status"]); + + + +} + + diff --git a/samples/client/petstore/cpp-tiny/lib/TestFiles/TagTest.cpp b/samples/client/petstore/cpp-tiny/lib/TestFiles/TagTest.cpp new file mode 100644 index 000000000000..41ea1d0095dd --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/TestFiles/TagTest.cpp @@ -0,0 +1,97 @@ + +#include "Tag.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Tag_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Tag obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_Tag_name_is_assigned_from_json() +{ + + + bourne::json input = + { + "name", "hello" + }; + + Tag obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getName().c_str()); + + + + + + +} + + + +void test_Tag_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Tag obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_Tag_name_is_converted_to_json() +{ + + bourne::json input = + { + "name", "hello" + }; + + Tag obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["name"] == output["name"]); + + + +} + + diff --git a/samples/client/petstore/cpp-tiny/lib/TestFiles/UserTest.cpp b/samples/client/petstore/cpp-tiny/lib/TestFiles/UserTest.cpp new file mode 100644 index 000000000000..689ee582bee3 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/TestFiles/UserTest.cpp @@ -0,0 +1,349 @@ + +#include "User.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_User_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_User_username_is_assigned_from_json() +{ + + + bourne::json input = + { + "username", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getUsername().c_str()); + + + + + + +} + + +void test_User_firstName_is_assigned_from_json() +{ + + + bourne::json input = + { + "firstName", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getFirstName().c_str()); + + + + + + +} + + +void test_User_lastName_is_assigned_from_json() +{ + + + bourne::json input = + { + "lastName", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getLastName().c_str()); + + + + + + +} + + +void test_User_email_is_assigned_from_json() +{ + + + bourne::json input = + { + "email", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getEmail().c_str()); + + + + + + +} + + +void test_User_password_is_assigned_from_json() +{ + + + bourne::json input = + { + "password", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getPassword().c_str()); + + + + + + +} + + +void test_User_phone_is_assigned_from_json() +{ + + + bourne::json input = + { + "phone", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getPhone().c_str()); + + + + + + +} + + +void test_User_userStatus_is_assigned_from_json() +{ + bourne::json input = + { + "userStatus", 1 + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getUserStatus()); + + + + + + + + +} + + + +void test_User_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_User_username_is_converted_to_json() +{ + + bourne::json input = + { + "username", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["username"] == output["username"]); + + + +} + + +void test_User_firstName_is_converted_to_json() +{ + + bourne::json input = + { + "firstName", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["firstName"] == output["firstName"]); + + + +} + + +void test_User_lastName_is_converted_to_json() +{ + + bourne::json input = + { + "lastName", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["lastName"] == output["lastName"]); + + + +} + + +void test_User_email_is_converted_to_json() +{ + + bourne::json input = + { + "email", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["email"] == output["email"]); + + + +} + + +void test_User_password_is_converted_to_json() +{ + + bourne::json input = + { + "password", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["password"] == output["password"]); + + + +} + + +void test_User_phone_is_converted_to_json() +{ + + bourne::json input = + { + "phone", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["phone"] == output["phone"]); + + + +} + + +void test_User_userStatus_is_converted_to_json() +{ + bourne::json input = + { + "userStatus", 1 + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["userStatus"] == output["userStatus"]); + + + + +} + + diff --git a/samples/client/petstore/cpp-tiny/lib/service/AbstractService.cpp b/samples/client/petstore/cpp-tiny/lib/service/AbstractService.cpp new file mode 100644 index 000000000000..ac7e992cecc2 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/AbstractService.cpp @@ -0,0 +1,8 @@ +#include "AbstractService.h" +#include "Arduino.h" + + + +void Tiny::AbstractService::begin(std::string url){ + http.begin(String(url.c_str()), test_root_ca); //HTTPS connection +} diff --git a/samples/client/petstore/cpp-tiny/lib/service/AbstractService.h b/samples/client/petstore/cpp-tiny/lib/service/AbstractService.h new file mode 100644 index 000000000000..07214896d7f2 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/AbstractService.h @@ -0,0 +1,28 @@ +#ifndef TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ +#define TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ + +#include "HTTPClient.h" +#include "Response.h" +namespace Tiny { + +/** +* Class +* Generated with openapi::tiny-cpp-client +*/ +class AbstractService { +public: +HTTPClient http; +std::string basepath = "https://petstore3.swagger.io/api/v3"; // TODO: change to your url + +void begin(std::string url); + +// Go and comment out a certificate in root.cert, if you get an error here +// Certificate from file +const char* test_root_ca = +#include "../../root.cert" +; + +}; // end class +}// namespace Tinyclient + +#endif /* TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ */ diff --git a/samples/client/petstore/cpp-tiny/lib/service/PetApi.cpp b/samples/client/petstore/cpp-tiny/lib/service/PetApi.cpp new file mode 100644 index 000000000000..1fa081a04b4d --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/PetApi.cpp @@ -0,0 +1,418 @@ +#include "PetApi.h" + +using namespace Tiny; + + + + Response< + Pet + > + PetApi:: + addPet( + + Pet pet + + ) + { + std::string url = basepath + "/pet"; // + // Query | + // Headers | + // Form | + // Body | pet + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + + payload = pet.toJson().dump(); + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Pet obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + String + > + PetApi:: + deletePet( + + long petId + , + + std::string apiKey + + ) + { + std::string url = basepath + "/pet/{petId}"; //petId + // Query | + // Headers | apiKey + // Form | + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | DELETE + int httpCode = http.sendRequest("DELETE", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + std::list + > + PetApi:: + findPetsByStatus( + std::list status + + + ) + { + std::string url = basepath + "/pet/findByStatus"; // + // Query | status + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + std::list obj = std::list(); + bourne::json jsonPayload(output_string); + + + + + + + + + + for(auto& var : jsonPayload.array_range()) + { + Pet tmp(var.dump()); + obj.push_back(tmp); + } + + + + + + + + + Response> response(obj, httpCode); + return response; + } + + Response< + std::list + > + PetApi:: + findPetsByTags( + std::list tags + + + ) + { + std::string url = basepath + "/pet/findByTags"; // + // Query | tags + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + std::list obj = std::list(); + bourne::json jsonPayload(output_string); + + + + + + + + + + for(auto& var : jsonPayload.array_range()) + { + Pet tmp(var.dump()); + obj.push_back(tmp); + } + + + + + + + + + Response> response(obj, httpCode); + return response; + } + + Response< + Pet + > + PetApi:: + getPetById( + + long petId + + ) + { + std::string url = basepath + "/pet/{petId}"; //petId + // Query | + // Headers | + // Form | + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Pet obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + Pet + > + PetApi:: + updatePet( + + Pet pet + + ) + { + std::string url = basepath + "/pet"; // + // Query | + // Headers | + // Form | + // Body | pet + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | PUT + http.addHeader("Content-Type", "application/json"); + + + + payload = pet.toJson().dump(); + + int httpCode = http.sendRequest("PUT", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Pet obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + String + > + PetApi:: + updatePetWithForm( + + long petId + , + + std::string name + , + + std::string status + + ) + { + std::string url = basepath + "/pet/{petId}"; //petId + // Query | + // Headers | + // Form | name status + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + ApiResponse + > + PetApi:: + uploadFile( + + long petId + , + + std::string additionalMetadata + , + + std::string file + + ) + { + std::string url = basepath + "/pet/{petId}/uploadImage"; //petId + // Query | + // Headers | + // Form | additionalMetadata file + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + ApiResponse obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + + + diff --git a/samples/client/petstore/cpp-tiny/lib/service/PetApi.h b/samples/client/petstore/cpp-tiny/lib/service/PetApi.h new file mode 100644 index 000000000000..abcb0af0de90 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/PetApi.h @@ -0,0 +1,163 @@ +#ifndef TINY_CPP_CLIENT_PetApi_H_ +#define TINY_CPP_CLIENT_PetApi_H_ + + +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +#include "ApiResponse.h" +#include "Pet.h" + +namespace Tiny { + +/** + * Class + * Generated with openapi::tiny-cpp-client + */ + +class PetApi : public AbstractService { +public: + PetApi() = default; + + virtual ~PetApi() = default; + + /** + * Add a new pet to the store. + * + * + * \param pet Pet object that needs to be added to the store *Required* + */ + Response< + Pet + > + addPet( + + Pet pet + + ); + /** + * Deletes a pet. + * + * + * \param petId Pet id to delete *Required* + * \param apiKey + */ + Response< + String + > + deletePet( + + long petId + , + + std::string apiKey + + ); + /** + * Finds Pets by status. + * + * Multiple status values can be provided with comma separated strings + * \param status Status values that need to be considered for filter *Required* + */ + Response< + std::list + > + findPetsByStatus( + std::list status + + + ); + /** + * Finds Pets by tags. + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * \param tags Tags to filter by *Required* + */ + Response< + std::list + > + findPetsByTags( + std::list tags + + + ); + /** + * Find pet by ID. + * + * Returns a single pet + * \param petId ID of pet to return *Required* + */ + Response< + Pet + > + getPetById( + + long petId + + ); + /** + * Update an existing pet. + * + * + * \param pet Pet object that needs to be added to the store *Required* + */ + Response< + Pet + > + updatePet( + + Pet pet + + ); + /** + * Updates a pet in the store with form data. + * + * + * \param petId ID of pet that needs to be updated *Required* + * \param name Updated name of the pet + * \param status Updated status of the pet + */ + Response< + String + > + updatePetWithForm( + + long petId + , + + std::string name + , + + std::string status + + ); + /** + * uploads an image. + * + * + * \param petId ID of pet to update *Required* + * \param additionalMetadata Additional data to pass to server + * \param file file to upload + */ + Response< + ApiResponse + > + uploadFile( + + long petId + , + + std::string additionalMetadata + , + + std::string file + + ); +}; + +} + +#endif /* TINY_CPP_CLIENT_PetApi_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/cpp-tiny/lib/service/Response.h b/samples/client/petstore/cpp-tiny/lib/service/Response.h new file mode 100644 index 000000000000..9b7b616b8f1b --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/Response.h @@ -0,0 +1,25 @@ +#ifndef TINY_CPP_CLIENT_RESPONSE_H_ +#define TINY_CPP_CLIENT_RESPONSE_H_ +#include + +namespace Tiny { + +/** +* Class +* Generated with openapi::tiny-cpp-client +*/ +template + class Response { + public: + + Response(T _obj, int _code){ + obj = _obj; + code = _code; + } + + int code; + T obj; + }; + } // namespace Tinyclient + +#endif /* TINY_CPP_CLIENT_RESPONSE_H_ */ diff --git a/samples/client/petstore/cpp-tiny/lib/service/StoreApi.cpp b/samples/client/petstore/cpp-tiny/lib/service/StoreApi.cpp new file mode 100644 index 000000000000..210eb8277ac6 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/StoreApi.cpp @@ -0,0 +1,185 @@ +#include "StoreApi.h" + +using namespace Tiny; + + + + Response< + String + > + StoreApi:: + deleteOrder( + + std::string orderId + + ) + { + std::string url = basepath + "/store/order/{orderId}"; //orderId + // Query | + // Headers | + // Form | + // Body | + + std::string s_orderId("{"); + s_orderId.append("orderId"); + s_orderId.append("}"); + + int pos = url.find(s_orderId); + + url.erase(pos, s_orderId.length()); + url.insert(pos, stringify(orderId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | DELETE + int httpCode = http.sendRequest("DELETE", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + StoreApi:: + getInventory( + ) + { + std::string url = basepath + "/store/inventory"; // + // Query | + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + //TODO: Implement map logic here + + + + + //TODO: No support for maps. + Response response(output, httpCode); + return response; + } + + Response< + Order + > + StoreApi:: + getOrderById( + + long orderId + + ) + { + std::string url = basepath + "/store/order/{orderId}"; //orderId + // Query | + // Headers | + // Form | + // Body | + + std::string s_orderId("{"); + s_orderId.append("orderId"); + s_orderId.append("}"); + + int pos = url.find(s_orderId); + + url.erase(pos, s_orderId.length()); + url.insert(pos, stringify(orderId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Order obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + Order + > + StoreApi:: + placeOrder( + + Order order + + ) + { + std::string url = basepath + "/store/order"; // + // Query | + // Headers | + // Form | + // Body | order + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + + payload = order.toJson().dump(); + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Order obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + + + diff --git a/samples/client/petstore/cpp-tiny/lib/service/StoreApi.h b/samples/client/petstore/cpp-tiny/lib/service/StoreApi.h new file mode 100644 index 000000000000..1bf0db023737 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/StoreApi.h @@ -0,0 +1,83 @@ +#ifndef TINY_CPP_CLIENT_StoreApi_H_ +#define TINY_CPP_CLIENT_StoreApi_H_ + + +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +#include +#include "Order.h" + +namespace Tiny { + +/** + * Class + * Generated with openapi::tiny-cpp-client + */ + +class StoreApi : public AbstractService { +public: + StoreApi() = default; + + virtual ~StoreApi() = default; + + /** + * Delete purchase order by ID. + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * \param orderId ID of the order that needs to be deleted *Required* + */ + Response< + String + > + deleteOrder( + + std::string orderId + + ); + /** + * Returns pet inventories by status. + * + * Returns a map of status codes to quantities + */ + Response< + String + > + getInventory( + ); + /** + * Find purchase order by ID. + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * \param orderId ID of pet that needs to be fetched *Required* + */ + Response< + Order + > + getOrderById( + + long orderId + + ); + /** + * Place an order for a pet. + * + * + * \param order order placed for purchasing the pet *Required* + */ + Response< + Order + > + placeOrder( + + Order order + + ); +}; + +} + +#endif /* TINY_CPP_CLIENT_StoreApi_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/cpp-tiny/lib/service/UserApi.cpp b/samples/client/petstore/cpp-tiny/lib/service/UserApi.cpp new file mode 100644 index 000000000000..d1cf12b80a9e --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/UserApi.cpp @@ -0,0 +1,366 @@ +#include "UserApi.h" + +using namespace Tiny; + + + + Response< + String + > + UserApi:: + createUser( + + User user + + ) + { + std::string url = basepath + "/user"; // + // Query | + // Headers | + // Form | + // Body | user + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + + payload = user.toJson().dump(); + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + createUsersWithArrayInput( + std::list user + + + ) + { + std::string url = basepath + "/user/createWithArray"; // + // Query | + // Headers | + // Form | + // Body | user + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + bourne::json tmp_arr = bourne::json::array(); + for(auto& var : user) + { + auto tmp = var.toJson(); + tmp_arr.append(tmp); + + } + payload = tmp_arr.dump(); + + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + createUsersWithListInput( + std::list user + + + ) + { + std::string url = basepath + "/user/createWithList"; // + // Query | + // Headers | + // Form | + // Body | user + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + bourne::json tmp_arr = bourne::json::array(); + for(auto& var : user) + { + auto tmp = var.toJson(); + tmp_arr.append(tmp); + + } + payload = tmp_arr.dump(); + + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + deleteUser( + + std::string username + + ) + { + std::string url = basepath + "/user/{username}"; //username + // Query | + // Headers | + // Form | + // Body | + + std::string s_username("{"); + s_username.append("username"); + s_username.append("}"); + + int pos = url.find(s_username); + + url.erase(pos, s_username.length()); + url.insert(pos, stringify(username)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | DELETE + int httpCode = http.sendRequest("DELETE", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + User + > + UserApi:: + getUserByName( + + std::string username + + ) + { + std::string url = basepath + "/user/{username}"; //username + // Query | + // Headers | + // Form | + // Body | + + std::string s_username("{"); + s_username.append("username"); + s_username.append("}"); + + int pos = url.find(s_username); + + url.erase(pos, s_username.length()); + url.insert(pos, stringify(username)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + User obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + std::string + > + UserApi:: + loginUser( + + std::string username + , + + std::string password + + ) + { + std::string url = basepath + "/user/login"; // + // Query | username password + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + bourne::json jsonPayload(output_string); + std::string obj; + jsonToValue(&obj, jsonPayload, "std::string"); + + + + Response response(obj, httpCode); + return response; + } + + Response< + String + > + UserApi:: + logoutUser( + ) + { + std::string url = basepath + "/user/logout"; // + // Query | + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + updateUser( + + std::string username + , + + User user + + ) + { + std::string url = basepath + "/user/{username}"; //username + // Query | + // Headers | + // Form | + // Body | user + + std::string s_username("{"); + s_username.append("username"); + s_username.append("}"); + + int pos = url.find(s_username); + + url.erase(pos, s_username.length()); + url.insert(pos, stringify(username)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | PUT + http.addHeader("Content-Type", "application/json"); + + + + payload = user.toJson().dump(); + + int httpCode = http.sendRequest("PUT", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + + + diff --git a/samples/client/petstore/cpp-tiny/lib/service/UserApi.h b/samples/client/petstore/cpp-tiny/lib/service/UserApi.h new file mode 100644 index 000000000000..afdaefa0f8c9 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/UserApi.h @@ -0,0 +1,147 @@ +#ifndef TINY_CPP_CLIENT_UserApi_H_ +#define TINY_CPP_CLIENT_UserApi_H_ + + +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +#include "User.h" +#include + +namespace Tiny { + +/** + * Class + * Generated with openapi::tiny-cpp-client + */ + +class UserApi : public AbstractService { +public: + UserApi() = default; + + virtual ~UserApi() = default; + + /** + * Create user. + * + * This can only be done by the logged in user. + * \param user Created user object *Required* + */ + Response< + String + > + createUser( + + User user + + ); + /** + * Creates list of users with given input array. + * + * + * \param user List of user object *Required* + */ + Response< + String + > + createUsersWithArrayInput( + std::list user + + + ); + /** + * Creates list of users with given input array. + * + * + * \param user List of user object *Required* + */ + Response< + String + > + createUsersWithListInput( + std::list user + + + ); + /** + * Delete user. + * + * This can only be done by the logged in user. + * \param username The name that needs to be deleted *Required* + */ + Response< + String + > + deleteUser( + + std::string username + + ); + /** + * Get user by user name. + * + * + * \param username The name that needs to be fetched. Use user1 for testing. *Required* + */ + Response< + User + > + getUserByName( + + std::string username + + ); + /** + * Logs user into the system. + * + * + * \param username The user name for login *Required* + * \param password The password for login in clear text *Required* + */ + Response< + std::string + > + loginUser( + + std::string username + , + + std::string password + + ); + /** + * Logs out current logged in user session. + * + * + */ + Response< + String + > + logoutUser( + ); + /** + * Updated user. + * + * This can only be done by the logged in user. + * \param username name that need to be deleted *Required* + * \param user Updated user object *Required* + */ + Response< + String + > + updateUser( + + std::string username + , + + User user + + ); +}; + +} + +#endif /* TINY_CPP_CLIENT_UserApi_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/cpp-tiny/platformio.ini b/samples/client/petstore/cpp-tiny/platformio.ini new file mode 100644 index 000000000000..00781178d10b --- /dev/null +++ b/samples/client/petstore/cpp-tiny/platformio.ini @@ -0,0 +1,7 @@ +[env:esp32] +platform = espressif32 +board = nodemcu-32s +framework = arduino +lib_deps = https://github.com/steinwurf/bourne.git +extra_scripts = pre_compiling_bourne.py + diff --git a/samples/client/petstore/cpp-tiny/pre_compiling_bourne.py b/samples/client/petstore/cpp-tiny/pre_compiling_bourne.py new file mode 100644 index 000000000000..96356dcdf158 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/pre_compiling_bourne.py @@ -0,0 +1,25 @@ +Import("env") + +## Compatibility for bourne to work on microcontrollers +# We insert '#define _GLIBCXX_USE_C99' in files that use std::stoll or std::to_string +def insert_c99_into(file): + import fileinput + + path = env['PROJECT_LIBDEPS_DIR'] + "/" + env['PIOENV'] + "/bourne/src/bourne/" + file + value = '#define _GLIBCXX_USE_C99 1\n' + + for line in fileinput.FileInput(path,inplace=1): + if line.startswith('#define _GLIBCXX_USE_C99'): + continue + elif line.startswith('// D'): + line=line.replace(line,line+value) + print(line, end='') + +def fix_parser(): + insert_c99_into('detail/parser.cpp') + +def fix_json(): + insert_c99_into('json.cpp') + +fix_parser() +fix_json() \ No newline at end of file diff --git a/samples/client/petstore/cpp-tiny/root.cert b/samples/client/petstore/cpp-tiny/root.cert new file mode 100644 index 000000000000..bad9c08efad1 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/root.cert @@ -0,0 +1,53 @@ +// TODO: Provide your service root certificate. +// Below is two examples of root certificates. + +// Let's encrypt root certificate +/** +"-----BEGIN CERTIFICATE-----\n" \ +"MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n" \ +"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" \ +"d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n" \ +"QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n" \ +"MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n" \ +"b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n" \ +"9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n" \ +"CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n" \ +"nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n" \ +"43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n" \ +"T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n" \ +"gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n" \ +"BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n" \ +"TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n" \ +"DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n" \ +"hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n" \ +"06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n" \ +"PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n" \ +"YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n" \ +"CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n" \ +"-----END CERTIFICATE-----\n" +*/ + +// Amazon_Root_CA_1.pem +/** +"-----BEGIN CERTIFICATE-----\n" \ +"MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\n" \ +"ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n" \ +"b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\n" \ +"MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\n" \ +"b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\n" \ +"ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\n" \ +"9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\n" \ +"IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\n" \ +"VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L\n" \ +"93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm\n" \ +"jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n" \ +"AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\n" \ +"A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\n" \ +"U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\n" \ +"N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv\n" \ +"o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\n" \ +"5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\n" \ +"rqXRfboQnoZsG4q5WTP468SQvvG5\n" \ +"-----END CERTIFICATE-----\n" \ +*/ + diff --git a/samples/client/petstore/cpp-tiny/src/main.cpp b/samples/client/petstore/cpp-tiny/src/main.cpp new file mode 100644 index 000000000000..34ba455fbdd3 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/src/main.cpp @@ -0,0 +1,37 @@ +#include "PetApi.h" + +const char* ssid = "your wifi name"; // TODO Change wifi name +const char* password = "Your wifi password"; //TODO Change wifi password + + +void setup(){ + //Initialize serial and wait for port to open: + Serial.begin(9600); + delay(100); + + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + WiFi.begin(ssid, password); + + // attempt to connect to Wifi network: + while (WiFi.status() != WL_CONNECTED) { + Serial.print("."); + // wait 1 second for re-trying + delay(1000); + } + + Serial.print("Connected to "); + Serial.println(ssid); + + //Print LAN IP. + Serial.print("IP address set: "); + Serial.println(WiFi.localIP()); + + Tiny::PetApi petapi; + auto resp = petapi.getPetById(10); + Serial.println(resp.code); + Tiny::Pet pet = resp.obj; + Serial.println(pet.toJson().dump().c_str()); +} + +void loop(){} diff --git a/samples/client/petstore/cpp-tiny/test/RunTests.cpp b/samples/client/petstore/cpp-tiny/test/RunTests.cpp new file mode 100644 index 000000000000..4caafb4ee441 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/test/RunTests.cpp @@ -0,0 +1,204 @@ + +#include "ApiResponseTest.cpp" + +#include "CategoryTest.cpp" + +#include "OrderTest.cpp" + +#include "PetTest.cpp" + +#include "TagTest.cpp" + +#include "UserTest.cpp" + + + +void setUp(){} + +void tearDown(){} + +void runTests(){ + + + RUN_TEST(test_ApiResponse_code_is_assigned_from_json); + + + RUN_TEST(test_ApiResponse_type_is_assigned_from_json); + + + RUN_TEST(test_ApiResponse_message_is_assigned_from_json); + + + + RUN_TEST(test_Category_id_is_assigned_from_json); + + + RUN_TEST(test_Category_name_is_assigned_from_json); + + + + RUN_TEST(test_Order_id_is_assigned_from_json); + + + RUN_TEST(test_Order_petId_is_assigned_from_json); + + + RUN_TEST(test_Order_quantity_is_assigned_from_json); + + + RUN_TEST(test_Order_shipDate_is_assigned_from_json); + + + RUN_TEST(test_Order_status_is_assigned_from_json); + + + RUN_TEST(test_Order_complete_is_assigned_from_json); + + + + RUN_TEST(test_Pet_id_is_assigned_from_json); + + + + RUN_TEST(test_Pet_name_is_assigned_from_json); + + + + + RUN_TEST(test_Pet_status_is_assigned_from_json); + + + + RUN_TEST(test_Tag_id_is_assigned_from_json); + + + RUN_TEST(test_Tag_name_is_assigned_from_json); + + + + RUN_TEST(test_User_id_is_assigned_from_json); + + + RUN_TEST(test_User_username_is_assigned_from_json); + + + RUN_TEST(test_User_firstName_is_assigned_from_json); + + + RUN_TEST(test_User_lastName_is_assigned_from_json); + + + RUN_TEST(test_User_email_is_assigned_from_json); + + + RUN_TEST(test_User_password_is_assigned_from_json); + + + RUN_TEST(test_User_phone_is_assigned_from_json); + + + RUN_TEST(test_User_userStatus_is_assigned_from_json); + + + + + + RUN_TEST(test_ApiResponse_code_is_converted_to_json); + + + RUN_TEST(test_ApiResponse_type_is_converted_to_json); + + + RUN_TEST(test_ApiResponse_message_is_converted_to_json); + + + + RUN_TEST(test_Category_id_is_converted_to_json); + + + RUN_TEST(test_Category_name_is_converted_to_json); + + + + RUN_TEST(test_Order_id_is_converted_to_json); + + + RUN_TEST(test_Order_petId_is_converted_to_json); + + + RUN_TEST(test_Order_quantity_is_converted_to_json); + + + RUN_TEST(test_Order_shipDate_is_converted_to_json); + + + RUN_TEST(test_Order_status_is_converted_to_json); + + + RUN_TEST(test_Order_complete_is_converted_to_json); + + + + RUN_TEST(test_Pet_id_is_converted_to_json); + + + + RUN_TEST(test_Pet_name_is_converted_to_json); + + + + + RUN_TEST(test_Pet_status_is_converted_to_json); + + + + RUN_TEST(test_Tag_id_is_converted_to_json); + + + RUN_TEST(test_Tag_name_is_converted_to_json); + + + + RUN_TEST(test_User_id_is_converted_to_json); + + + RUN_TEST(test_User_username_is_converted_to_json); + + + RUN_TEST(test_User_firstName_is_converted_to_json); + + + RUN_TEST(test_User_lastName_is_converted_to_json); + + + RUN_TEST(test_User_email_is_converted_to_json); + + + RUN_TEST(test_User_password_is_converted_to_json); + + + RUN_TEST(test_User_phone_is_converted_to_json); + + + RUN_TEST(test_User_userStatus_is_converted_to_json); + + + + +} + +int main(void) { + UNITY_BEGIN(); + runTests(); + return UNITY_END(); +} + +void setup() { + UNITY_BEGIN(); + runTests(); + UNITY_END(); +} + +void loop() { + +} diff --git a/samples/client/petstore/cpp-ue4/.openapi-generator/VERSION b/samples/client/petstore/cpp-ue4/.openapi-generator/VERSION index c30f0ec2be7f..d509cc92aa80 100644 --- a/samples/client/petstore/cpp-ue4/.openapi-generator/VERSION +++ b/samples/client/petstore/cpp-ue4/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.0-SNAPSHOT \ No newline at end of file +5.1.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/cpp-ue4/Private/OpenAPIBaseModel.cpp b/samples/client/petstore/cpp-ue4/Private/OpenAPIBaseModel.cpp index b277e2570285..f8552ac0b7d9 100644 --- a/samples/client/petstore/cpp-ue4/Private/OpenAPIBaseModel.cpp +++ b/samples/client/petstore/cpp-ue4/Private/OpenAPIBaseModel.cpp @@ -12,11 +12,28 @@ #include "OpenAPIBaseModel.h" -#include "Async/Async.h" - namespace OpenAPI { +bool HttpRetryManager::Tick(float DeltaTime) +{ + FManager::Update(); + return true; +} + +HttpRetryParams::HttpRetryParams(const FRetryLimitCountSetting& InRetryLimitCountOverride /*= FRetryLimitCountSetting()*/, + const FRetryTimeoutRelativeSecondsSetting& InRetryTimeoutRelativeSecondsOverride /*= FRetryTimeoutRelativeSecondsSetting()*/, + const FRetryResponseCodes& InRetryResponseCodes /*= FRetryResponseCodes()*/, + const FRetryVerbs& InRetryVerbs /*= FRetryVerbs()*/, + const FRetryDomainsPtr& InRetryDomains /*= FRetryDomainsPtr() */) + : RetryLimitCountOverride(InRetryLimitCountOverride) + , RetryTimeoutRelativeSecondsOverride(InRetryTimeoutRelativeSecondsOverride) + , RetryResponseCodes(InRetryResponseCodes) + , RetryVerbs(InRetryVerbs) + , RetryDomains(InRetryDomains) +{ +} + void Response::SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode) { ResponseCode = InHttpResponseCode; @@ -27,13 +44,4 @@ void Response::SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode) } } -void Response::AsyncRetry() const -{ - // Unfortunately, it is currently usafe to call ProcessRequest() directly here. - // This is because the HttpManager will remove all references to this HttpRequest in FHttpManager::Tick including the new request we just added, instead of removing just one. - // This will lead to the request's destruction and eventually a crash. - // The only solution is therefore to ensure we are taking an extra reference to the request, and that the request is added after the queue is flushed. - Async(EAsyncExecution::TaskGraph, [AddRef = FHttpRequestPtr(GetHttpRequest())](){ AddRef->ProcessRequest(); }); -} - } diff --git a/samples/client/petstore/cpp-ue4/Private/OpenAPIPetApi.cpp b/samples/client/petstore/cpp-ue4/Private/OpenAPIPetApi.cpp index 68a0d933aca7..72d2c58ea6e1 100644 --- a/samples/client/petstore/cpp-ue4/Private/OpenAPIPetApi.cpp +++ b/samples/client/petstore/cpp-ue4/Private/OpenAPIPetApi.cpp @@ -54,6 +54,40 @@ bool OpenAPIPetApi::IsValid() const return true; } +void OpenAPIPetApi::SetHttpRetryManager(FHttpRetrySystem::FManager& InRetryManager) +{ + if(RetryManager != &GetHttpRetryManager()) + { + DefaultRetryManager.Reset(); + RetryManager = &InRetryManager; + } +} + +FHttpRetrySystem::FManager& OpenAPIPetApi::GetHttpRetryManager() +{ + return *RetryManager; +} + +FHttpRequestRef OpenAPIPetApi::CreateHttpRequest(const Request& Request) const +{ + if (!Request.GetRetryParams().IsSet()) + { + return FHttpModule::Get().CreateRequest(); + } + else + { + if (!RetryManager) + { + // Create default retry manager if none was specified + DefaultRetryManager = MakeUnique(6, 60); + RetryManager = DefaultRetryManager.Get(); + } + + const HttpRetryParams& Params = Request.GetRetryParams().GetValue(); + return RetryManager->CreateRequest(Params.RetryLimitCountOverride, Params.RetryTimeoutRelativeSecondsOverride, Params.RetryResponseCodes, Params.RetryVerbs, Params.RetryDomains); + } +} + void OpenAPIPetApi::HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const { InOutResponse.SetHttpResponse(HttpResponse); @@ -103,7 +137,7 @@ bool OpenAPIPetApi::AddPet(const AddPetRequest& Request, const FAddPetDelegate& if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -113,26 +147,15 @@ bool OpenAPIPetApi::AddPet(const AddPetRequest& Request, const FAddPetDelegate& Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnAddPetResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnAddPetResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIPetApi::OnAddPetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAddPetDelegate Delegate, int AutoRetryCount) const +void OpenAPIPetApi::OnAddPetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAddPetDelegate Delegate) const { AddPetResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnAddPetResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIPetApi::DeletePet(const DeletePetRequest& Request, const FDeletePetDelegate& Delegate /*= FDeletePetDelegate()*/) const @@ -140,7 +163,7 @@ bool OpenAPIPetApi::DeletePet(const DeletePetRequest& Request, const FDeletePetD if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -150,26 +173,15 @@ bool OpenAPIPetApi::DeletePet(const DeletePetRequest& Request, const FDeletePetD Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnDeletePetResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnDeletePetResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIPetApi::OnDeletePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeletePetDelegate Delegate, int AutoRetryCount) const +void OpenAPIPetApi::OnDeletePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeletePetDelegate Delegate) const { DeletePetResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnDeletePetResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIPetApi::FindPetsByStatus(const FindPetsByStatusRequest& Request, const FFindPetsByStatusDelegate& Delegate /*= FFindPetsByStatusDelegate()*/) const @@ -177,7 +189,7 @@ bool OpenAPIPetApi::FindPetsByStatus(const FindPetsByStatusRequest& Request, con if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -187,26 +199,15 @@ bool OpenAPIPetApi::FindPetsByStatus(const FindPetsByStatusRequest& Request, con Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnFindPetsByStatusResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnFindPetsByStatusResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIPetApi::OnFindPetsByStatusResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByStatusDelegate Delegate, int AutoRetryCount) const +void OpenAPIPetApi::OnFindPetsByStatusResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByStatusDelegate Delegate) const { FindPetsByStatusResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnFindPetsByStatusResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIPetApi::FindPetsByTags(const FindPetsByTagsRequest& Request, const FFindPetsByTagsDelegate& Delegate /*= FFindPetsByTagsDelegate()*/) const @@ -214,7 +215,7 @@ bool OpenAPIPetApi::FindPetsByTags(const FindPetsByTagsRequest& Request, const F if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -224,26 +225,15 @@ bool OpenAPIPetApi::FindPetsByTags(const FindPetsByTagsRequest& Request, const F Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnFindPetsByTagsResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnFindPetsByTagsResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIPetApi::OnFindPetsByTagsResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByTagsDelegate Delegate, int AutoRetryCount) const +void OpenAPIPetApi::OnFindPetsByTagsResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByTagsDelegate Delegate) const { FindPetsByTagsResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnFindPetsByTagsResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIPetApi::GetPetById(const GetPetByIdRequest& Request, const FGetPetByIdDelegate& Delegate /*= FGetPetByIdDelegate()*/) const @@ -251,7 +241,7 @@ bool OpenAPIPetApi::GetPetById(const GetPetByIdRequest& Request, const FGetPetBy if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -261,26 +251,15 @@ bool OpenAPIPetApi::GetPetById(const GetPetByIdRequest& Request, const FGetPetBy Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnGetPetByIdResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnGetPetByIdResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIPetApi::OnGetPetByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPetByIdDelegate Delegate, int AutoRetryCount) const +void OpenAPIPetApi::OnGetPetByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPetByIdDelegate Delegate) const { GetPetByIdResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnGetPetByIdResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIPetApi::UpdatePet(const UpdatePetRequest& Request, const FUpdatePetDelegate& Delegate /*= FUpdatePetDelegate()*/) const @@ -288,7 +267,7 @@ bool OpenAPIPetApi::UpdatePet(const UpdatePetRequest& Request, const FUpdatePetD if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -298,26 +277,15 @@ bool OpenAPIPetApi::UpdatePet(const UpdatePetRequest& Request, const FUpdatePetD Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUpdatePetResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUpdatePetResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIPetApi::OnUpdatePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetDelegate Delegate, int AutoRetryCount) const +void OpenAPIPetApi::OnUpdatePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetDelegate Delegate) const { UpdatePetResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUpdatePetResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIPetApi::UpdatePetWithForm(const UpdatePetWithFormRequest& Request, const FUpdatePetWithFormDelegate& Delegate /*= FUpdatePetWithFormDelegate()*/) const @@ -325,7 +293,7 @@ bool OpenAPIPetApi::UpdatePetWithForm(const UpdatePetWithFormRequest& Request, c if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -335,26 +303,15 @@ bool OpenAPIPetApi::UpdatePetWithForm(const UpdatePetWithFormRequest& Request, c Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUpdatePetWithFormResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUpdatePetWithFormResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIPetApi::OnUpdatePetWithFormResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetWithFormDelegate Delegate, int AutoRetryCount) const +void OpenAPIPetApi::OnUpdatePetWithFormResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetWithFormDelegate Delegate) const { UpdatePetWithFormResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUpdatePetWithFormResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIPetApi::UploadFile(const UploadFileRequest& Request, const FUploadFileDelegate& Delegate /*= FUploadFileDelegate()*/) const @@ -362,7 +319,7 @@ bool OpenAPIPetApi::UploadFile(const UploadFileRequest& Request, const FUploadFi if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -372,26 +329,15 @@ bool OpenAPIPetApi::UploadFile(const UploadFileRequest& Request, const FUploadFi Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUploadFileResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUploadFileResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIPetApi::OnUploadFileResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUploadFileDelegate Delegate, int AutoRetryCount) const +void OpenAPIPetApi::OnUploadFileResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUploadFileDelegate Delegate) const { UploadFileResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIPetApi::OnUploadFileResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } } diff --git a/samples/client/petstore/cpp-ue4/Private/OpenAPIStoreApi.cpp b/samples/client/petstore/cpp-ue4/Private/OpenAPIStoreApi.cpp index 32000a959073..ed25814006e0 100644 --- a/samples/client/petstore/cpp-ue4/Private/OpenAPIStoreApi.cpp +++ b/samples/client/petstore/cpp-ue4/Private/OpenAPIStoreApi.cpp @@ -54,6 +54,40 @@ bool OpenAPIStoreApi::IsValid() const return true; } +void OpenAPIStoreApi::SetHttpRetryManager(FHttpRetrySystem::FManager& InRetryManager) +{ + if(RetryManager != &GetHttpRetryManager()) + { + DefaultRetryManager.Reset(); + RetryManager = &InRetryManager; + } +} + +FHttpRetrySystem::FManager& OpenAPIStoreApi::GetHttpRetryManager() +{ + return *RetryManager; +} + +FHttpRequestRef OpenAPIStoreApi::CreateHttpRequest(const Request& Request) const +{ + if (!Request.GetRetryParams().IsSet()) + { + return FHttpModule::Get().CreateRequest(); + } + else + { + if (!RetryManager) + { + // Create default retry manager if none was specified + DefaultRetryManager = MakeUnique(6, 60); + RetryManager = DefaultRetryManager.Get(); + } + + const HttpRetryParams& Params = Request.GetRetryParams().GetValue(); + return RetryManager->CreateRequest(Params.RetryLimitCountOverride, Params.RetryTimeoutRelativeSecondsOverride, Params.RetryResponseCodes, Params.RetryVerbs, Params.RetryDomains); + } +} + void OpenAPIStoreApi::HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const { InOutResponse.SetHttpResponse(HttpResponse); @@ -103,7 +137,7 @@ bool OpenAPIStoreApi::DeleteOrder(const DeleteOrderRequest& Request, const FDele if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -113,26 +147,15 @@ bool OpenAPIStoreApi::DeleteOrder(const DeleteOrderRequest& Request, const FDele Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnDeleteOrderResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnDeleteOrderResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIStoreApi::OnDeleteOrderResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteOrderDelegate Delegate, int AutoRetryCount) const +void OpenAPIStoreApi::OnDeleteOrderResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteOrderDelegate Delegate) const { DeleteOrderResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnDeleteOrderResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIStoreApi::GetInventory(const GetInventoryRequest& Request, const FGetInventoryDelegate& Delegate /*= FGetInventoryDelegate()*/) const @@ -140,7 +163,7 @@ bool OpenAPIStoreApi::GetInventory(const GetInventoryRequest& Request, const FGe if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -150,26 +173,15 @@ bool OpenAPIStoreApi::GetInventory(const GetInventoryRequest& Request, const FGe Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnGetInventoryResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnGetInventoryResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIStoreApi::OnGetInventoryResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetInventoryDelegate Delegate, int AutoRetryCount) const +void OpenAPIStoreApi::OnGetInventoryResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetInventoryDelegate Delegate) const { GetInventoryResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnGetInventoryResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIStoreApi::GetOrderById(const GetOrderByIdRequest& Request, const FGetOrderByIdDelegate& Delegate /*= FGetOrderByIdDelegate()*/) const @@ -177,7 +189,7 @@ bool OpenAPIStoreApi::GetOrderById(const GetOrderByIdRequest& Request, const FGe if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -187,26 +199,15 @@ bool OpenAPIStoreApi::GetOrderById(const GetOrderByIdRequest& Request, const FGe Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnGetOrderByIdResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnGetOrderByIdResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIStoreApi::OnGetOrderByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetOrderByIdDelegate Delegate, int AutoRetryCount) const +void OpenAPIStoreApi::OnGetOrderByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetOrderByIdDelegate Delegate) const { GetOrderByIdResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnGetOrderByIdResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIStoreApi::PlaceOrder(const PlaceOrderRequest& Request, const FPlaceOrderDelegate& Delegate /*= FPlaceOrderDelegate()*/) const @@ -214,7 +215,7 @@ bool OpenAPIStoreApi::PlaceOrder(const PlaceOrderRequest& Request, const FPlaceO if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -224,26 +225,15 @@ bool OpenAPIStoreApi::PlaceOrder(const PlaceOrderRequest& Request, const FPlaceO Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnPlaceOrderResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnPlaceOrderResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIStoreApi::OnPlaceOrderResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FPlaceOrderDelegate Delegate, int AutoRetryCount) const +void OpenAPIStoreApi::OnPlaceOrderResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FPlaceOrderDelegate Delegate) const { PlaceOrderResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIStoreApi::OnPlaceOrderResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } } diff --git a/samples/client/petstore/cpp-ue4/Private/OpenAPIUserApi.cpp b/samples/client/petstore/cpp-ue4/Private/OpenAPIUserApi.cpp index 9fdd937b3b9e..8f38a6358f46 100644 --- a/samples/client/petstore/cpp-ue4/Private/OpenAPIUserApi.cpp +++ b/samples/client/petstore/cpp-ue4/Private/OpenAPIUserApi.cpp @@ -54,6 +54,40 @@ bool OpenAPIUserApi::IsValid() const return true; } +void OpenAPIUserApi::SetHttpRetryManager(FHttpRetrySystem::FManager& InRetryManager) +{ + if(RetryManager != &GetHttpRetryManager()) + { + DefaultRetryManager.Reset(); + RetryManager = &InRetryManager; + } +} + +FHttpRetrySystem::FManager& OpenAPIUserApi::GetHttpRetryManager() +{ + return *RetryManager; +} + +FHttpRequestRef OpenAPIUserApi::CreateHttpRequest(const Request& Request) const +{ + if (!Request.GetRetryParams().IsSet()) + { + return FHttpModule::Get().CreateRequest(); + } + else + { + if (!RetryManager) + { + // Create default retry manager if none was specified + DefaultRetryManager = MakeUnique(6, 60); + RetryManager = DefaultRetryManager.Get(); + } + + const HttpRetryParams& Params = Request.GetRetryParams().GetValue(); + return RetryManager->CreateRequest(Params.RetryLimitCountOverride, Params.RetryTimeoutRelativeSecondsOverride, Params.RetryResponseCodes, Params.RetryVerbs, Params.RetryDomains); + } +} + void OpenAPIUserApi::HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const { InOutResponse.SetHttpResponse(HttpResponse); @@ -103,7 +137,7 @@ bool OpenAPIUserApi::CreateUser(const CreateUserRequest& Request, const FCreateU if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -113,26 +147,15 @@ bool OpenAPIUserApi::CreateUser(const CreateUserRequest& Request, const FCreateU Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUserResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUserResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIUserApi::OnCreateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUserDelegate Delegate, int AutoRetryCount) const +void OpenAPIUserApi::OnCreateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUserDelegate Delegate) const { CreateUserResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUserResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIUserApi::CreateUsersWithArrayInput(const CreateUsersWithArrayInputRequest& Request, const FCreateUsersWithArrayInputDelegate& Delegate /*= FCreateUsersWithArrayInputDelegate()*/) const @@ -140,7 +163,7 @@ bool OpenAPIUserApi::CreateUsersWithArrayInput(const CreateUsersWithArrayInputRe if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -150,26 +173,15 @@ bool OpenAPIUserApi::CreateUsersWithArrayInput(const CreateUsersWithArrayInputRe Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUsersWithArrayInputResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUsersWithArrayInputResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIUserApi::OnCreateUsersWithArrayInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithArrayInputDelegate Delegate, int AutoRetryCount) const +void OpenAPIUserApi::OnCreateUsersWithArrayInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithArrayInputDelegate Delegate) const { CreateUsersWithArrayInputResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUsersWithArrayInputResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIUserApi::CreateUsersWithListInput(const CreateUsersWithListInputRequest& Request, const FCreateUsersWithListInputDelegate& Delegate /*= FCreateUsersWithListInputDelegate()*/) const @@ -177,7 +189,7 @@ bool OpenAPIUserApi::CreateUsersWithListInput(const CreateUsersWithListInputRequ if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -187,26 +199,15 @@ bool OpenAPIUserApi::CreateUsersWithListInput(const CreateUsersWithListInputRequ Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUsersWithListInputResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUsersWithListInputResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIUserApi::OnCreateUsersWithListInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithListInputDelegate Delegate, int AutoRetryCount) const +void OpenAPIUserApi::OnCreateUsersWithListInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithListInputDelegate Delegate) const { CreateUsersWithListInputResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnCreateUsersWithListInputResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIUserApi::DeleteUser(const DeleteUserRequest& Request, const FDeleteUserDelegate& Delegate /*= FDeleteUserDelegate()*/) const @@ -214,7 +215,7 @@ bool OpenAPIUserApi::DeleteUser(const DeleteUserRequest& Request, const FDeleteU if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -224,26 +225,15 @@ bool OpenAPIUserApi::DeleteUser(const DeleteUserRequest& Request, const FDeleteU Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnDeleteUserResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnDeleteUserResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIUserApi::OnDeleteUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteUserDelegate Delegate, int AutoRetryCount) const +void OpenAPIUserApi::OnDeleteUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteUserDelegate Delegate) const { DeleteUserResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnDeleteUserResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIUserApi::GetUserByName(const GetUserByNameRequest& Request, const FGetUserByNameDelegate& Delegate /*= FGetUserByNameDelegate()*/) const @@ -251,7 +241,7 @@ bool OpenAPIUserApi::GetUserByName(const GetUserByNameRequest& Request, const FG if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -261,26 +251,15 @@ bool OpenAPIUserApi::GetUserByName(const GetUserByNameRequest& Request, const FG Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnGetUserByNameResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnGetUserByNameResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIUserApi::OnGetUserByNameResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserByNameDelegate Delegate, int AutoRetryCount) const +void OpenAPIUserApi::OnGetUserByNameResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserByNameDelegate Delegate) const { GetUserByNameResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnGetUserByNameResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIUserApi::LoginUser(const LoginUserRequest& Request, const FLoginUserDelegate& Delegate /*= FLoginUserDelegate()*/) const @@ -288,7 +267,7 @@ bool OpenAPIUserApi::LoginUser(const LoginUserRequest& Request, const FLoginUser if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -298,26 +277,15 @@ bool OpenAPIUserApi::LoginUser(const LoginUserRequest& Request, const FLoginUser Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnLoginUserResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnLoginUserResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIUserApi::OnLoginUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginUserDelegate Delegate, int AutoRetryCount) const +void OpenAPIUserApi::OnLoginUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginUserDelegate Delegate) const { LoginUserResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnLoginUserResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIUserApi::LogoutUser(const LogoutUserRequest& Request, const FLogoutUserDelegate& Delegate /*= FLogoutUserDelegate()*/) const @@ -325,7 +293,7 @@ bool OpenAPIUserApi::LogoutUser(const LogoutUserRequest& Request, const FLogoutU if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -335,26 +303,15 @@ bool OpenAPIUserApi::LogoutUser(const LogoutUserRequest& Request, const FLogoutU Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnLogoutUserResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnLogoutUserResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIUserApi::OnLogoutUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLogoutUserDelegate Delegate, int AutoRetryCount) const +void OpenAPIUserApi::OnLogoutUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLogoutUserDelegate Delegate) const { LogoutUserResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnLogoutUserResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } bool OpenAPIUserApi::UpdateUser(const UpdateUserRequest& Request, const FUpdateUserDelegate& Delegate /*= FUpdateUserDelegate()*/) const @@ -362,7 +319,7 @@ bool OpenAPIUserApi::UpdateUser(const UpdateUserRequest& Request, const FUpdateU if (!IsValid()) return false; - FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest(); + FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) @@ -372,26 +329,15 @@ bool OpenAPIUserApi::UpdateUser(const UpdateUserRequest& Request, const FUpdateU Request.SetupHttpRequest(HttpRequest); - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnUpdateUserResponse, Delegate, Request.GetAutoRetryCount()); + HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnUpdateUserResponse, Delegate); return HttpRequest->ProcessRequest(); } -void OpenAPIUserApi::OnUpdateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateUserDelegate Delegate, int AutoRetryCount) const +void OpenAPIUserApi::OnUpdateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateUserDelegate Delegate) const { UpdateUserResponse Response; - Response.SetHttpRequest(HttpRequest); - HandleResponse(HttpResponse, bSucceeded, Response); - - if(!Response.IsSuccessful() && AutoRetryCount > 0) - { - HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPIUserApi::OnUpdateUserResponse, Delegate, AutoRetryCount - 1); - Response.AsyncRetry(); - } - else - { - Delegate.ExecuteIfBound(Response); - } + Delegate.ExecuteIfBound(Response); } } diff --git a/samples/client/petstore/cpp-ue4/Public/OpenAPIBaseModel.h b/samples/client/petstore/cpp-ue4/Public/OpenAPIBaseModel.h index d73441e1326c..538589752458 100644 --- a/samples/client/petstore/cpp-ue4/Public/OpenAPIBaseModel.h +++ b/samples/client/petstore/cpp-ue4/Public/OpenAPIBaseModel.h @@ -16,11 +16,38 @@ #include "Interfaces/IHttpResponse.h" #include "Serialization/JsonWriter.h" #include "Dom/JsonObject.h" +#include "HttpRetrySystem.h" +#include "Containers/Ticker.h" namespace OpenAPI { typedef TSharedRef> JsonWriter; +using namespace FHttpRetrySystem; + +struct OPENAPI_API HttpRetryManager : public FManager, public FTickerObjectBase +{ + using FManager::FManager; + + bool Tick(float DeltaTime) final; +}; + +struct OPENAPI_API HttpRetryParams +{ + HttpRetryParams( + const FRetryLimitCountSetting& InRetryLimitCountOverride = FRetryLimitCountSetting(), + const FRetryTimeoutRelativeSecondsSetting& InRetryTimeoutRelativeSecondsOverride = FRetryTimeoutRelativeSecondsSetting(), + const FRetryResponseCodes& InRetryResponseCodes = FRetryResponseCodes(), + const FRetryVerbs& InRetryVerbs = FRetryVerbs(), + const FRetryDomainsPtr& InRetryDomains = FRetryDomainsPtr() + ); + + FRetryLimitCountSetting RetryLimitCountOverride; + FRetryTimeoutRelativeSecondsSetting RetryTimeoutRelativeSecondsOverride; + FRetryResponseCodes RetryResponseCodes; + FRetryVerbs RetryVerbs; + FRetryDomainsPtr RetryDomains; +}; class OPENAPI_API Model { @@ -37,11 +64,12 @@ class OPENAPI_API Request virtual void SetupHttpRequest(const FHttpRequestRef& HttpRequest) const = 0; virtual FString ComputePath() const = 0; - void SetAutoRetryCount(int InCount) { AutoRetryCount = InCount; } - int GetAutoRetryCount() const { return AutoRetryCount; } + /* Enables retry and optionally sets a retry policy for this request */ + void SetShouldRetry(const HttpRetryParams& Params = HttpRetryParams()) { RetryParams = Params; } + const TOptional& GetRetryParams() const { return RetryParams; } private: - int AutoRetryCount = 0; + TOptional RetryParams; }; class OPENAPI_API Response @@ -53,8 +81,6 @@ class OPENAPI_API Response void SetSuccessful(bool InSuccessful) { Successful = InSuccessful; } bool IsSuccessful() const { return Successful; } - void AsyncRetry() const; - virtual void SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode); EHttpResponseCodes::Type GetHttpResponseCode() const { return ResponseCode; } @@ -64,15 +90,11 @@ class OPENAPI_API Response void SetHttpResponse(const FHttpResponsePtr& InHttpResponse) { HttpResponse = InHttpResponse; } const FHttpResponsePtr& GetHttpResponse() const { return HttpResponse; } - void SetHttpRequest(const FHttpRequestPtr& InHttpRequest) { HttpRequest = InHttpRequest; } - const FHttpRequestPtr& GetHttpRequest() const { return HttpRequest; } - private: bool Successful; EHttpResponseCodes::Type ResponseCode; FString ResponseString; FHttpResponsePtr HttpResponse; - FHttpRequestPtr HttpRequest; }; } diff --git a/samples/client/petstore/cpp-ue4/Public/OpenAPIHelpers.h b/samples/client/petstore/cpp-ue4/Public/OpenAPIHelpers.h index e4f58b19c66e..cd804d34245f 100644 --- a/samples/client/petstore/cpp-ue4/Public/OpenAPIHelpers.h +++ b/samples/client/petstore/cpp-ue4/Public/OpenAPIHelpers.h @@ -114,6 +114,11 @@ inline FStringFormatArg ToStringFormatArg(const FDateTime& Value) return FStringFormatArg(Value.ToIso8601()); } +inline FStringFormatArg ToStringFormatArg(const FGuid& Value) +{ + return FStringFormatArg(Value.ToString(EGuidFormats::DigitsWithHyphens)); +} + inline FStringFormatArg ToStringFormatArg(const TArray& Value) { return FStringFormatArg(Base64UrlEncode(Value)); @@ -229,6 +234,11 @@ inline void WriteJsonValue(JsonWriter& Writer, const FDateTime& Value) Writer->WriteValue(Value.ToIso8601()); } +inline void WriteJsonValue(JsonWriter& Writer, const FGuid& Value) +{ + Writer->WriteValue(Value.ToString(EGuidFormats::DigitsWithHyphens)); +} + inline void WriteJsonValue(JsonWriter& Writer, const Model& Value) { Value.WriteJson(Writer); @@ -290,6 +300,17 @@ inline bool TryGetJsonValue(const TSharedPtr& JsonValue, FDateTime& return false; } +inline bool TryGetJsonValue(const TSharedPtr& JsonValue, FGuid& Value) +{ + FString TmpValue; + if (JsonValue->TryGetString(TmpValue)) + { + return FGuid::Parse(TmpValue, Value); + } + else + return false; +} + inline bool TryGetJsonValue(const TSharedPtr& JsonValue, bool& Value) { bool TmpValue; diff --git a/samples/client/petstore/cpp-ue4/Public/OpenAPIPetApi.h b/samples/client/petstore/cpp-ue4/Public/OpenAPIPetApi.h index bde6403c4913..db422a0eccc6 100644 --- a/samples/client/petstore/cpp-ue4/Public/OpenAPIPetApi.h +++ b/samples/client/petstore/cpp-ue4/Public/OpenAPIPetApi.h @@ -24,9 +24,19 @@ class OPENAPI_API OpenAPIPetApi OpenAPIPetApi(); ~OpenAPIPetApi(); + /* Sets the URL Endpoint. + * Note: several fallback endpoints can be configured in request retry policies, see Request::SetShouldRetry */ void SetURL(const FString& Url); + + /* Adds global header params to all requests */ void AddHeaderParam(const FString& Key, const FString& Value); void ClearHeaderParams(); + + /* Sets the retry manager to the user-defined retry manager. User must manage the lifetime of the retry manager. + * If no retry manager is specified and a request needs retries, a default retry manager will be used. + * See also: Request::SetShouldRetry */ + void SetHttpRetryManager(FHttpRetrySystem::FManager& RetryManager); + FHttpRetrySystem::FManager& GetHttpRetryManager(); class AddPetRequest; class AddPetResponse; @@ -63,22 +73,24 @@ class OPENAPI_API OpenAPIPetApi bool UpdatePetWithForm(const UpdatePetWithFormRequest& Request, const FUpdatePetWithFormDelegate& Delegate = FUpdatePetWithFormDelegate()) const; bool UploadFile(const UploadFileRequest& Request, const FUploadFileDelegate& Delegate = FUploadFileDelegate()) const; - private: - void OnAddPetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAddPetDelegate Delegate, int AutoRetryCount) const; - void OnDeletePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeletePetDelegate Delegate, int AutoRetryCount) const; - void OnFindPetsByStatusResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByStatusDelegate Delegate, int AutoRetryCount) const; - void OnFindPetsByTagsResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByTagsDelegate Delegate, int AutoRetryCount) const; - void OnGetPetByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPetByIdDelegate Delegate, int AutoRetryCount) const; - void OnUpdatePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetDelegate Delegate, int AutoRetryCount) const; - void OnUpdatePetWithFormResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetWithFormDelegate Delegate, int AutoRetryCount) const; - void OnUploadFileResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUploadFileDelegate Delegate, int AutoRetryCount) const; + void OnAddPetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAddPetDelegate Delegate) const; + void OnDeletePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeletePetDelegate Delegate) const; + void OnFindPetsByStatusResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByStatusDelegate Delegate) const; + void OnFindPetsByTagsResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FFindPetsByTagsDelegate Delegate) const; + void OnGetPetByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPetByIdDelegate Delegate) const; + void OnUpdatePetResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetDelegate Delegate) const; + void OnUpdatePetWithFormResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePetWithFormDelegate Delegate) const; + void OnUploadFileResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUploadFileDelegate Delegate) const; + FHttpRequestRef CreateHttpRequest(const Request& Request) const; bool IsValid() const; void HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const; FString Url; TMap AdditionalHeaderParams; + mutable FHttpRetrySystem::FManager* RetryManager = nullptr; + mutable TUniquePtr DefaultRetryManager; }; } diff --git a/samples/client/petstore/cpp-ue4/Public/OpenAPIStoreApi.h b/samples/client/petstore/cpp-ue4/Public/OpenAPIStoreApi.h index 5f5377327328..934a1b277c74 100644 --- a/samples/client/petstore/cpp-ue4/Public/OpenAPIStoreApi.h +++ b/samples/client/petstore/cpp-ue4/Public/OpenAPIStoreApi.h @@ -24,9 +24,19 @@ class OPENAPI_API OpenAPIStoreApi OpenAPIStoreApi(); ~OpenAPIStoreApi(); + /* Sets the URL Endpoint. + * Note: several fallback endpoints can be configured in request retry policies, see Request::SetShouldRetry */ void SetURL(const FString& Url); + + /* Adds global header params to all requests */ void AddHeaderParam(const FString& Key, const FString& Value); void ClearHeaderParams(); + + /* Sets the retry manager to the user-defined retry manager. User must manage the lifetime of the retry manager. + * If no retry manager is specified and a request needs retries, a default retry manager will be used. + * See also: Request::SetShouldRetry */ + void SetHttpRetryManager(FHttpRetrySystem::FManager& RetryManager); + FHttpRetrySystem::FManager& GetHttpRetryManager(); class DeleteOrderRequest; class DeleteOrderResponse; @@ -47,18 +57,20 @@ class OPENAPI_API OpenAPIStoreApi bool GetOrderById(const GetOrderByIdRequest& Request, const FGetOrderByIdDelegate& Delegate = FGetOrderByIdDelegate()) const; bool PlaceOrder(const PlaceOrderRequest& Request, const FPlaceOrderDelegate& Delegate = FPlaceOrderDelegate()) const; - private: - void OnDeleteOrderResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteOrderDelegate Delegate, int AutoRetryCount) const; - void OnGetInventoryResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetInventoryDelegate Delegate, int AutoRetryCount) const; - void OnGetOrderByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetOrderByIdDelegate Delegate, int AutoRetryCount) const; - void OnPlaceOrderResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FPlaceOrderDelegate Delegate, int AutoRetryCount) const; + void OnDeleteOrderResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteOrderDelegate Delegate) const; + void OnGetInventoryResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetInventoryDelegate Delegate) const; + void OnGetOrderByIdResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetOrderByIdDelegate Delegate) const; + void OnPlaceOrderResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FPlaceOrderDelegate Delegate) const; + FHttpRequestRef CreateHttpRequest(const Request& Request) const; bool IsValid() const; void HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const; FString Url; TMap AdditionalHeaderParams; + mutable FHttpRetrySystem::FManager* RetryManager = nullptr; + mutable TUniquePtr DefaultRetryManager; }; } diff --git a/samples/client/petstore/cpp-ue4/Public/OpenAPIUserApi.h b/samples/client/petstore/cpp-ue4/Public/OpenAPIUserApi.h index e60ce6754039..809c4950125b 100644 --- a/samples/client/petstore/cpp-ue4/Public/OpenAPIUserApi.h +++ b/samples/client/petstore/cpp-ue4/Public/OpenAPIUserApi.h @@ -24,9 +24,19 @@ class OPENAPI_API OpenAPIUserApi OpenAPIUserApi(); ~OpenAPIUserApi(); + /* Sets the URL Endpoint. + * Note: several fallback endpoints can be configured in request retry policies, see Request::SetShouldRetry */ void SetURL(const FString& Url); + + /* Adds global header params to all requests */ void AddHeaderParam(const FString& Key, const FString& Value); void ClearHeaderParams(); + + /* Sets the retry manager to the user-defined retry manager. User must manage the lifetime of the retry manager. + * If no retry manager is specified and a request needs retries, a default retry manager will be used. + * See also: Request::SetShouldRetry */ + void SetHttpRetryManager(FHttpRetrySystem::FManager& RetryManager); + FHttpRetrySystem::FManager& GetHttpRetryManager(); class CreateUserRequest; class CreateUserResponse; @@ -63,22 +73,24 @@ class OPENAPI_API OpenAPIUserApi bool LogoutUser(const LogoutUserRequest& Request, const FLogoutUserDelegate& Delegate = FLogoutUserDelegate()) const; bool UpdateUser(const UpdateUserRequest& Request, const FUpdateUserDelegate& Delegate = FUpdateUserDelegate()) const; - private: - void OnCreateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUserDelegate Delegate, int AutoRetryCount) const; - void OnCreateUsersWithArrayInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithArrayInputDelegate Delegate, int AutoRetryCount) const; - void OnCreateUsersWithListInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithListInputDelegate Delegate, int AutoRetryCount) const; - void OnDeleteUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteUserDelegate Delegate, int AutoRetryCount) const; - void OnGetUserByNameResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserByNameDelegate Delegate, int AutoRetryCount) const; - void OnLoginUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginUserDelegate Delegate, int AutoRetryCount) const; - void OnLogoutUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLogoutUserDelegate Delegate, int AutoRetryCount) const; - void OnUpdateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateUserDelegate Delegate, int AutoRetryCount) const; + void OnCreateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUserDelegate Delegate) const; + void OnCreateUsersWithArrayInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithArrayInputDelegate Delegate) const; + void OnCreateUsersWithListInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithListInputDelegate Delegate) const; + void OnDeleteUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteUserDelegate Delegate) const; + void OnGetUserByNameResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserByNameDelegate Delegate) const; + void OnLoginUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginUserDelegate Delegate) const; + void OnLogoutUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLogoutUserDelegate Delegate) const; + void OnUpdateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateUserDelegate Delegate) const; + FHttpRequestRef CreateHttpRequest(const Request& Request) const; bool IsValid() const; void HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const; FString Url; TMap AdditionalHeaderParams; + mutable FHttpRetrySystem::FManager* RetryManager = nullptr; + mutable TUniquePtr DefaultRetryManager; }; } diff --git a/samples/client/petstore/crystal/.openapi-generator/VERSION b/samples/client/petstore/crystal/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/crystal/.openapi-generator/VERSION +++ b/samples/client/petstore/crystal/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/crystal/.travis.yml b/samples/client/petstore/crystal/.travis.yml index a8fa5ad86ea1..b40e33fb20e5 100644 --- a/samples/client/petstore/crystal/.travis.yml +++ b/samples/client/petstore/crystal/.travis.yml @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 5.1.1-SNAPSHOT +#OpenAPI Generator version: 5.2.0-SNAPSHOT # language: crystal diff --git a/samples/client/petstore/crystal/bin/ameba b/samples/client/petstore/crystal/bin/ameba index 332b8c750a45..c88ac4a8d026 100755 Binary files a/samples/client/petstore/crystal/bin/ameba and b/samples/client/petstore/crystal/bin/ameba differ diff --git a/samples/client/petstore/crystal/pom.xml b/samples/client/petstore/crystal/pom.xml index f4b890f7d802..29b7e4bc3516 100644 --- a/samples/client/petstore/crystal/pom.xml +++ b/samples/client/petstore/crystal/pom.xml @@ -34,6 +34,10 @@ shards + + install + --ignore-crystal-version + diff --git a/samples/client/petstore/crystal/shard.lock b/samples/client/petstore/crystal/shard.lock index 97567adcb9e5..6a33ec4f671f 100644 --- a/samples/client/petstore/crystal/shard.lock +++ b/samples/client/petstore/crystal/shard.lock @@ -2,23 +2,23 @@ version: 2.0 shards: ameba: git: https://github.com/crystal-ameba/ameba.git - version: 0.13.3 + version: 0.14.3 crest: git: https://github.com/mamantoha/crest.git - version: 0.26.1 + version: 0.26.8 exception_page: git: https://github.com/crystal-loot/exception_page.git - version: 0.1.4 + version: 0.1.5 http-client-digest_auth: git: https://github.com/mamantoha/http-client-digest_auth.git - version: 0.4.0 + version: 0.6.0 http_proxy: git: https://github.com/mamantoha/http_proxy.git - version: 0.7.2 + version: 0.8.0 kemal: git: https://github.com/kemalcr/kemal.git @@ -26,7 +26,7 @@ shards: kilt: git: https://github.com/jeromegn/kilt.git - version: 0.4.0 + version: 0.4.1 radix: git: https://github.com/luislavena/radix.git diff --git a/samples/client/petstore/crystal/shard.yml b/samples/client/petstore/crystal/shard.yml index 06fc3300e053..a4c86a06e2a2 100644 --- a/samples/client/petstore/crystal/shard.yml +++ b/samples/client/petstore/crystal/shard.yml @@ -1,4 +1,4 @@ -name: Petstore +name: petstore version: 1.0.0 authors: - diff --git a/samples/client/petstore/crystal/spec/api/pet_api_spec.cr b/samples/client/petstore/crystal/spec/api/pet_api_spec.cr index 23bdfa818477..5c5f56295acc 100644 --- a/samples/client/petstore/crystal/spec/api/pet_api_spec.cr +++ b/samples/client/petstore/crystal/spec/api/pet_api_spec.cr @@ -79,7 +79,16 @@ describe "PetApi" do describe "get_pet_by_id test" do it "should work" do # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html - api_instance = Petstore::PetApi.new + + config = Petstore::Configuration.new + config.access_token = "yyy" + config.api_key[:api_key] = "xxx" + config.api_key_prefix[:api_key] = "Token" + + api_client = Petstore::ApiClient.new(config) + + api_instance = Petstore::PetApi.new(api_client) + # create a pet to start with pet_id = Int64.new(91829) pet = Petstore::Pet.new(id: pet_id, category: Petstore::Category.new(id: pet_id + 10, name: "crystal category"), name: "crystal", photo_urls: ["https://crystal-lang.org"], tags: [Petstore::Tag.new(id: pet_id + 100, name: "crystal tag")], status: "available") diff --git a/samples/client/petstore/crystal/spec/api_client_spec.cr b/samples/client/petstore/crystal/spec/api_client_spec.cr new file mode 100644 index 000000000000..18209417eabf --- /dev/null +++ b/samples/client/petstore/crystal/spec/api_client_spec.cr @@ -0,0 +1,56 @@ +require "./spec_helper" + +describe Petstore::ApiClient do + describe "#update_params_for_auth!" do + describe "oauth2" do + it "should add 'Authorization' to header" do + config = Petstore::Configuration.new + config.access_token = "xxx" + + header_params = {} of String => String + query_params = {} of String => String + + api_client = Petstore::ApiClient.new(config) + api_client.update_params_for_auth!(header_params, query_params, ["petstore_auth"]) + + header_params["Authorization"].should eq "Bearer xxx" + query_params.size.should eq 0 + end + end + + describe "api_key" do + context "without api_key_prefix" do + it "should add 'api_key' to header" do + config = Petstore::Configuration.new + config.api_key[:api_key] = "xxx" + + header_params = {} of String => String + query_params = {} of String => String + + api_client = Petstore::ApiClient.new(config) + api_client.update_params_for_auth!(header_params, query_params, ["api_key"]) + + header_params["api_key"].should eq "xxx" + query_params.empty?.should be_true + end + end + + context "with api_key_prefix" do + it "should add 'api_key' to header" do + config = Petstore::Configuration.new + config.api_key[:api_key] = "xxx" + config.api_key_prefix[:api_key] = "Token" + + header_params = {} of String => String + query_params = {} of String => String + + api_client = Petstore::ApiClient.new(config) + api_client.update_params_for_auth!(header_params, query_params, ["api_key"]) + + header_params["api_key"].should eq "Token xxx" + query_params.empty?.should be_true + end + end + end + end +end diff --git a/samples/client/petstore/crystal/spec/configuration_spec.cr b/samples/client/petstore/crystal/spec/configuration_spec.cr new file mode 100644 index 000000000000..a99e77166dde --- /dev/null +++ b/samples/client/petstore/crystal/spec/configuration_spec.cr @@ -0,0 +1,26 @@ +require "./spec_helper" + +describe Petstore::Configuration do + describe "#initialize" do + context "with block" do + it "works" do + config = Petstore::Configuration.new do |config| + config.username = "xxx" + end + + config.username.should eq "xxx" + end + end + end + + describe "#configure" do + it "works" do + config = Petstore::Configuration.new + config.configure do |config| + config.username = "xxx" + end + + config.username.should eq "xxx" + end + end +end diff --git a/samples/client/petstore/crystal/spec/petstore_spec.cr b/samples/client/petstore/crystal/spec/petstore_spec.cr new file mode 100644 index 000000000000..cca7698a536d --- /dev/null +++ b/samples/client/petstore/crystal/spec/petstore_spec.cr @@ -0,0 +1,19 @@ +require "./spec_helper" + +describe Petstore do + describe "#configure" do + it "works" do + Petstore.configure do |config| + config.username = "xxx" + end + + config = Petstore.configure + + config.should eq Petstore::Configuration.default + config.username.should eq "xxx" + + # Clean up + Petstore::Configuration.default.username = nil + end + end +end diff --git a/samples/client/petstore/crystal/spec/spec_helper.cr b/samples/client/petstore/crystal/spec/spec_helper.cr index 5a27efa1a2fa..6532505ff2b2 100644 --- a/samples/client/petstore/crystal/spec/spec_helper.cr +++ b/samples/client/petstore/crystal/spec/spec_helper.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 5.1.1-SNAPSHOT +#OpenAPI Generator version: 5.2.0-SNAPSHOT # # load modules diff --git a/samples/client/petstore/crystal/src/petstore.cr b/samples/client/petstore/crystal/src/petstore.cr index 13d16661a6bd..fadebdc48488 100644 --- a/samples/client/petstore/crystal/src/petstore.cr +++ b/samples/client/petstore/crystal/src/petstore.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 5.1.1-SNAPSHOT +#OpenAPI Generator version: 5.2.0-SNAPSHOT # # Dependencies @@ -17,18 +17,21 @@ module Petstore VERSION = {{ `shards version #{__DIR__}`.chomp.stringify }} + # Return the default `Configuration` object. + def self.configure + Configuration.default + end + # Customize default settings for the SDK using block. - # Petstore.configure do |config| - # config.username = "xxx" - # config.password = "xxx" - # end - # If no block given, return the default Configuration object. - def configure - if block_given? - yield(Configuration.default) - else - Configuration.default - end + # + # ``` + # Petstore.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # ``` + def self.configure + yield Configuration.default end end diff --git a/samples/client/petstore/crystal/src/petstore/api/pet_api.cr b/samples/client/petstore/crystal/src/petstore/api/pet_api.cr index efcf4a26ff09..41466efaf1b7 100644 --- a/samples/client/petstore/crystal/src/petstore/api/pet_api.cr +++ b/samples/client/petstore/crystal/src/petstore/api/pet_api.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 5.1.1-SNAPSHOT +#OpenAPI Generator version: 5.2.0-SNAPSHOT # require "uri" @@ -40,7 +40,7 @@ module Petstore local_var_path = "/pet" # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -99,7 +99,7 @@ module Petstore local_var_path = "/pet/{petId}".sub("{" + "petId" + "}", URI.encode(pet_id.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -157,8 +157,8 @@ module Petstore local_var_path = "/pet/findByStatus" # query parameters - query_params = Hash(Symbol, String).new - query_params[:"status"] = @api_client.build_collection_param(status, :csv) + query_params = Hash(String, String).new + query_params["status"] = @api_client.build_collection_param(status, :csv) # header parameters header_params = Hash(String, String).new @@ -217,8 +217,8 @@ module Petstore local_var_path = "/pet/findByTags" # query parameters - query_params = Hash(Symbol, String).new - query_params[:"tags"] = @api_client.build_collection_param(tags, :csv) + query_params = Hash(String, String).new + query_params["tags"] = @api_client.build_collection_param(tags, :csv) # header parameters header_params = Hash(String, String).new @@ -277,7 +277,7 @@ module Petstore local_var_path = "/pet/{petId}".sub("{" + "petId" + "}", URI.encode(pet_id.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -334,7 +334,7 @@ module Petstore local_var_path = "/pet" # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -393,7 +393,7 @@ module Petstore local_var_path = "/pet/{petId}".sub("{" + "petId" + "}", URI.encode(pet_id.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -452,7 +452,7 @@ module Petstore local_var_path = "/pet/{petId}/uploadImage".sub("{" + "petId" + "}", URI.encode(pet_id.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new diff --git a/samples/client/petstore/crystal/src/petstore/api/store_api.cr b/samples/client/petstore/crystal/src/petstore/api/store_api.cr index 226a3a779517..03f45309463c 100644 --- a/samples/client/petstore/crystal/src/petstore/api/store_api.cr +++ b/samples/client/petstore/crystal/src/petstore/api/store_api.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 5.1.1-SNAPSHOT +#OpenAPI Generator version: 5.2.0-SNAPSHOT # require "uri" @@ -42,7 +42,7 @@ module Petstore local_var_path = "/store/order/{orderId}".sub("{" + "orderId" + "}", URI.encode(order_id.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -93,7 +93,7 @@ module Petstore local_var_path = "/store/inventory" # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -160,7 +160,7 @@ module Petstore local_var_path = "/store/order/{orderId}".sub("{" + "orderId" + "}", URI.encode(order_id.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -217,7 +217,7 @@ module Petstore local_var_path = "/store/order" # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new diff --git a/samples/client/petstore/crystal/src/petstore/api/user_api.cr b/samples/client/petstore/crystal/src/petstore/api/user_api.cr index 6601e7d57ea7..0b2468c50d36 100644 --- a/samples/client/petstore/crystal/src/petstore/api/user_api.cr +++ b/samples/client/petstore/crystal/src/petstore/api/user_api.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 5.1.1-SNAPSHOT +#OpenAPI Generator version: 5.2.0-SNAPSHOT # require "uri" @@ -42,7 +42,7 @@ module Petstore local_var_path = "/user" # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -99,7 +99,7 @@ module Petstore local_var_path = "/user/createWithArray" # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -156,7 +156,7 @@ module Petstore local_var_path = "/user/createWithList" # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -215,7 +215,7 @@ module Petstore local_var_path = "/user/{username}".sub("{" + "username" + "}", URI.encode(username.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -270,7 +270,7 @@ module Petstore local_var_path = "/user/{username}".sub("{" + "username" + "}", URI.encode(username.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -338,9 +338,9 @@ module Petstore local_var_path = "/user/login" # query parameters - query_params = Hash(Symbol, String).new - query_params[:"username"] = username - query_params[:"password"] = password + query_params = Hash(String, String).new + query_params["username"] = username + query_params["password"] = password # header parameters header_params = Hash(String, String).new @@ -391,7 +391,7 @@ module Petstore local_var_path = "/user/logout" # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -454,7 +454,7 @@ module Petstore local_var_path = "/user/{username}".sub("{" + "username" + "}", URI.encode(username.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new diff --git a/samples/client/petstore/crystal/src/petstore/api_client.cr b/samples/client/petstore/crystal/src/petstore/api_client.cr index 579bc3f3b968..a0f4a469c48b 100644 --- a/samples/client/petstore/crystal/src/petstore/api_client.cr +++ b/samples/client/petstore/crystal/src/petstore/api_client.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 5.1.1-SNAPSHOT +#OpenAPI Generator version: 5.2.0-SNAPSHOT # require "json" @@ -171,7 +171,7 @@ module Petstore # @param [Hash] query_params Query parameters # @param [String] auth_names Authentication scheme name def update_params_for_auth!(header_params, query_params, auth_names) - Array{auth_names}.each do |auth_name| + auth_names.each do |auth_name| auth_setting = @config.auth_settings[auth_name] next unless auth_setting case auth_setting[:in] @@ -264,7 +264,7 @@ module Petstore # # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: # the data deserialized from response body (could be nil), response status code and response headers. - def call_api(http_method : Symbol, path : String, operation : Symbol, return_type : String, post_body : String?, auth_names = [] of String, header_params = {} of String => String, query_params = {} of Symbol => String, form_params = {} of Symbol => String) + def call_api(http_method : Symbol, path : String, operation : Symbol, return_type : String, post_body : String?, auth_names = [] of String, header_params = {} of String => String, query_params = {} of String => String, form_params = {} of Symbol => String) #ssl_options = { # :ca_file => @config.ssl_ca_file, # :verify => @config.ssl_verify, @@ -282,6 +282,8 @@ module Petstore # conn.adapter(Faraday.default_adapter) #end + update_params_for_auth! header_params, query_params, auth_names + if !post_body.nil? && !post_body.empty? # use JSON string in the payload form_or_body = post_body diff --git a/samples/client/petstore/crystal/src/petstore/api_error.cr b/samples/client/petstore/crystal/src/petstore/api_error.cr index 9e7c178a48ff..ef28c709d56a 100644 --- a/samples/client/petstore/crystal/src/petstore/api_error.cr +++ b/samples/client/petstore/crystal/src/petstore/api_error.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 5.1.1-SNAPSHOT +#OpenAPI Generator version: 5.2.0-SNAPSHOT # module Petstore diff --git a/samples/client/petstore/crystal/src/petstore/configuration.cr b/samples/client/petstore/crystal/src/petstore/configuration.cr index 0b97ee465e34..18ef2969ac36 100644 --- a/samples/client/petstore/crystal/src/petstore/configuration.cr +++ b/samples/client/petstore/crystal/src/petstore/configuration.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 5.1.1-SNAPSHOT +#OpenAPI Generator version: 5.2.0-SNAPSHOT # require "log" @@ -38,7 +38,7 @@ module Petstore # @return [Hash] key: parameter name, value: parameter value (API key) # # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) - # config.api_key[:"api_key"] = "xxx" + # config.api_key[:api_key] = "xxx" property api_key : Hash(Symbol, String) # Defines API key prefixes used with API Key authentications. @@ -46,7 +46,7 @@ module Petstore # @return [Hash] key: parameter name, value: API key prefix # # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) - # config.api_key_prefix[:"api_key"] = "Token" + # config.api_key_prefix[:api_key] = "Token" property api_key_prefix : Hash(Symbol, String) # Defines the username used with HTTP basic authentication. @@ -127,6 +127,7 @@ module Petstore # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 #property params_encoding : String? + # Create a new `Configuration`. def initialize @scheme = "http" @host = "petstore.swagger.io" @@ -149,9 +150,19 @@ module Petstore @password = nil @access_token = nil @temp_folder_path = nil + end - # TODO revise below to support block - #yield(self) if block_given? + # Create a new `Configuration` with block. + # + # ``` + # config = Petstore::Configuration.new do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # ``` + def initialize + initialize + yield self end # The default Configuration object. @@ -159,8 +170,9 @@ module Petstore @@default ||= Configuration.new end + # Configure object with block. def configure - yield(self) if block_given? + yield self end def scheme=(scheme) @@ -191,10 +203,10 @@ module Petstore # Gets API key (with prefix if set). # @param [String] param_name the parameter name of API key auth def api_key_with_prefix(param_name) - if @api_key_prefix[param_name] - "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + if prefix = @api_key_prefix[param_name]? + "#{prefix} #{@api_key[param_name]}" else - @api_key[param_name] + @api_key[param_name]? || "" end end @@ -205,19 +217,19 @@ module Petstore # Returns Auth Settings hash for api client. def auth_settings - Hash{ "api_key" => { - type: "api_key", - in: "header", - key: "api_key", - value: api_key_with_prefix("api_key") - }, - "petstore_auth" => - { - type: "oauth2", - in: "header", - key: "Authorization", - value: "Bearer #{access_token}" - }, + Hash{ + "api_key" => { + type: "api_key", + in: "header", + key: "api_key", + value: api_key_with_prefix(:api_key) + }, + "petstore_auth" => { + type: "oauth2", + in: "header", + key: "Authorization", + value: "Bearer #{access_token}" + }, } end diff --git a/samples/client/petstore/crystal/src/petstore/models/api_response.cr b/samples/client/petstore/crystal/src/petstore/models/api_response.cr index 57d64a5c8fb8..7d15b7200f85 100644 --- a/samples/client/petstore/crystal/src/petstore/models/api_response.cr +++ b/samples/client/petstore/crystal/src/petstore/models/api_response.cr @@ -5,23 +5,23 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 5.1.1-SNAPSHOT +#OpenAPI Generator version: 5.2.0-SNAPSHOT # +require "json" require "time" module Petstore # Describes the result of uploading an image resource - class ApiResponse include JSON::Serializable - include JSON::Serializable + class ApiResponse + include JSON::Serializable + @[JSON::Field(key: code, type: Int32)] property code : Int32 - @[JSON::Field(key: type, type: String)] property _type : String - @[JSON::Field(key: message, type: String)] property message : String diff --git a/samples/client/petstore/crystal/src/petstore/models/category.cr b/samples/client/petstore/crystal/src/petstore/models/category.cr index 5d05264ea490..7d573eb7a82e 100644 --- a/samples/client/petstore/crystal/src/petstore/models/category.cr +++ b/samples/client/petstore/crystal/src/petstore/models/category.cr @@ -5,19 +5,20 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 5.1.1-SNAPSHOT +#OpenAPI Generator version: 5.2.0-SNAPSHOT # +require "json" require "time" module Petstore # A category for a pet - class Category include JSON::Serializable - include JSON::Serializable + class Category + include JSON::Serializable + @[JSON::Field(key: id, type: Int64)] property id : Int64 - @[JSON::Field(key: name, type: String)] property name : String diff --git a/samples/client/petstore/crystal/src/petstore/models/order.cr b/samples/client/petstore/crystal/src/petstore/models/order.cr index 4941aa0126cc..05de437e07c4 100644 --- a/samples/client/petstore/crystal/src/petstore/models/order.cr +++ b/samples/client/petstore/crystal/src/petstore/models/order.cr @@ -5,36 +5,33 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 5.1.1-SNAPSHOT +#OpenAPI Generator version: 5.2.0-SNAPSHOT # +require "json" require "time" module Petstore # An order for a pets from the pet store - class Order include JSON::Serializable - include JSON::Serializable + class Order + include JSON::Serializable + @[JSON::Field(key: id, type: Int64)] property id : Int64 - @[JSON::Field(key: petId, type: Int64)] property pet_id : Int64 - @[JSON::Field(key: quantity, type: Int32)] property quantity : Int32 - @[JSON::Field(key: shipDate, type: Time)] property ship_date : Time - # Order Status @[JSON::Field(key: status, type: String)] property status : String - @[JSON::Field(key: complete, type: Bool)] property complete : Bool diff --git a/samples/client/petstore/crystal/src/petstore/models/pet.cr b/samples/client/petstore/crystal/src/petstore/models/pet.cr index 7d63ff38d555..2d2c236e48bd 100644 --- a/samples/client/petstore/crystal/src/petstore/models/pet.cr +++ b/samples/client/petstore/crystal/src/petstore/models/pet.cr @@ -5,35 +5,32 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 5.1.1-SNAPSHOT +#OpenAPI Generator version: 5.2.0-SNAPSHOT # +require "json" require "time" module Petstore # A pet for sale in the pet store - class Pet include JSON::Serializable - include JSON::Serializable + class Pet + include JSON::Serializable + @[JSON::Field(key: id, type: Int64)] property id : Int64 - @[JSON::Field(key: category, type: Category)] property category : Category - @[JSON::Field(key: name, type: String)] property name : String - @[JSON::Field(key: photoUrls, type: Array(String))] property photo_urls : Array(String) - @[JSON::Field(key: tags, type: Array(Tag))] property tags : Array(Tag) - # pet status in the store @[JSON::Field(key: status, type: String)] property status : String diff --git a/samples/client/petstore/crystal/src/petstore/models/tag.cr b/samples/client/petstore/crystal/src/petstore/models/tag.cr index 85051f4ad6b7..6e6f16a21d38 100644 --- a/samples/client/petstore/crystal/src/petstore/models/tag.cr +++ b/samples/client/petstore/crystal/src/petstore/models/tag.cr @@ -5,19 +5,20 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 5.1.1-SNAPSHOT +#OpenAPI Generator version: 5.2.0-SNAPSHOT # +require "json" require "time" module Petstore # A tag for a pet - class Tag include JSON::Serializable - include JSON::Serializable + class Tag + include JSON::Serializable + @[JSON::Field(key: id, type: Int64)] property id : Int64 - @[JSON::Field(key: name, type: String)] property name : String diff --git a/samples/client/petstore/crystal/src/petstore/models/user.cr b/samples/client/petstore/crystal/src/petstore/models/user.cr index d3bce3feb3be..3732dc4d2e42 100644 --- a/samples/client/petstore/crystal/src/petstore/models/user.cr +++ b/samples/client/petstore/crystal/src/petstore/models/user.cr @@ -5,43 +5,38 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 5.1.1-SNAPSHOT +#OpenAPI Generator version: 5.2.0-SNAPSHOT # +require "json" require "time" module Petstore # A User who is purchasing from the pet store - class User include JSON::Serializable - include JSON::Serializable + class User + include JSON::Serializable + @[JSON::Field(key: id, type: Int64)] property id : Int64 - @[JSON::Field(key: username, type: String)] property username : String - @[JSON::Field(key: firstName, type: String)] property first_name : String - @[JSON::Field(key: lastName, type: String)] property last_name : String - @[JSON::Field(key: email, type: String)] property email : String - @[JSON::Field(key: password, type: String)] property password : String - @[JSON::Field(key: phone, type: String)] property phone : String - # User Status @[JSON::Field(key: userStatus, type: Int32)] property user_status : Int32 diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/.openapi-generator/FILES b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/.openapi-generator/FILES index e6b9861f3320..d317e6120516 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/.openapi-generator/FILES +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/.openapi-generator/FILES @@ -97,6 +97,7 @@ src/Org.OpenAPITools/Client/ApiResponse.cs src/Org.OpenAPITools/Client/ClientUtils.cs src/Org.OpenAPITools/Client/Configuration.cs src/Org.OpenAPITools/Client/ExceptionFactory.cs +src/Org.OpenAPITools/Client/FileParameter.cs src/Org.OpenAPITools/Client/GlobalConfiguration.cs src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs src/Org.OpenAPITools/Client/IApiAccessor.cs diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/README.md index e16da183ea85..48379909c58f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/README.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/README.md @@ -83,6 +83,7 @@ services.AddHttpClient(httpClient => ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -96,7 +97,10 @@ namespace Example Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new AnotherFakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new AnotherFakeApi(httpClient, config, httpClientHandler); var modelClient = new ModelClient(); // ModelClient | client model try diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/AnotherFakeApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/AnotherFakeApi.md index 93fca7e408ac..83cdaf2ae930 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/AnotherFakeApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/AnotherFakeApi.md @@ -19,6 +19,7 @@ To test special tags and operation ID starting with number ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -31,7 +32,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new AnotherFakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new AnotherFakeApi(httpClient, config, httpClientHandler); var modelClient = new ModelClient(); // ModelClient | client model try diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/DefaultApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/DefaultApi.md index 6f5de6b68511..ec7241832837 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/DefaultApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/DefaultApi.md @@ -17,6 +17,7 @@ Method | HTTP request | Description ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -29,7 +30,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new DefaultApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new DefaultApi(httpClient, config, httpClientHandler); try { diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeApi.md index af8d565abfb1..c5a0b767f3d2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeApi.md @@ -31,6 +31,7 @@ Health check endpoint ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -43,7 +44,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); try { @@ -98,6 +102,7 @@ Test serialization of outer boolean types ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -110,7 +115,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var body = true; // bool? | Input boolean as post body (optional) try @@ -168,6 +176,7 @@ Test serialization of object with outer number type ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -180,7 +189,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var outerComposite = new OuterComposite(); // OuterComposite | Input composite as post body (optional) try @@ -238,6 +250,7 @@ Test serialization of outer number types ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -250,7 +263,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var body = 8.14; // decimal? | Input number as post body (optional) try @@ -308,6 +324,7 @@ Test serialization of outer string types ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -320,7 +337,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var body = body_example; // string | Input string as post body (optional) try @@ -376,6 +396,7 @@ Array of Enums ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -388,7 +409,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); try { @@ -443,6 +467,7 @@ For this test, the body for this request much reference a schema named `File`. ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -455,7 +480,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var fileSchemaTestClass = new FileSchemaTestClass(); // FileSchemaTestClass | try @@ -510,6 +538,7 @@ No authorization required ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -522,7 +551,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var query = query_example; // string | var user = new User(); // User | @@ -581,6 +613,7 @@ To test \"client\" model ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -593,7 +626,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var modelClient = new ModelClient(); // ModelClient | client model try @@ -642,7 +678,7 @@ No authorization required # **TestEndpointParameters** -> void TestEndpointParameters (decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, System.IO.Stream binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = null) +> void TestEndpointParameters (decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, FileParameter binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = null) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -652,6 +688,7 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -668,7 +705,10 @@ namespace Example config.Username = "YOUR_USERNAME"; config.Password = "YOUR_PASSWORD"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var number = 8.14; // decimal | None var _double = 1.2D; // double | None var patternWithoutDelimiter = patternWithoutDelimiter_example; // string | None @@ -678,7 +718,7 @@ namespace Example var int64 = 789; // long? | None (optional) var _float = 3.4F; // float? | None (optional) var _string = _string_example; // string | None (optional) - var binary = BINARY_DATA_HERE; // System.IO.Stream | None (optional) + var binary = BINARY_DATA_HERE; // FileParameter | None (optional) var date = 2013-10-20; // DateTime? | None (optional) var dateTime = 2013-10-20T19:20:30+01:00; // DateTime? | None (optional) (default to "2010-02-01T10:20:10.111110+01:00") var password = password_example; // string | None (optional) @@ -713,7 +753,7 @@ Name | Type | Description | Notes **int64** | **long?**| None | [optional] **_float** | **float?**| None | [optional] **_string** | **string**| None | [optional] - **binary** | **System.IO.Stream****System.IO.Stream**| None | [optional] + **binary** | **FileParameter****FileParameter**| None | [optional] **date** | **DateTime?**| None | [optional] **dateTime** | **DateTime?**| None | [optional] [default to "2010-02-01T10:20:10.111110+01:00"] **password** | **string**| None | [optional] @@ -753,6 +793,7 @@ To test enum parameters ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -765,7 +806,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var enumHeaderStringArray = enumHeaderStringArray_example; // List | Header parameter enum test (string array) (optional) var enumHeaderString = enumHeaderString_example; // string | Header parameter enum test (string) (optional) (default to -efg) var enumQueryStringArray = enumQueryStringArray_example; // List | Query parameter enum test (string array) (optional) @@ -838,6 +882,7 @@ Fake endpoint to test group parameters (optional) ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -853,7 +898,10 @@ namespace Example // Configure Bearer token for authorization: bearer_test config.AccessToken = "YOUR_BEARER_TOKEN"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var requiredStringGroup = 56; // int | Required String in group parameters var requiredBooleanGroup = true; // bool | Required Boolean in group parameters var requiredInt64Group = 789; // long | Required Integer in group parameters @@ -919,6 +967,7 @@ test inline additionalProperties ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -931,7 +980,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var requestBody = new Dictionary(); // Dictionary | request body try @@ -987,6 +1039,7 @@ test json serialization of form data ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -999,7 +1052,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var param = param_example; // string | field1 var param2 = param2_example; // string | field2 @@ -1059,6 +1115,7 @@ To test the collection format in query parameters ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -1071,7 +1128,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new FakeApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); var pipe = new List(); // List | var ioutil = new List(); // List | var http = new List(); // List | diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeClassnameTags123Api.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeClassnameTags123Api.md index 13235fbd10f0..4c748ad71c8e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeClassnameTags123Api.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeClassnameTags123Api.md @@ -19,6 +19,7 @@ To test class name in snake case ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -36,7 +37,10 @@ namespace Example // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key_query", "Bearer"); - var apiInstance = new FakeClassnameTags123Api(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeClassnameTags123Api(httpClient, config, httpClientHandler); var modelClient = new ModelClient(); // ModelClient | client model try diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FormatTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FormatTest.md index 39a70be7ad47..505dbad52df7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FormatTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FormatTest.md @@ -13,7 +13,7 @@ Name | Type | Description | Notes **Decimal** | **decimal** | | [optional] **String** | **string** | | [optional] **Byte** | **byte[]** | | -**Binary** | **System.IO.Stream** | | [optional] +**Binary** | [**FileParameter**](FileParameter.md) | | [optional] **Date** | **DateTime** | | **DateTime** | **DateTime** | | [optional] **Uuid** | **Guid** | | [optional] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/PetApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/PetApi.md index 47820f406dd2..02d0e8e111a6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/PetApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/PetApi.md @@ -25,6 +25,7 @@ Add a new pet to the store ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -40,7 +41,10 @@ namespace Example // Configure OAuth2 access token for authorization: petstore_auth config.AccessToken = "YOUR_ACCESS_TOKEN"; - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var pet = new Pet(); // Pet | Pet object that needs to be added to the store try @@ -96,6 +100,7 @@ Deletes a pet ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -111,7 +116,10 @@ namespace Example // Configure OAuth2 access token for authorization: petstore_auth config.AccessToken = "YOUR_ACCESS_TOKEN"; - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var petId = 789; // long | Pet id to delete var apiKey = apiKey_example; // string | (optional) @@ -171,6 +179,7 @@ Multiple status values can be provided with comma separated strings ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -186,7 +195,10 @@ namespace Example // Configure OAuth2 access token for authorization: petstore_auth config.AccessToken = "YOUR_ACCESS_TOKEN"; - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var status = status_example; // List | Status values that need to be considered for filter try @@ -246,6 +258,7 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -261,7 +274,10 @@ namespace Example // Configure OAuth2 access token for authorization: petstore_auth config.AccessToken = "YOUR_ACCESS_TOKEN"; - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var tags = new List(); // List | Tags to filter by try @@ -321,6 +337,7 @@ Returns a single pet ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -338,7 +355,10 @@ namespace Example // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key", "Bearer"); - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var petId = 789; // long | ID of pet to return try @@ -397,6 +417,7 @@ Update an existing pet ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -412,7 +433,10 @@ namespace Example // Configure OAuth2 access token for authorization: petstore_auth config.AccessToken = "YOUR_ACCESS_TOKEN"; - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var pet = new Pet(); // Pet | Pet object that needs to be added to the store try @@ -470,6 +494,7 @@ Updates a pet in the store with form data ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -485,7 +510,10 @@ namespace Example // Configure OAuth2 access token for authorization: petstore_auth config.AccessToken = "YOUR_ACCESS_TOKEN"; - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var petId = 789; // long | ID of pet that needs to be updated var name = name_example; // string | Updated name of the pet (optional) var status = status_example; // string | Updated status of the pet (optional) @@ -537,7 +565,7 @@ void (empty response body) # **UploadFile** -> ApiResponse UploadFile (long petId, string additionalMetadata = null, System.IO.Stream file = null) +> ApiResponse UploadFile (long petId, string additionalMetadata = null, FileParameter file = null) uploads an image @@ -545,6 +573,7 @@ uploads an image ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -560,10 +589,13 @@ namespace Example // Configure OAuth2 access token for authorization: petstore_auth config.AccessToken = "YOUR_ACCESS_TOKEN"; - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var petId = 789; // long | ID of pet to update var additionalMetadata = additionalMetadata_example; // string | Additional data to pass to server (optional) - var file = BINARY_DATA_HERE; // System.IO.Stream | file to upload (optional) + var file = BINARY_DATA_HERE; // FileParameter | file to upload (optional) try { @@ -588,7 +620,7 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **long**| ID of pet to update | **additionalMetadata** | **string**| Additional data to pass to server | [optional] - **file** | **System.IO.Stream****System.IO.Stream**| file to upload | [optional] + **file** | **FileParameter****FileParameter**| file to upload | [optional] ### Return type @@ -613,7 +645,7 @@ Name | Type | Description | Notes # **UploadFileWithRequiredFile** -> ApiResponse UploadFileWithRequiredFile (long petId, System.IO.Stream requiredFile, string additionalMetadata = null) +> ApiResponse UploadFileWithRequiredFile (long petId, FileParameter requiredFile, string additionalMetadata = null) uploads an image (required) @@ -621,6 +653,7 @@ uploads an image (required) ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -636,9 +669,12 @@ namespace Example // Configure OAuth2 access token for authorization: petstore_auth config.AccessToken = "YOUR_ACCESS_TOKEN"; - var apiInstance = new PetApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new PetApi(httpClient, config, httpClientHandler); var petId = 789; // long | ID of pet to update - var requiredFile = BINARY_DATA_HERE; // System.IO.Stream | file to upload + var requiredFile = BINARY_DATA_HERE; // FileParameter | file to upload var additionalMetadata = additionalMetadata_example; // string | Additional data to pass to server (optional) try @@ -663,7 +699,7 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **long**| ID of pet to update | - **requiredFile** | **System.IO.Stream****System.IO.Stream**| file to upload | + **requiredFile** | **FileParameter****FileParameter**| file to upload | **additionalMetadata** | **string**| Additional data to pass to server | [optional] ### Return type diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/StoreApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/StoreApi.md index 24e2480d5deb..248bf31f849c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/StoreApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/StoreApi.md @@ -22,6 +22,7 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -34,7 +35,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new StoreApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new StoreApi(httpClient, config, httpClientHandler); var orderId = orderId_example; // string | ID of the order that needs to be deleted try @@ -93,6 +97,7 @@ Returns a map of status codes to quantities ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -110,7 +115,10 @@ namespace Example // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key", "Bearer"); - var apiInstance = new StoreApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new StoreApi(httpClient, config, httpClientHandler); try { @@ -165,6 +173,7 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -177,7 +186,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new StoreApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new StoreApi(httpClient, config, httpClientHandler); var orderId = 789; // long | ID of pet that needs to be fetched try @@ -236,6 +248,7 @@ Place an order for a pet ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -248,7 +261,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new StoreApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new StoreApi(httpClient, config, httpClientHandler); var order = new Order(); // Order | order placed for purchasing the pet try diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/UserApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/UserApi.md index aa12c26c69f1..417d9002cf94 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/UserApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/UserApi.md @@ -26,6 +26,7 @@ This can only be done by the logged in user. ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -38,7 +39,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new UserApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new UserApi(httpClient, config, httpClientHandler); var user = new User(); // User | Created user object try @@ -94,6 +98,7 @@ Creates list of users with given input array ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -106,7 +111,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new UserApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new UserApi(httpClient, config, httpClientHandler); var user = new List(); // List | List of user object try @@ -162,6 +170,7 @@ Creates list of users with given input array ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -174,7 +183,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new UserApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new UserApi(httpClient, config, httpClientHandler); var user = new List(); // List | List of user object try @@ -232,6 +244,7 @@ This can only be done by the logged in user. ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -244,7 +257,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new UserApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new UserApi(httpClient, config, httpClientHandler); var username = username_example; // string | The name that needs to be deleted try @@ -301,6 +317,7 @@ Get user by user name ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -313,7 +330,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new UserApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new UserApi(httpClient, config, httpClientHandler); var username = username_example; // string | The name that needs to be fetched. Use user1 for testing. try @@ -372,6 +392,7 @@ Logs user into the system ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -384,7 +405,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new UserApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new UserApi(httpClient, config, httpClientHandler); var username = username_example; // string | The user name for login var password = password_example; // string | The password for login in clear text @@ -444,6 +468,7 @@ Logs out current logged in user session ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -456,7 +481,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new UserApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new UserApi(httpClient, config, httpClientHandler); try { @@ -510,6 +538,7 @@ This can only be done by the logged in user. ```csharp using System.Collections.Generic; using System.Diagnostics; +using System.Net.Http; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; using Org.OpenAPITools.Model; @@ -522,7 +551,10 @@ namespace Example { Configuration config = new Configuration(); config.BasePath = "http://petstore.swagger.io:80/v2"; - var apiInstance = new UserApi(config); + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new UserApi(httpClient, config, httpClientHandler); var username = username_example; // string | name that need to be deleted var user = new User(); // User | Updated user object diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/PetApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/PetApiTests.cs index eca3164a17fd..1af712abb4d0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/PetApiTests.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/PetApiTests.cs @@ -16,6 +16,8 @@ using System.Reflection; using Xunit; +using System.Net.Http; + using Org.OpenAPITools.Client; using Org.OpenAPITools.Api; using Org.OpenAPITools.Model; @@ -34,6 +36,7 @@ public class PetApiTests : IDisposable private PetApi instance; private long petId = 11088; + private long notExsistentPetId = 99999; /// /// Create a Pet object @@ -73,8 +76,10 @@ private byte[] GetBytes(string str) } public PetApiTests() - { - instance = new PetApi(); + { + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + instance = new PetApi(httpClient, httpClientHandler); // create pet Pet p = createPet(); @@ -153,7 +158,9 @@ public void GetPetByIdTest() c1.Timeout = 10000; c1.UserAgent = "TEST_USER_AGENT"; - PetApi petApi = new PetApi(c1); + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + PetApi petApi = new PetApi(httpClient, c1, httpClientHandler); Pet response = petApi.GetPetById(petId); Assert.IsType(response); @@ -198,6 +205,25 @@ public void TestGetPetByIdAsync() Assert.Equal("sample category name2", response.Category.Name); } + /// + /// Test GetPetById on an not existent Id + /// + [Fact] + public void TestGetPetById_TestException() + { + PetApi petApi = new PetApi(); + + var exception = Assert.Throws(() => + { + petApi.GetPetById(notExsistentPetId); + }); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.ErrorContent); + Assert.Equal("Error calling GetPetById: {\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.Message); + } + /* a simple test for binary response. no longer in use. [Fact] public void TestGetByIdBinaryResponse() @@ -241,7 +267,25 @@ public void TestGetPetByIdWithHttpInfoAsync() Assert.Equal(56, response.Category.Id); Assert.Equal("sample category name2", response.Category.Name); } - + + [Fact] + public void TestGetPetByIdWithHttpInfoAsync_Test404Response() + { + PetApi petApi = new PetApi(); + petApi.ExceptionFactory = null; + var response = petApi.GetPetByIdWithHttpInfoAsync(notExsistentPetId).Result; + Pet result = response.Data; + + Assert.IsType>(response); + Assert.Equal(404, (int)response.StatusCode); + Assert.True(response.Headers.ContainsKey("Content-Type")); + Assert.Equal("application/json", response.Headers["Content-Type"][0]); + + Assert.Null(result); + Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", response.RawContent); + Assert.Equal("Not Found", response.ErrorText); + } + /// /// Test UpdatePet /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/PetApiTestsV2.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/PetApiTestsV2.cs new file mode 100644 index 000000000000..e00f3d614671 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Api/PetApiTestsV2.cs @@ -0,0 +1,579 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * + * Generated by: https://github.com/openapitools/openapi-generator.git + */ +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Reflection; +using System.Threading.Tasks; +using Xunit; + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Class for testing PetApi + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the API endpoint. + /// + public class PetApiTestsV2 : IDisposable + { + // CONFIGURE TESTING PARAMETERS HERE + // see the Integration Test Wiki for details: https://github.com/OpenAPITools/openapi-generator/wiki/Integration-Tests + private const string BasePath = "http://petstore.swagger.io/v2"; + private const long PetId = 100000; + private const long NotExistentId = 100001; + + private readonly HttpClient _httpClient = new HttpClient(); + private readonly PetApi _petApi; + + public PetApiTestsV2() + { + // prepare the client + _petApi = new PetApi(_httpClient, new Configuration + { + BasePath = BasePath, + Timeout = 10000, + UserAgent = "TEST_USER_AGENT" + }); + + // add a sample pet for the expected PetId + _petApi.AddPet(BuildSamplePet()); + + // ensure there is not a pet for that ID + try + { + _petApi.DeletePet(NotExistentId); + } + catch (ApiException ex) when (ex.ErrorCode == 404) { } + } + + #region Get + + /// + /// Test GetPetById with an existent Id + /// + [Fact] + public void GetPetById_GivenExistentId_ReturnsPet() + { + Pet expected = BuildSamplePet(); + + Pet response = _petApi.GetPetById(PetId); + + Assert.IsType(response); + Assert.Equal(expected.Name, response.Name); + Assert.Equal(expected.Status, response.Status); + Assert.IsType>(response.Tags); + Assert.Equal(expected.Tags[0].Id, response.Tags[0].Id); + Assert.Equal(expected.Tags[0].Name, response.Tags[0].Name); + Assert.IsType>(response.PhotoUrls); + Assert.Equal(expected.PhotoUrls[0], response.PhotoUrls[0]); + Assert.IsType(response.Category); + Assert.Equal(expected.Category.Id, response.Category.Id); + Assert.Equal(expected.Category.Name, response.Category.Name); + } + + /// + /// Test GetPetById with a not existent Id + /// + [Fact] + public void GetPetById_GivenNotExistentId_ThrowsApiException() + { + var exception = Assert.Throws(() => + { + _petApi.GetPetById(NotExistentId); + }); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.ErrorContent); + Assert.Equal("Error calling GetPetById: {\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.Message); + } + + /// + /// Test GetPetByIdWithHttpInfo with an existent Id + /// + [Fact] + public void GetPetByIdWithHttpInfo_GivenExistentId_Returns200Response() + { + Pet expected = BuildSamplePet(); + + ApiResponse response = _petApi.GetPetByIdWithHttpInfo(PetId); + Pet result = response.Data; + + Assert.IsType>(response); + Assert.Equal(200, (int)response.StatusCode); + Assert.True(response.Headers.ContainsKey("Content-Type")); + Assert.Equal("application/json", response.Headers["Content-Type"][0]); + + Assert.Equal(expected.Name, result.Name); + Assert.Equal(expected.Status, result.Status); + Assert.IsType>(result.Tags); + Assert.Equal(expected.Tags[0].Id, result.Tags[0].Id); + Assert.Equal(expected.Tags[0].Name, result.Tags[0].Name); + Assert.IsType>(result.PhotoUrls); + Assert.Equal(expected.PhotoUrls[0], result.PhotoUrls[0]); + Assert.IsType(result.Category); + Assert.Equal(expected.Category.Id, result.Category.Id); + Assert.Equal(expected.Category.Name, result.Category.Name); + } + + /// + /// Test GetPetByIdWithHttpInfo with a not existent Id and the ExceptionFactory disabled + /// + [Fact] + public void GetPetByIdWithHttpInfo_GivenNotExistentId_ThrowsApiException() + { + var exception = Assert.Throws(() => + { + _petApi.GetPetByIdWithHttpInfo(NotExistentId); + }); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.ErrorContent); + Assert.Equal("Error calling GetPetById: {\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.Message); + } + + /// + /// Test GetPetByIdWithHttpInfo with a not existent Id and the ExceptionFactory disabled + /// + [Fact] + public void GetPetByIdWithHttpInfo_WithoutExceptionFactory_GivenNotExistentId_Returns404Response() + { + _petApi.ExceptionFactory = null; + ApiResponse response = _petApi.GetPetByIdWithHttpInfo(NotExistentId); + Pet result = response.Data; + + Assert.IsType>(response); + Assert.Equal(404, (int)response.StatusCode); + Assert.True(response.Headers.ContainsKey("Content-Type")); + Assert.Equal("application/json", response.Headers["Content-Type"][0]); + + Assert.Null(result); + Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", response.RawContent); + Assert.Equal("Not Found", response.ErrorText); + } + + #endregion + + #region Get Async + + /// + /// Test GetPetByIdAsync with an existent Id. + /// + [Fact] + public async Task GetPetByIdAsync_GivenExistentId_ReturnsPet() + { + Pet expected = BuildSamplePet(); + + Pet response = await _petApi.GetPetByIdAsync(PetId); + + Assert.IsType(response); + Assert.Equal(expected.Name, response.Name); + Assert.Equal(expected.Status, response.Status); + Assert.IsType>(response.Tags); + Assert.Equal(expected.Tags[0].Id, response.Tags[0].Id); + Assert.Equal(expected.Tags[0].Name, response.Tags[0].Name); + Assert.IsType>(response.PhotoUrls); + Assert.Equal(expected.PhotoUrls[0], response.PhotoUrls[0]); + Assert.IsType(response.Category); + Assert.Equal(expected.Category.Id, response.Category.Id); + Assert.Equal(expected.Category.Name, response.Category.Name); + } + + /// + /// Test GetPetByIdAsync with a not existent Id. + /// + [Fact] + public async Task GetPetByIdAsync_GivenNotExistentId_ThrowsApiException() + { + var exception = await Assert.ThrowsAsync(() => _petApi.GetPetByIdAsync(NotExistentId)); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.ErrorContent); + Assert.Equal("Error calling GetPetById: {\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.Message); + } + + /// + /// Test GetPetByIdWithHttpInfoAsync with an existent Id. + /// + [Fact] + public async Task GetPetByIdWithHttpInfoAsync_GivenExistentId_Returns200Response() + { + Pet expected = BuildSamplePet(); + + ApiResponse response = await _petApi.GetPetByIdWithHttpInfoAsync(PetId); + Pet result = response.Data; + + Assert.IsType>(response); + Assert.Equal(200, (int)response.StatusCode); + Assert.True(response.Headers.ContainsKey("Content-Type")); + Assert.Equal("application/json", response.Headers["Content-Type"][0]); + + Assert.Equal(expected.Name, result.Name); + Assert.Equal(expected.Status, result.Status); + Assert.IsType>(result.Tags); + Assert.Equal(expected.Tags[0].Id, result.Tags[0].Id); + Assert.Equal(expected.Tags[0].Name, result.Tags[0].Name); + Assert.IsType>(result.PhotoUrls); + Assert.Equal(expected.PhotoUrls[0], result.PhotoUrls[0]); + Assert.IsType(result.Category); + Assert.Equal(expected.Category.Id, result.Category.Id); + Assert.Equal(expected.Category.Name, result.Category.Name); + } + + /// + /// Test GetPetByIdWithHttpInfoAsync with a not existent Id and the ExceptionFactory disabled. + /// + [Fact] + public async Task GetPetByIdWithHttpInfoAsync_GivenNotExistentId_ThrowsApiException() + { + var exception = await Assert.ThrowsAsync(() => _petApi.GetPetByIdWithHttpInfoAsync(NotExistentId)); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.ErrorContent); + Assert.Equal("Error calling GetPetById: {\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.Message); + } + + /// + /// Test GetPetByIdWithHttpInfoAsync with a not existent Id and the ExceptionFactory disabled. + /// + [Fact] + public async Task GetPetByIdWithHttpInfoAsync_WithoutExceptionFactory_GivenNotExistentId_Returns404Response() + { + _petApi.ExceptionFactory = null; + ApiResponse response = await _petApi.GetPetByIdWithHttpInfoAsync(NotExistentId); + Pet result = response.Data; + + Assert.IsType>(response); + Assert.Equal(404, (int)response.StatusCode); + Assert.True(response.Headers.ContainsKey("Content-Type")); + Assert.Equal("application/json", response.Headers["Content-Type"][0]); + + Assert.Null(result); + Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", response.RawContent); + Assert.Equal("Not Found", response.ErrorText); + } + + #endregion + + #region Find + + /// + /// Test FindPetsByStatus filtering available pets. + /// + [Fact(Skip = "too much elements to fetch, the server cut the json content")] + public void FindPetsByStatus_ReturnsListOfPetsFiltered() + { + List pets = _petApi.FindPetsByStatus(new List(new[] { "available" })); + + foreach (Pet pet in pets) + { + Assert.IsType(pet); + Assert.Equal(Pet.StatusEnum.Available, pet.Status); + } + } + + #endregion + + #region Add + + /// + /// Test AddPet with an existent Id. The current server beavior is to update the Pet. + /// + [Fact] + public void AddPet_GivenExistentId_UpdateThePet() + { + Pet pet = BuildSamplePet(); + + _petApi.AddPet(pet); + } + + #endregion + + #region AddAsync + + /// + /// Test AddPetAsync with an existent Id. The current server beavior is to update the Pet. + /// + [Fact] + public async Task AddPetAsync_GivenExistentId_UpdateThePet() + { + Pet pet = BuildSamplePet(); + + await _petApi.AddPetAsync(pet); + } + + #endregion + + #region Update + + /// + /// Test UpdatePet with an existent Id. + /// + [Fact] + public void UpdatePet_GivenExistentId_UpdateThePet() + { + Pet pet = BuildSamplePet(); + + _petApi.UpdatePet(pet); + } + + /// + /// Test UpdatePet with a not existent Id. The current server beavior is to create the Pet. + /// + [Fact] + public void UpdatePet_GivenNotExistentId_UpdateThePet() + { + Pet pet = BuildSamplePet(i => i.Id = NotExistentId); + + _petApi.UpdatePet(pet); + } + + /// + /// Test UpdatePetWithForm with an existent Id. + /// + [Fact] + public void UpdatePetWithForm_GivenExistentId_UpdatesTheFields() + { + Pet expected = BuildSamplePet(pet => + { + pet.Name = "name updated"; + pet.Status = Pet.StatusEnum.Pending; + }); + + _petApi.UpdatePetWithForm(PetId, "name updated", "pending"); + + Pet response = _petApi.GetPetById(PetId); + + Assert.IsType(response); + Assert.Equal(expected.Name, response.Name); + Assert.Equal(expected.Status, response.Status); + Assert.IsType>(response.Tags); + Assert.Equal(expected.Tags[0].Id, response.Tags[0].Id); + Assert.Equal(expected.Tags[0].Name, response.Tags[0].Name); + Assert.IsType>(response.PhotoUrls); + Assert.Equal(expected.PhotoUrls[0], response.PhotoUrls[0]); + Assert.IsType(response.Category); + Assert.Equal(expected.Category.Id, response.Category.Id); + Assert.Equal(expected.Category.Name, response.Category.Name); + + _petApi.UpdatePetWithForm(PetId, "name updated twice"); + + response = _petApi.GetPetById(PetId); + + Assert.Equal("name updated twice", response.Name); + } + + /// + /// Test UploadFile with an existent Id. + /// + [Fact(Skip = "generates 500 code at the time of test")] + public void UploadFile_UploadFileUsingFormParameters_UpdatesTheFields() + { + var assembly = Assembly.GetExecutingAssembly(); + using Stream imageStream = assembly.GetManifestResourceStream("Org.OpenAPITools.Test.linux-logo.png"); + _petApi.UploadFile(PetId, "metadata sample", imageStream); + } + + /// + /// Test UploadFile with an existent Id. + /// + [Fact(Skip = "generates 500 code at the time of test")] + public void UploadFile_UploadFileAlone_UpdatesTheField() + { + var assembly = Assembly.GetExecutingAssembly(); + using Stream imageStream = assembly.GetManifestResourceStream("Org.OpenAPITools.Test.linux-logo.png"); + _petApi.UploadFile(petId: PetId, file: imageStream); + } + + #endregion + + #region UpdateAsync + + /// + /// Test UpdatePetAsync with an existent Id. + /// + [Fact] + public async Task UpdatePetAsync_GivenExistentId_UpdateThePet() + { + Pet pet = BuildSamplePet(); + + await _petApi.UpdatePetAsync(pet); + } + + /// + /// Test UpdatePetAsync with a not existent Id. The current server beavior is to create the Pet. + /// + [Fact] + public async Task UpdatePetAsync_GivenNotExistentId_UpdateThePet() + { + Pet pet = BuildSamplePet(i => i.Id = NotExistentId); + + await _petApi.UpdatePetAsync(pet); + } + + /// + /// Test UpdatePetWithFormAsync with an existent Id. + /// + [Fact] + public async Task UpdatePetWithFormAsync_GivenExistentId_UpdatesTheFields() + { + Pet expected = BuildSamplePet(pet => + { + pet.Name = "name updated"; + pet.Status = Pet.StatusEnum.Pending; + }); + + await _petApi.UpdatePetWithFormAsync(PetId, "name updated", "pending"); + + Pet response = await _petApi.GetPetByIdAsync(PetId); + + Assert.IsType(response); + Assert.Equal(expected.Name, response.Name); + Assert.Equal(expected.Status, response.Status); + Assert.IsType>(response.Tags); + Assert.Equal(expected.Tags[0].Id, response.Tags[0].Id); + Assert.Equal(expected.Tags[0].Name, response.Tags[0].Name); + Assert.IsType>(response.PhotoUrls); + Assert.Equal(expected.PhotoUrls[0], response.PhotoUrls[0]); + Assert.IsType(response.Category); + Assert.Equal(expected.Category.Id, response.Category.Id); + Assert.Equal(expected.Category.Name, response.Category.Name); + + await _petApi.UpdatePetWithFormAsync(PetId, "name updated twice"); + + response = await _petApi.GetPetByIdAsync(PetId); + + Assert.Equal("name updated twice", response.Name); + } + + /// + /// Test UploadFileAsync with an existent Id. + /// + [Fact(Skip = "generates 500 code at the time of test")] + public async Task UploadFileAsync_UploadFileUsingFormParameters_UpdatesTheFields() + { + var assembly = Assembly.GetExecutingAssembly(); + await using Stream imageStream = assembly.GetManifestResourceStream("Org.OpenAPITools.Test.linux-logo.png"); + await _petApi.UploadFileAsync(PetId, "metadata sample", imageStream); + } + + /// + /// Test UploadFileAsync with an existent Id. + /// + [Fact(Skip = "generates 500 code at the time of test")] + public async Task UploadFileAsync_UploadFileAlone_UpdatesTheField() + { + var assembly = Assembly.GetExecutingAssembly(); + await using Stream imageStream = assembly.GetManifestResourceStream("Org.OpenAPITools.Test.linux-logo.png"); + await _petApi.UploadFileAsync(petId: PetId, file: imageStream); + } + + #endregion + + #region Delete + + /// + /// Test DeletePet with an existent Id. + /// + [Fact] + public void DeletePet_GivenExistentId_DeleteThePet() + { + _petApi.DeletePet(PetId); + + var exception = Assert.Throws(() => _petApi.GetPetById(PetId)); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + } + + /// + /// Test DeletePet with a not existent Id. The current server beavior is to return 404. + /// + [Fact] + public void DeletePet_GivenNotExistentId_ThrowsApiException() + { + var exception = Assert.Throws(() => _petApi.DeletePet(NotExistentId)); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + } + + #endregion + + #region DeleteAsync + + /// + /// Test DeletePet with an existent Id. + /// + [Fact] + public async Task DeletePetAsync_GivenExistentId_DeleteThePet() + { + await _petApi.DeletePetAsync(PetId); + + var exception = Assert.Throws(() => _petApi.GetPetById(PetId)); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + } + + /// + /// Test DeletePet with a not existent Id. The current server beavior is to return 404. + /// + [Fact] + public async Task DeletePetAsync_GivenNotExistentId_ThrowsApiException() + { + var exception = await Assert.ThrowsAsync(() => _petApi.DeletePetAsync(NotExistentId)); + + Assert.IsType(exception); + Assert.Equal(404, exception.ErrorCode); + } + + #endregion + + private static Pet BuildSamplePet(Action callback = null) + { + var pet = new Pet( + name: "csharp test", + photoUrls: new List { "http://petstore.com/csharp_test" }) + { + Id = PetId, + Status = Pet.StatusEnum.Available, + Category = new Category { Id = 10, Name = "sample category" }, + Tags = new List { new Tag { Id = 100, Name = "sample tag" } } + }; + + callback?.Invoke(pet); + + return pet; + } + + public void Dispose() + { + // remove the pet after testing + try + { + _petApi.DeletePet(PetId); + } + catch (ApiException ex) when (ex.ErrorCode == 404) { } + + _petApi.Dispose(); + _httpClient.Dispose(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index dcc1208d75cf..20f33144c2a7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,7 +8,10 @@ - + + + + @@ -18,9 +21,7 @@ - - - - + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index 6ee69d73cd39..8498781b05c4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -100,6 +100,8 @@ public partial class AnotherFakeApi : IDisposable, IAnotherFakeApi /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// public AnotherFakeApi() : this((string)null) @@ -108,9 +110,11 @@ public AnotherFakeApi() : this((string)null) /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. - /// + /// /// public AnotherFakeApi(String basePath) { @@ -126,6 +130,8 @@ public AnotherFakeApi(String basePath) /// /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// An instance of Configuration. /// @@ -148,13 +154,14 @@ public AnotherFakeApi(Org.OpenAPITools.Client.Configuration configuration) /// Initializes a new instance of the class. /// /// An instance of HttpClient. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// /// /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public AnotherFakeApi(HttpClient client) : this(client, (string)null) + public AnotherFakeApi(HttpClient client, HttpClientHandler handler = null) : this(client, (string)null, handler) { } @@ -163,14 +170,15 @@ public AnotherFakeApi(HttpClient client) : this(client, (string)null) /// /// An instance of HttpClient. /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// - /// + /// /// - /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public AnotherFakeApi(HttpClient client, String basePath) + public AnotherFakeApi(HttpClient client, String basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client"); @@ -178,7 +186,7 @@ public AnotherFakeApi(HttpClient client, String basePath) Org.OpenAPITools.Client.GlobalConfiguration.Instance, new Org.OpenAPITools.Client.Configuration { BasePath = basePath } ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath); + this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath, handler); this.Client = this.ApiClient; this.AsynchronousClient = this.ApiClient; this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; @@ -189,81 +197,23 @@ public AnotherFakeApi(HttpClient client, String basePath) /// /// An instance of HttpClient. /// An instance of Configuration. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// /// /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public AnotherFakeApi(HttpClient client, Org.OpenAPITools.Client.Configuration configuration) + public AnotherFakeApi(HttpClient client, Org.OpenAPITools.Client.Configuration configuration, HttpClientHandler handler = null) { if (configuration == null) throw new ArgumentNullException("configuration"); - if (client == null) throw new ArgumentNullException("client"); - - this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( - Org.OpenAPITools.Client.GlobalConfiguration.Instance, - configuration - ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath); - this.Client = this.ApiClient; - this.AsynchronousClient = this.ApiClient; - ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; - } - - /// - /// Initializes a new instance of the class. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// - /// - public AnotherFakeApi(HttpClient client, HttpClientHandler handler) : this(client, handler, (string)null) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// The target service's base path in URL format. - /// - /// - /// - public AnotherFakeApi(HttpClient client, HttpClientHandler handler, String basePath) - { if (client == null) throw new ArgumentNullException("client"); - if (handler == null) throw new ArgumentNullException("handler"); - - this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( - Org.OpenAPITools.Client.GlobalConfiguration.Instance, - new Org.OpenAPITools.Client.Configuration { BasePath = basePath } - ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, handler, this.Configuration.BasePath); - this.Client = this.ApiClient; - this.AsynchronousClient = this.ApiClient; - this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; - } - - /// - /// Initializes a new instance of the class using Configuration object. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// An instance of Configuration. - /// - /// - public AnotherFakeApi(HttpClient client, HttpClientHandler handler, Org.OpenAPITools.Client.Configuration configuration) - { - if (configuration == null) throw new ArgumentNullException("configuration"); - if (client == null) throw new ArgumentNullException("client"); - if (handler == null) throw new ArgumentNullException("handler"); this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, configuration ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, handler, this.Configuration.BasePath); + this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath, handler); this.Client = this.ApiClient; this.AsynchronousClient = this.ApiClient; ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/DefaultApi.cs index f79f629815a8..299f2875b21c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -93,6 +93,8 @@ public partial class DefaultApi : IDisposable, IDefaultApi /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// public DefaultApi() : this((string)null) @@ -101,9 +103,11 @@ public DefaultApi() : this((string)null) /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. - /// + /// /// public DefaultApi(String basePath) { @@ -119,6 +123,8 @@ public DefaultApi(String basePath) /// /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// An instance of Configuration. /// @@ -141,13 +147,14 @@ public DefaultApi(Org.OpenAPITools.Client.Configuration configuration) /// Initializes a new instance of the class. /// /// An instance of HttpClient. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// /// /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public DefaultApi(HttpClient client) : this(client, (string)null) + public DefaultApi(HttpClient client, HttpClientHandler handler = null) : this(client, (string)null, handler) { } @@ -156,14 +163,15 @@ public DefaultApi(HttpClient client) : this(client, (string)null) /// /// An instance of HttpClient. /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// - /// + /// /// - /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public DefaultApi(HttpClient client, String basePath) + public DefaultApi(HttpClient client, String basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client"); @@ -171,7 +179,7 @@ public DefaultApi(HttpClient client, String basePath) Org.OpenAPITools.Client.GlobalConfiguration.Instance, new Org.OpenAPITools.Client.Configuration { BasePath = basePath } ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath); + this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath, handler); this.Client = this.ApiClient; this.AsynchronousClient = this.ApiClient; this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; @@ -182,81 +190,23 @@ public DefaultApi(HttpClient client, String basePath) /// /// An instance of HttpClient. /// An instance of Configuration. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// /// /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public DefaultApi(HttpClient client, Org.OpenAPITools.Client.Configuration configuration) + public DefaultApi(HttpClient client, Org.OpenAPITools.Client.Configuration configuration, HttpClientHandler handler = null) { if (configuration == null) throw new ArgumentNullException("configuration"); - if (client == null) throw new ArgumentNullException("client"); - - this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( - Org.OpenAPITools.Client.GlobalConfiguration.Instance, - configuration - ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath); - this.Client = this.ApiClient; - this.AsynchronousClient = this.ApiClient; - ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; - } - - /// - /// Initializes a new instance of the class. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// - /// - public DefaultApi(HttpClient client, HttpClientHandler handler) : this(client, handler, (string)null) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// The target service's base path in URL format. - /// - /// - /// - public DefaultApi(HttpClient client, HttpClientHandler handler, String basePath) - { if (client == null) throw new ArgumentNullException("client"); - if (handler == null) throw new ArgumentNullException("handler"); - - this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( - Org.OpenAPITools.Client.GlobalConfiguration.Instance, - new Org.OpenAPITools.Client.Configuration { BasePath = basePath } - ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, handler, this.Configuration.BasePath); - this.Client = this.ApiClient; - this.AsynchronousClient = this.ApiClient; - this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; - } - - /// - /// Initializes a new instance of the class using Configuration object. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// An instance of Configuration. - /// - /// - public DefaultApi(HttpClient client, HttpClientHandler handler, Org.OpenAPITools.Client.Configuration configuration) - { - if (configuration == null) throw new ArgumentNullException("configuration"); - if (client == null) throw new ArgumentNullException("client"); - if (handler == null) throw new ArgumentNullException("handler"); this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, configuration ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, handler, this.Configuration.BasePath); + this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath, handler); this.Client = this.ApiClient; this.AsynchronousClient = this.ApiClient; ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeApi.cs index 96d3df634d2f..5631e484c0c3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeApi.cs @@ -227,7 +227,7 @@ public interface IFakeApiSync : IApiAccessor /// None (optional) /// None (optional) /// - void TestEndpointParameters(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), System.IO.Stream binary = default(System.IO.Stream), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string)); + void TestEndpointParameters(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), FileParameter binary = default(FileParameter), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string)); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -251,7 +251,7 @@ public interface IFakeApiSync : IApiAccessor /// None (optional) /// None (optional) /// ApiResponse of Object(void) - ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), System.IO.Stream binary = default(System.IO.Stream), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string)); + ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), FileParameter binary = default(FileParameter), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string)); /// /// To test enum parameters /// @@ -622,7 +622,7 @@ public interface IFakeApiAsync : IApiAccessor /// None (optional) /// Cancellation Token to cancel the request. /// Task of void - System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), System.IO.Stream binary = default(System.IO.Stream), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), FileParameter binary = default(FileParameter), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -647,7 +647,7 @@ public interface IFakeApiAsync : IApiAccessor /// None (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse - System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), System.IO.Stream binary = default(System.IO.Stream), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), FileParameter binary = default(FileParameter), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// /// To test enum parameters /// @@ -817,6 +817,8 @@ public partial class FakeApi : IDisposable, IFakeApi /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// public FakeApi() : this((string)null) @@ -825,9 +827,11 @@ public FakeApi() : this((string)null) /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. - /// + /// /// public FakeApi(String basePath) { @@ -843,6 +847,8 @@ public FakeApi(String basePath) /// /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// An instance of Configuration. /// @@ -865,13 +871,14 @@ public FakeApi(Org.OpenAPITools.Client.Configuration configuration) /// Initializes a new instance of the class. /// /// An instance of HttpClient. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// /// /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public FakeApi(HttpClient client) : this(client, (string)null) + public FakeApi(HttpClient client, HttpClientHandler handler = null) : this(client, (string)null, handler) { } @@ -880,14 +887,15 @@ public FakeApi(HttpClient client) : this(client, (string)null) /// /// An instance of HttpClient. /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// - /// + /// /// - /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public FakeApi(HttpClient client, String basePath) + public FakeApi(HttpClient client, String basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client"); @@ -895,7 +903,7 @@ public FakeApi(HttpClient client, String basePath) Org.OpenAPITools.Client.GlobalConfiguration.Instance, new Org.OpenAPITools.Client.Configuration { BasePath = basePath } ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath); + this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath, handler); this.Client = this.ApiClient; this.AsynchronousClient = this.ApiClient; this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; @@ -906,81 +914,23 @@ public FakeApi(HttpClient client, String basePath) /// /// An instance of HttpClient. /// An instance of Configuration. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// /// /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public FakeApi(HttpClient client, Org.OpenAPITools.Client.Configuration configuration) + public FakeApi(HttpClient client, Org.OpenAPITools.Client.Configuration configuration, HttpClientHandler handler = null) { if (configuration == null) throw new ArgumentNullException("configuration"); - if (client == null) throw new ArgumentNullException("client"); - - this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( - Org.OpenAPITools.Client.GlobalConfiguration.Instance, - configuration - ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath); - this.Client = this.ApiClient; - this.AsynchronousClient = this.ApiClient; - ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; - } - - /// - /// Initializes a new instance of the class. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// - /// - public FakeApi(HttpClient client, HttpClientHandler handler) : this(client, handler, (string)null) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// The target service's base path in URL format. - /// - /// - /// - public FakeApi(HttpClient client, HttpClientHandler handler, String basePath) - { if (client == null) throw new ArgumentNullException("client"); - if (handler == null) throw new ArgumentNullException("handler"); - - this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( - Org.OpenAPITools.Client.GlobalConfiguration.Instance, - new Org.OpenAPITools.Client.Configuration { BasePath = basePath } - ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, handler, this.Configuration.BasePath); - this.Client = this.ApiClient; - this.AsynchronousClient = this.ApiClient; - this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; - } - - /// - /// Initializes a new instance of the class using Configuration object. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// An instance of Configuration. - /// - /// - public FakeApi(HttpClient client, HttpClientHandler handler, Org.OpenAPITools.Client.Configuration configuration) - { - if (configuration == null) throw new ArgumentNullException("configuration"); - if (client == null) throw new ArgumentNullException("client"); - if (handler == null) throw new ArgumentNullException("handler"); this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, configuration ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, handler, this.Configuration.BasePath); + this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath, handler); this.Client = this.ApiClient; this.AsynchronousClient = this.ApiClient; ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; @@ -2074,7 +2024,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI /// None (optional) /// None (optional) /// - public void TestEndpointParameters(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), System.IO.Stream binary = default(System.IO.Stream), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string)) + public void TestEndpointParameters(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), FileParameter binary = default(FileParameter), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string)) { TestEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback); } @@ -2098,7 +2048,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI /// None (optional) /// None (optional) /// ApiResponse of Object(void) - public Org.OpenAPITools.Client.ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), System.IO.Stream binary = default(System.IO.Stream), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string)) + public Org.OpenAPITools.Client.ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), FileParameter binary = default(FileParameter), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string)) { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) @@ -2208,7 +2158,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI /// None (optional) /// Cancellation Token to cancel the request. /// Task of void - public async System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), System.IO.Stream binary = default(System.IO.Stream), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), FileParameter binary = default(FileParameter), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await TestEndpointParametersWithHttpInfoAsync(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback, cancellationToken).ConfigureAwait(false); } @@ -2233,7 +2183,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI /// None (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse - public async System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), System.IO.Stream binary = default(System.IO.Stream), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), FileParameter binary = default(FileParameter), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index 1aa57d4b4e26..efec560791ec 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -100,6 +100,8 @@ public partial class FakeClassnameTags123Api : IDisposable, IFakeClassnameTags12 /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// public FakeClassnameTags123Api() : this((string)null) @@ -108,9 +110,11 @@ public FakeClassnameTags123Api() : this((string)null) /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. - /// + /// /// public FakeClassnameTags123Api(String basePath) { @@ -126,6 +130,8 @@ public FakeClassnameTags123Api(String basePath) /// /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// An instance of Configuration. /// @@ -148,13 +154,14 @@ public FakeClassnameTags123Api(Org.OpenAPITools.Client.Configuration configurati /// Initializes a new instance of the class. /// /// An instance of HttpClient. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// /// /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public FakeClassnameTags123Api(HttpClient client) : this(client, (string)null) + public FakeClassnameTags123Api(HttpClient client, HttpClientHandler handler = null) : this(client, (string)null, handler) { } @@ -163,14 +170,15 @@ public FakeClassnameTags123Api(HttpClient client) : this(client, (string)null) /// /// An instance of HttpClient. /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// - /// + /// /// - /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public FakeClassnameTags123Api(HttpClient client, String basePath) + public FakeClassnameTags123Api(HttpClient client, String basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client"); @@ -178,7 +186,7 @@ public FakeClassnameTags123Api(HttpClient client, String basePath) Org.OpenAPITools.Client.GlobalConfiguration.Instance, new Org.OpenAPITools.Client.Configuration { BasePath = basePath } ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath); + this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath, handler); this.Client = this.ApiClient; this.AsynchronousClient = this.ApiClient; this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; @@ -189,81 +197,23 @@ public FakeClassnameTags123Api(HttpClient client, String basePath) /// /// An instance of HttpClient. /// An instance of Configuration. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// /// /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public FakeClassnameTags123Api(HttpClient client, Org.OpenAPITools.Client.Configuration configuration) + public FakeClassnameTags123Api(HttpClient client, Org.OpenAPITools.Client.Configuration configuration, HttpClientHandler handler = null) { if (configuration == null) throw new ArgumentNullException("configuration"); - if (client == null) throw new ArgumentNullException("client"); - - this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( - Org.OpenAPITools.Client.GlobalConfiguration.Instance, - configuration - ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath); - this.Client = this.ApiClient; - this.AsynchronousClient = this.ApiClient; - ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; - } - - /// - /// Initializes a new instance of the class. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// - /// - public FakeClassnameTags123Api(HttpClient client, HttpClientHandler handler) : this(client, handler, (string)null) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// The target service's base path in URL format. - /// - /// - /// - public FakeClassnameTags123Api(HttpClient client, HttpClientHandler handler, String basePath) - { if (client == null) throw new ArgumentNullException("client"); - if (handler == null) throw new ArgumentNullException("handler"); - - this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( - Org.OpenAPITools.Client.GlobalConfiguration.Instance, - new Org.OpenAPITools.Client.Configuration { BasePath = basePath } - ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, handler, this.Configuration.BasePath); - this.Client = this.ApiClient; - this.AsynchronousClient = this.ApiClient; - this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; - } - - /// - /// Initializes a new instance of the class using Configuration object. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// An instance of Configuration. - /// - /// - public FakeClassnameTags123Api(HttpClient client, HttpClientHandler handler, Org.OpenAPITools.Client.Configuration configuration) - { - if (configuration == null) throw new ArgumentNullException("configuration"); - if (client == null) throw new ArgumentNullException("client"); - if (handler == null) throw new ArgumentNullException("handler"); this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, configuration ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, handler, this.Configuration.BasePath); + this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath, handler); this.Client = this.ApiClient; this.AsynchronousClient = this.ApiClient; ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/PetApi.cs index ab82da44ef0f..1f74cee9c586 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/PetApi.cs @@ -176,7 +176,7 @@ public interface IPetApiSync : IApiAccessor /// Additional data to pass to server (optional) /// file to upload (optional) /// ApiResponse - ApiResponse UploadFile(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream)); + ApiResponse UploadFile(long petId, string additionalMetadata = default(string), FileParameter file = default(FileParameter)); /// /// uploads an image @@ -189,7 +189,7 @@ public interface IPetApiSync : IApiAccessor /// Additional data to pass to server (optional) /// file to upload (optional) /// ApiResponse of ApiResponse - ApiResponse UploadFileWithHttpInfo(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream)); + ApiResponse UploadFileWithHttpInfo(long petId, string additionalMetadata = default(string), FileParameter file = default(FileParameter)); /// /// uploads an image (required) /// @@ -198,7 +198,7 @@ public interface IPetApiSync : IApiAccessor /// file to upload /// Additional data to pass to server (optional) /// ApiResponse - ApiResponse UploadFileWithRequiredFile(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string)); + ApiResponse UploadFileWithRequiredFile(long petId, FileParameter requiredFile, string additionalMetadata = default(string)); /// /// uploads an image (required) @@ -211,7 +211,7 @@ public interface IPetApiSync : IApiAccessor /// file to upload /// Additional data to pass to server (optional) /// ApiResponse of ApiResponse - ApiResponse UploadFileWithRequiredFileWithHttpInfo(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string)); + ApiResponse UploadFileWithRequiredFileWithHttpInfo(long petId, FileParameter requiredFile, string additionalMetadata = default(string)); #endregion Synchronous Operations } @@ -400,7 +400,7 @@ public interface IPetApiAsync : IApiAccessor /// file to upload (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse - System.Threading.Tasks.Task UploadFileAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task UploadFileAsync(long petId, string additionalMetadata = default(string), FileParameter file = default(FileParameter), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// /// uploads an image @@ -414,7 +414,7 @@ public interface IPetApiAsync : IApiAccessor /// file to upload (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse (ApiResponse) - System.Threading.Tasks.Task> UploadFileWithHttpInfoAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task> UploadFileWithHttpInfoAsync(long petId, string additionalMetadata = default(string), FileParameter file = default(FileParameter), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// /// uploads an image (required) /// @@ -427,7 +427,7 @@ public interface IPetApiAsync : IApiAccessor /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse - System.Threading.Tasks.Task UploadFileWithRequiredFileAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task UploadFileWithRequiredFileAsync(long petId, FileParameter requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// /// uploads an image (required) @@ -441,7 +441,7 @@ public interface IPetApiAsync : IApiAccessor /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse (ApiResponse) - System.Threading.Tasks.Task> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, FileParameter requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); #endregion Asynchronous Operations } @@ -462,6 +462,8 @@ public partial class PetApi : IDisposable, IPetApi /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// public PetApi() : this((string)null) @@ -470,9 +472,11 @@ public PetApi() : this((string)null) /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. - /// + /// /// public PetApi(String basePath) { @@ -488,6 +492,8 @@ public PetApi(String basePath) /// /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// An instance of Configuration. /// @@ -510,13 +516,14 @@ public PetApi(Org.OpenAPITools.Client.Configuration configuration) /// Initializes a new instance of the class. /// /// An instance of HttpClient. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// /// /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public PetApi(HttpClient client) : this(client, (string)null) + public PetApi(HttpClient client, HttpClientHandler handler = null) : this(client, (string)null, handler) { } @@ -525,14 +532,15 @@ public PetApi(HttpClient client) : this(client, (string)null) /// /// An instance of HttpClient. /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// - /// + /// /// - /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public PetApi(HttpClient client, String basePath) + public PetApi(HttpClient client, String basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client"); @@ -540,7 +548,7 @@ public PetApi(HttpClient client, String basePath) Org.OpenAPITools.Client.GlobalConfiguration.Instance, new Org.OpenAPITools.Client.Configuration { BasePath = basePath } ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath); + this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath, handler); this.Client = this.ApiClient; this.AsynchronousClient = this.ApiClient; this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; @@ -551,81 +559,23 @@ public PetApi(HttpClient client, String basePath) /// /// An instance of HttpClient. /// An instance of Configuration. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// /// /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public PetApi(HttpClient client, Org.OpenAPITools.Client.Configuration configuration) + public PetApi(HttpClient client, Org.OpenAPITools.Client.Configuration configuration, HttpClientHandler handler = null) { if (configuration == null) throw new ArgumentNullException("configuration"); - if (client == null) throw new ArgumentNullException("client"); - - this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( - Org.OpenAPITools.Client.GlobalConfiguration.Instance, - configuration - ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath); - this.Client = this.ApiClient; - this.AsynchronousClient = this.ApiClient; - ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; - } - - /// - /// Initializes a new instance of the class. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// - /// - public PetApi(HttpClient client, HttpClientHandler handler) : this(client, handler, (string)null) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// The target service's base path in URL format. - /// - /// - /// - public PetApi(HttpClient client, HttpClientHandler handler, String basePath) - { if (client == null) throw new ArgumentNullException("client"); - if (handler == null) throw new ArgumentNullException("handler"); - - this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( - Org.OpenAPITools.Client.GlobalConfiguration.Instance, - new Org.OpenAPITools.Client.Configuration { BasePath = basePath } - ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, handler, this.Configuration.BasePath); - this.Client = this.ApiClient; - this.AsynchronousClient = this.ApiClient; - this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; - } - - /// - /// Initializes a new instance of the class using Configuration object. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// An instance of Configuration. - /// - /// - public PetApi(HttpClient client, HttpClientHandler handler, Org.OpenAPITools.Client.Configuration configuration) - { - if (configuration == null) throw new ArgumentNullException("configuration"); - if (client == null) throw new ArgumentNullException("client"); - if (handler == null) throw new ArgumentNullException("handler"); this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, configuration ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, handler, this.Configuration.BasePath); + this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath, handler); this.Client = this.ApiClient; this.AsynchronousClient = this.ApiClient; ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; @@ -1740,7 +1690,7 @@ public Org.OpenAPITools.Client.ApiResponse UpdatePetWithHttpInfo(Pet pet /// Additional data to pass to server (optional) /// file to upload (optional) /// ApiResponse - public ApiResponse UploadFile(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream)) + public ApiResponse UploadFile(long petId, string additionalMetadata = default(string), FileParameter file = default(FileParameter)) { Org.OpenAPITools.Client.ApiResponse localVarResponse = UploadFileWithHttpInfo(petId, additionalMetadata, file); return localVarResponse.Data; @@ -1754,7 +1704,7 @@ public Org.OpenAPITools.Client.ApiResponse UpdatePetWithHttpInfo(Pet pet /// Additional data to pass to server (optional) /// file to upload (optional) /// ApiResponse of ApiResponse - public Org.OpenAPITools.Client.ApiResponse UploadFileWithHttpInfo(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream)) + public Org.OpenAPITools.Client.ApiResponse UploadFileWithHttpInfo(long petId, string additionalMetadata = default(string), FileParameter file = default(FileParameter)) { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1811,7 +1761,7 @@ public Org.OpenAPITools.Client.ApiResponse UpdatePetWithHttpInfo(Pet pet /// file to upload (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse - public async System.Threading.Tasks.Task UploadFileAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task UploadFileAsync(long petId, string additionalMetadata = default(string), FileParameter file = default(FileParameter), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Org.OpenAPITools.Client.ApiResponse localVarResponse = await UploadFileWithHttpInfoAsync(petId, additionalMetadata, file, cancellationToken).ConfigureAwait(false); return localVarResponse.Data; @@ -1826,7 +1776,7 @@ public Org.OpenAPITools.Client.ApiResponse UpdatePetWithHttpInfo(Pet pet /// file to upload (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse (ApiResponse) - public async System.Threading.Tasks.Task> UploadFileWithHttpInfoAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task> UploadFileWithHttpInfoAsync(long petId, string additionalMetadata = default(string), FileParameter file = default(FileParameter), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1885,7 +1835,7 @@ public Org.OpenAPITools.Client.ApiResponse UpdatePetWithHttpInfo(Pet pet /// file to upload /// Additional data to pass to server (optional) /// ApiResponse - public ApiResponse UploadFileWithRequiredFile(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string)) + public ApiResponse UploadFileWithRequiredFile(long petId, FileParameter requiredFile, string additionalMetadata = default(string)) { Org.OpenAPITools.Client.ApiResponse localVarResponse = UploadFileWithRequiredFileWithHttpInfo(petId, requiredFile, additionalMetadata); return localVarResponse.Data; @@ -1899,7 +1849,7 @@ public Org.OpenAPITools.Client.ApiResponse UpdatePetWithHttpInfo(Pet pet /// file to upload /// Additional data to pass to server (optional) /// ApiResponse of ApiResponse - public Org.OpenAPITools.Client.ApiResponse UploadFileWithRequiredFileWithHttpInfo(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string)) + public Org.OpenAPITools.Client.ApiResponse UploadFileWithRequiredFileWithHttpInfo(long petId, FileParameter requiredFile, string additionalMetadata = default(string)) { // verify the required parameter 'requiredFile' is set if (requiredFile == null) @@ -1957,7 +1907,7 @@ public Org.OpenAPITools.Client.ApiResponse UpdatePetWithHttpInfo(Pet pet /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse - public async System.Threading.Tasks.Task UploadFileWithRequiredFileAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task UploadFileWithRequiredFileAsync(long petId, FileParameter requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Org.OpenAPITools.Client.ApiResponse localVarResponse = await UploadFileWithRequiredFileWithHttpInfoAsync(petId, requiredFile, additionalMetadata, cancellationToken).ConfigureAwait(false); return localVarResponse.Data; @@ -1972,7 +1922,7 @@ public Org.OpenAPITools.Client.ApiResponse UpdatePetWithHttpInfo(Pet pet /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse (ApiResponse) - public async System.Threading.Tasks.Task> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, FileParameter requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // verify the required parameter 'requiredFile' is set if (requiredFile == null) diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/StoreApi.cs index 760576e1ec06..d7b0b43698af 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/StoreApi.cs @@ -225,6 +225,8 @@ public partial class StoreApi : IDisposable, IStoreApi /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// public StoreApi() : this((string)null) @@ -233,9 +235,11 @@ public StoreApi() : this((string)null) /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. - /// + /// /// public StoreApi(String basePath) { @@ -251,6 +255,8 @@ public StoreApi(String basePath) /// /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// An instance of Configuration. /// @@ -273,13 +279,14 @@ public StoreApi(Org.OpenAPITools.Client.Configuration configuration) /// Initializes a new instance of the class. /// /// An instance of HttpClient. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// /// /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public StoreApi(HttpClient client) : this(client, (string)null) + public StoreApi(HttpClient client, HttpClientHandler handler = null) : this(client, (string)null, handler) { } @@ -288,14 +295,15 @@ public StoreApi(HttpClient client) : this(client, (string)null) /// /// An instance of HttpClient. /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// - /// + /// /// - /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public StoreApi(HttpClient client, String basePath) + public StoreApi(HttpClient client, String basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client"); @@ -303,7 +311,7 @@ public StoreApi(HttpClient client, String basePath) Org.OpenAPITools.Client.GlobalConfiguration.Instance, new Org.OpenAPITools.Client.Configuration { BasePath = basePath } ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath); + this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath, handler); this.Client = this.ApiClient; this.AsynchronousClient = this.ApiClient; this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; @@ -314,81 +322,23 @@ public StoreApi(HttpClient client, String basePath) /// /// An instance of HttpClient. /// An instance of Configuration. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// /// /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public StoreApi(HttpClient client, Org.OpenAPITools.Client.Configuration configuration) + public StoreApi(HttpClient client, Org.OpenAPITools.Client.Configuration configuration, HttpClientHandler handler = null) { if (configuration == null) throw new ArgumentNullException("configuration"); - if (client == null) throw new ArgumentNullException("client"); - - this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( - Org.OpenAPITools.Client.GlobalConfiguration.Instance, - configuration - ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath); - this.Client = this.ApiClient; - this.AsynchronousClient = this.ApiClient; - ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; - } - - /// - /// Initializes a new instance of the class. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// - /// - public StoreApi(HttpClient client, HttpClientHandler handler) : this(client, handler, (string)null) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// The target service's base path in URL format. - /// - /// - /// - public StoreApi(HttpClient client, HttpClientHandler handler, String basePath) - { if (client == null) throw new ArgumentNullException("client"); - if (handler == null) throw new ArgumentNullException("handler"); - - this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( - Org.OpenAPITools.Client.GlobalConfiguration.Instance, - new Org.OpenAPITools.Client.Configuration { BasePath = basePath } - ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, handler, this.Configuration.BasePath); - this.Client = this.ApiClient; - this.AsynchronousClient = this.ApiClient; - this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; - } - - /// - /// Initializes a new instance of the class using Configuration object. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// An instance of Configuration. - /// - /// - public StoreApi(HttpClient client, HttpClientHandler handler, Org.OpenAPITools.Client.Configuration configuration) - { - if (configuration == null) throw new ArgumentNullException("configuration"); - if (client == null) throw new ArgumentNullException("client"); - if (handler == null) throw new ArgumentNullException("handler"); this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, configuration ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, handler, this.Configuration.BasePath); + this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath, handler); this.Client = this.ApiClient; this.AsynchronousClient = this.ApiClient; ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/UserApi.cs index c1174daeadfb..9b4826f955eb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/UserApi.cs @@ -397,6 +397,8 @@ public partial class UserApi : IDisposable, IUserApi /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// public UserApi() : this((string)null) @@ -405,9 +407,11 @@ public UserApi() : this((string)null) /// /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. - /// + /// /// public UserApi(String basePath) { @@ -423,6 +427,8 @@ public UserApi(String basePath) /// /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// An instance of Configuration. /// @@ -445,13 +451,14 @@ public UserApi(Org.OpenAPITools.Client.Configuration configuration) /// Initializes a new instance of the class. /// /// An instance of HttpClient. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// /// /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public UserApi(HttpClient client) : this(client, (string)null) + public UserApi(HttpClient client, HttpClientHandler handler = null) : this(client, (string)null, handler) { } @@ -460,14 +467,15 @@ public UserApi(HttpClient client) : this(client, (string)null) /// /// An instance of HttpClient. /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// - /// + /// /// - /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public UserApi(HttpClient client, String basePath) + public UserApi(HttpClient client, String basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client"); @@ -475,7 +483,7 @@ public UserApi(HttpClient client, String basePath) Org.OpenAPITools.Client.GlobalConfiguration.Instance, new Org.OpenAPITools.Client.Configuration { BasePath = basePath } ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath); + this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath, handler); this.Client = this.ApiClient; this.AsynchronousClient = this.ApiClient; this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; @@ -486,81 +494,23 @@ public UserApi(HttpClient client, String basePath) /// /// An instance of HttpClient. /// An instance of Configuration. + /// An optional instance of HttpClientHandler that is used by HttpClient. /// /// /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public UserApi(HttpClient client, Org.OpenAPITools.Client.Configuration configuration) + public UserApi(HttpClient client, Org.OpenAPITools.Client.Configuration configuration, HttpClientHandler handler = null) { if (configuration == null) throw new ArgumentNullException("configuration"); - if (client == null) throw new ArgumentNullException("client"); - - this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( - Org.OpenAPITools.Client.GlobalConfiguration.Instance, - configuration - ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath); - this.Client = this.ApiClient; - this.AsynchronousClient = this.ApiClient; - ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; - } - - /// - /// Initializes a new instance of the class. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// - /// - public UserApi(HttpClient client, HttpClientHandler handler) : this(client, handler, (string)null) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// The target service's base path in URL format. - /// - /// - /// - public UserApi(HttpClient client, HttpClientHandler handler, String basePath) - { if (client == null) throw new ArgumentNullException("client"); - if (handler == null) throw new ArgumentNullException("handler"); - - this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( - Org.OpenAPITools.Client.GlobalConfiguration.Instance, - new Org.OpenAPITools.Client.Configuration { BasePath = basePath } - ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, handler, this.Configuration.BasePath); - this.Client = this.ApiClient; - this.AsynchronousClient = this.ApiClient; - this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; - } - - /// - /// Initializes a new instance of the class using Configuration object. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// An instance of Configuration. - /// - /// - public UserApi(HttpClient client, HttpClientHandler handler, Org.OpenAPITools.Client.Configuration configuration) - { - if (configuration == null) throw new ArgumentNullException("configuration"); - if (client == null) throw new ArgumentNullException("client"); - if (handler == null) throw new ArgumentNullException("handler"); this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, configuration ); - this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, handler, this.Configuration.BasePath); + this.ApiClient = new Org.OpenAPITools.Client.ApiClient(client, this.Configuration.BasePath, handler); this.Client = this.ApiClient; this.AsynchronousClient = this.ApiClient; ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs index 6cf20d594436..bc7d7d847851 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs @@ -80,9 +80,9 @@ public string Serialize(object obj) } } - public T Deserialize(HttpResponseMessage response) + public async Task Deserialize(HttpResponseMessage response) { - var result = (T)Deserialize(response, typeof(T)); + var result = (T) await Deserialize(response, typeof(T)); return result; } @@ -92,19 +92,19 @@ public T Deserialize(HttpResponseMessage response) /// The HTTP response. /// Object type. /// Object representation of the JSON string. - internal object Deserialize(HttpResponseMessage response, Type type) + internal async Task Deserialize(HttpResponseMessage response, Type type) { IList headers = response.Headers.Select(x => x.Key + "=" + x.Value).ToList(); if (type == typeof(byte[])) // return byte array { - return response.Content.ReadAsByteArrayAsync().Result; + return await response.Content.ReadAsByteArrayAsync(); } // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) if (type == typeof(Stream)) { - var bytes = response.Content.ReadAsByteArrayAsync().Result; + var bytes = await response.Content.ReadAsByteArrayAsync(); if (headers != null) { var filePath = String.IsNullOrEmpty(_configuration.TempFolderPath) @@ -128,18 +128,18 @@ internal object Deserialize(HttpResponseMessage response, Type type) if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content.ReadAsStringAsync().Result, null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(await response.Content.ReadAsStringAsync(), null, System.Globalization.DateTimeStyles.RoundtripKind); } if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type { - return Convert.ChangeType(response.Content.ReadAsStringAsync().Result, type); + return Convert.ChangeType(await response.Content.ReadAsStringAsync(), type); } // at this point, it must be a model (json) try { - return JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result, type, _serializerSettings); + return JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync(), type, _serializerSettings); } catch (Exception e) { @@ -168,9 +168,9 @@ public partial class ApiClient : IDisposable, ISynchronousClient, IAsynchronousC { private readonly String _baseUrl; - private readonly HttpClientHandler _httpClientHandler; - private readonly HttpClient _httpClient; - private readonly bool _disposeClient; + private readonly HttpClientHandler _httpClientHandler; + private readonly HttpClient _httpClient; + private readonly bool _disposeClient; /// /// Specifies the settings on a object. @@ -191,89 +191,66 @@ public partial class ApiClient : IDisposable, ISynchronousClient, IAsynchronousC /// /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// public ApiClient() : this(Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath) - { + { } - + /// /// Initializes a new instance of the . + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. /// /// The target service's base path in URL format. /// public ApiClient(String basePath) - { - if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); + { + if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); - _httpClientHandler = new HttpClientHandler(); - _httpClient = new HttpClient(_httpClientHandler, true); + _httpClientHandler = new HttpClientHandler(); + _httpClient = new HttpClient(_httpClientHandler, true); _disposeClient = true; - _baseUrl = basePath; + _baseUrl = basePath; } - + /// /// Initializes a new instance of the , defaulting to the global configurations' base url. /// /// An instance of HttpClient. - /// - /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. - /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. - /// - public ApiClient(HttpClient client) : - this(client, Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath) - { - } - - /// - /// Initializes a new instance of the - /// - /// An instance of HttpClient. - /// The target service's base path in URL format. - /// - /// - /// - /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. - /// - public ApiClient(HttpClient client, String basePath) - { - if (client == null) throw new ArgumentNullException("client cannot be null"); - if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); - - _httpClient = client; - _baseUrl = basePath; + /// + public ApiClient(HttpClient client, HttpClientHandler handler = null) : + this(client, Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath, handler) + { } - - /// - /// Initializes a new instance of the , defaulting to the global configurations' base url. - /// - /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// - public ApiClient(HttpClient client, HttpClientHandler handler) : - this(client, handler, Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath) - { - } - - /// + + /// /// Initializes a new instance of the . /// /// An instance of HttpClient. - /// An instance of HttpClientHandler that is used by HttpClient. - /// The target service's base path in URL format. - /// - /// - public ApiClient(HttpClient client, HttpClientHandler handler, String basePath) - { - if (client == null) throw new ArgumentNullException("client cannot be null"); - if (handler == null) throw new ArgumentNullException("handler cannot be null"); - if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); - - _httpClientHandler = handler; - _httpClient = client; - _baseUrl = basePath; + /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public ApiClient(HttpClient client, String basePath, HttpClientHandler handler = null) + { + if (client == null) throw new ArgumentNullException("client cannot be null"); + if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); + + _httpClientHandler = handler; + _httpClient = client; + _baseUrl = basePath; } /// @@ -300,12 +277,10 @@ HttpContent PrepareMultipartFormDataContent(RequestOptions options) { foreach (var fileParam in options.FileParameters) { - var fileStream = fileParam.Value as FileStream; - var fileStreamName = fileStream != null ? System.IO.Path.GetFileName(fileStream.Name) : null; - var content = new StreamContent(fileParam.Value); + var content = new StreamContent(fileParam.Value.Content); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); multipartContent.Add(content, fileParam.Key, - fileStreamName ?? "no_file_name_provided"); + fileParam.Value.Name); } } return multipartContent; @@ -337,11 +312,7 @@ private HttpRequestMessage NewRequest( builder.AddPathParameters(options.PathParameters); - // In case of POST or PUT pass query parameters in request body - if (method != HttpMethod.Post && method != HttpMethod.Put) - { - builder.AddQueryParameters(options.QueryParameters); - } + builder.AddQueryParameters(options.QueryParameters); HttpRequestMessage request = new HttpRequestMessage(method, builder.GetFullUri()); @@ -391,11 +362,11 @@ private HttpRequestMessage NewRequest( { if (options.Data != null) { - if (options.Data is Stream s) + if (options.Data is FileParameter fp) { contentType = contentType ?? "application/octet-stream"; - var streamContent = new StreamContent(s); + var streamContent = new StreamContent(fp.Content); streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Content = streamContent; } @@ -422,10 +393,10 @@ private HttpRequestMessage NewRequest( partial void InterceptRequest(HttpRequestMessage req); partial void InterceptResponse(HttpRequestMessage req, HttpResponseMessage response); - private ApiResponse ToApiResponse(HttpResponseMessage response, object responseData, Uri uri) + private async Task> ToApiResponse(HttpResponseMessage response, object responseData, Uri uri) { T result = (T) responseData; - string rawContent = response.Content.ToString(); + string rawContent = await response.Content.ReadAsStringAsync(); var transformed = new ApiResponse(response.StatusCode, new Multimap(), result, rawContent) { @@ -467,7 +438,7 @@ private ApiResponse ToApiResponse(HttpResponseMessage response, object res private ApiResponse Exec(HttpRequestMessage req, IReadableConfiguration configuration) { - return ExecAsync(req, configuration).Result; + return ExecAsync(req, configuration).GetAwaiter().GetResult(); } private async Task> ExecAsync(HttpRequestMessage req, @@ -528,7 +499,12 @@ private async Task> ExecAsync(HttpRequestMessage req, response = await _httpClient.SendAsync(req, cancellationToken).ConfigureAwait(false); } - object responseData = deserializer.Deserialize(response); + if (!response.IsSuccessStatusCode) + { + return await ToApiResponse(response, default(T), req.RequestUri); + } + + object responseData = await deserializer.Deserialize(response); // if the response type is oneOf/anyOf, call FromJSON to deserialize the data if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) @@ -542,9 +518,7 @@ private async Task> ExecAsync(HttpRequestMessage req, InterceptResponse(req, response); - var result = ToApiResponse(response, responseData, req.RequestUri); - - return result; + return await ToApiResponse(response, responseData, req.RequestUri); } #region IAsynchronousClient diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/FileParameter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/FileParameter.cs new file mode 100644 index 000000000000..4a83ada8588f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/FileParameter.cs @@ -0,0 +1,62 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System.IO; + +namespace Org.OpenAPITools.Client +{ + + /// + /// Represents a File passed to the API as a Parameter, allows using different backends for files + /// + public class FileParameter + { + /// + /// The filename + /// + public string Name { get; set; } = "no_name_provided"; + + /// + /// The content of the file + /// + public Stream Content { get; set; } + + /// + /// Construct a FileParameter just from the contents, will extract the filename from a filestream + /// + /// The file content + public FileParameter(Stream content) + { + if (content is FileStream fs) + { + Name = fs.Name; + } + Content = content; + } + + /// + /// Construct a FileParameter from name and content + /// + /// The filename + /// The file content + public FileParameter(string filename, Stream content) + { + Name = filename; + Content = content; + } + + /// + /// Implicit conversion of stream to file parameter. Useful for backwards compatibility. + /// + /// Stream to convert + /// FileParameter + public static implicit operator FileParameter(Stream s) => new FileParameter(s); + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/RequestOptions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/RequestOptions.cs index d8da585db9c0..9c0a9a9f968f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/RequestOptions.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/RequestOptions.cs @@ -46,7 +46,7 @@ public class RequestOptions /// /// File parameters to be sent along with the request. /// - public Dictionary FileParameters { get; set; } + public Dictionary FileParameters { get; set; } /// /// Cookies to be sent along with the request. @@ -67,7 +67,7 @@ public RequestOptions() QueryParameters = new Multimap(); HeaderParameters = new Multimap(); FormParameters = new Dictionary(); - FileParameters = new Dictionary(); + FileParameters = new Dictionary(); Cookies = new List(); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs index 5f212ec734f2..5c88c5a5ce9b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Animal.cs index 95c79122ad70..c39799127da3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Animal.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ApiResponse.cs index c9a0a78efa72..5a990e9f881f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ApiResponse.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Apple.cs index b414d3021a66..d52db06ca2e9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Apple.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Apple.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AppleReq.cs index a12033584928..3354d6a5932c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AppleReq.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs index bf2c8663ff64..52f424010d5c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs index 09a9bbb88500..da6a1f502007 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayTest.cs index 4406ffb33ea8..3b9b986b9aeb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayTest.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Banana.cs index a7513bb453af..630ae7ecf0d3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Banana.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Banana.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BananaReq.cs index 4a52e918a46e..0a22d500b132 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BananaReq.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BasquePig.cs index 5c6f9a0e83db..ade2a65ef240 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BasquePig.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Capitalization.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Capitalization.cs index a4ab27bd8986..1ca2387e23cd 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Capitalization.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Capitalization.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Cat.cs index 3fd19648bb9c..e62e22180fe4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Cat.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/CatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/CatAllOf.cs index 8d61cf77b64c..c47a05d16c2b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/CatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/CatAllOf.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Category.cs index 581a23ef2a59..35dd26746958 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Category.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs index e883d3d20bb3..66e6c4ec0eea 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCatAllOf.cs index 36268a8093a2..5c28c73530cf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCatAllOf.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ClassModel.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ClassModel.cs index bb2121cd5177..52cedf0979d3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ClassModel.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ClassModel.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index 78f3c6c03e3a..cccb856a6509 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DanishPig.cs index dd2de1d038a5..68bf604b95f8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DanishPig.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Dog.cs index 1ff9ab1624dc..5abe5bc73b3c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Dog.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DogAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DogAllOf.cs index cd2f1a0eeecc..b33fdf12c682 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DogAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DogAllOf.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs index 28e2ea556933..7240327f31e0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumArrays.cs index be9b0c5e801f..ca4515c95da1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumClass.cs index 48b3d7d0e7e0..324fb5fba895 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumClass.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumTest.cs index c9c56e18386f..a5135a7f39a8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumTest.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index ed443f68cf77..751b3b8a99a4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/File.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/File.cs index af4a38ae023d..81bd9c7fbef1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/File.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/File.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs index cc6b3e34c5db..1195e6656500 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Foo.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Foo.cs index 836374681193..b1fa5a8fa438 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Foo.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Foo.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FormatTest.cs index 9e7466bb502e..c2dd5cc4d71f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FormatTest.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; @@ -59,7 +60,7 @@ protected FormatTest() /// password (required). /// A string that is a 10 digit number. Can have leading zeros.. /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01.. - public FormatTest(int integer = default(int), int int32 = default(int), long int64 = default(long), decimal number = default(decimal), float _float = default(float), double _double = default(double), decimal _decimal = default(decimal), string _string = default(string), byte[] _byte = default(byte[]), System.IO.Stream binary = default(System.IO.Stream), DateTime date = default(DateTime), DateTime dateTime = default(DateTime), Guid uuid = default(Guid), string password = default(string), string patternWithDigits = default(string), string patternWithDigitsAndDelimiter = default(string)) + public FormatTest(int integer = default(int), int int32 = default(int), long int64 = default(long), decimal number = default(decimal), float _float = default(float), double _double = default(double), decimal _decimal = default(decimal), string _string = default(string), byte[] _byte = default(byte[]), FileParameter binary = default(FileParameter), DateTime date = default(DateTime), DateTime dateTime = default(DateTime), Guid uuid = default(Guid), string password = default(string), string patternWithDigits = default(string), string patternWithDigitsAndDelimiter = default(string)) { this.Number = number; // to ensure "_byte" is required (not null) @@ -140,7 +141,7 @@ protected FormatTest() /// Gets or Sets Binary /// [DataMember(Name = "binary", EmitDefaultValue = false)] - public System.IO.Stream Binary { get; set; } + public FileParameter Binary { get; set; } /// /// Gets or Sets Date diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Fruit.cs index 132be5b4d3bd..40a654afced5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Fruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Fruit.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; using System.Reflection; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FruitReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FruitReq.cs index 380896933df8..170960035f4d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FruitReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FruitReq.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; using System.Reflection; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GmFruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GmFruit.cs index c168aa41d4ce..4aef7618a378 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GmFruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GmFruit.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index 9352d27022f2..129aae285549 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index 3a2c3d26a92c..84c369eb4786 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HealthCheckResult.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HealthCheckResult.cs index 1cd90560cbed..e6b4399e926b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HealthCheckResult.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HealthCheckResult.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs index 5f4b24acafa1..0352d11ac24d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index 46963173f71a..a7416acf77b9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/List.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/List.cs index ecf4e8ff00ea..10cd9420a74d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/List.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/List.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Mammal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Mammal.cs index 2e847a10eb6c..55f278a25ac0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Mammal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Mammal.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; using System.Reflection; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MapTest.cs index b88cfef72c10..76f2c995a93e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MapTest.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index dc3d45a080a4..88d8e6493d9f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Model200Response.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Model200Response.cs index b1e76d250816..50eb434c96d0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Model200Response.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Model200Response.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ModelClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ModelClient.cs index 4ee431a9b2f2..744bda615644 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ModelClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ModelClient.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Name.cs index a6a01dd4ed3e..25cd5ddb6356 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Name.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs index 4ceaab61bc63..f3fdf07243cf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableShape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableShape.cs index 80339ebf79bb..b2be225d54cb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableShape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableShape.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; using System.Reflection; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NumberOnly.cs index e9b006094cf6..3932b5404eec 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NumberOnly.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Order.cs index 4f327640915d..d7a06f4eef80 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Order.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Order.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterComposite.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterComposite.cs index 1e4e03993e05..c9d3dd0b595a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterComposite.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterComposite.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnum.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnum.cs index 2aa496a2e074..f3ee68510aa5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnum.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnum.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs index dd79c7010d6b..60fb98c58dc6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumInteger.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumInteger.cs index 44dc91c700ad..8624155f7451 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumInteger.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumInteger.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs index b927507cf97a..5d6d21bf8008 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ParentPet.cs index a205b59b6d09..c2c91753d7cb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ParentPet.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pet.cs index db3cdd72606d..88c2fb08970f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pet.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pig.cs index d8605861e63a..b1c57219d9f0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pig.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; using System.Reflection; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Quadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Quadrilateral.cs index 17463ca09a4b..028b84f07527 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Quadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Quadrilateral.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; using System.Reflection; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index e7727cf856c9..555fb636825f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index 4ab8f7d5c6a8..99ad2a8307cb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Return.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Return.cs index 75e7f1f25305..18802e2b7f15 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Return.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Return.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index c539590907c7..527bcfab54c5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Shape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Shape.cs index e75e0e8b167f..7186154a9615 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Shape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Shape.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; using System.Reflection; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeInterface.cs index 051100b4e6c1..6d2208e202fc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeOrNull.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeOrNull.cs index 7471bafb3799..eb9191dbc4d2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeOrNull.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeOrNull.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; using System.Reflection; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index 5280a0c308a7..33787f755a71 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SpecialModelName.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SpecialModelName.cs index 26861d98d34d..1023ae9a402d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SpecialModelName.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Tag.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Tag.cs index aba43e338beb..dce80a7cbc36 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Tag.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Tag.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Triangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Triangle.cs index cccaa79a8ff5..ba1fd6d00ec4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Triangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Triangle.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; using System.Reflection; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TriangleInterface.cs index 4b7274465ce0..66f49d7c2dea 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/User.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/User.cs index ea24f093e147..532f743af53f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/User.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/User.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Whale.cs index 80fbf9c368c2..2abe262ebbd4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Whale.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs index cfa92d1b708a..91dce88b9232 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs @@ -21,6 +21,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore/OpenAPIClient/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClient/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient/README.md b/samples/client/petstore/csharp/OpenAPIClient/README.md index f33c01b2a43d..0174c279b8d5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/README.md +++ b/samples/client/petstore/csharp/OpenAPIClient/README.md @@ -114,6 +114,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**FakeOuterNumberSerialize**](docs/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | *FakeApi* | [**FakeOuterStringSerialize**](docs/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | *FakeApi* | [**FakePropertyEnumIntegerSerialize**](docs/FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**TestBodyWithBinary**](docs/FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | *FakeApi* | [**TestBodyWithFileSchema**](docs/FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**TestBodyWithQueryParams**](docs/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**TestClientModel**](docs/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model diff --git a/samples/client/petstore/csharp/OpenAPIClient/docs/FakeApi.md b/samples/client/petstore/csharp/OpenAPIClient/docs/FakeApi.md index 64474672ca8f..b821e3f31c12 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/docs/FakeApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**FakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | [**FakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | [**FakePropertyEnumIntegerSerialize**](FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +[**TestBodyWithBinary**](FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | [**TestBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | [**TestBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model @@ -546,13 +547,87 @@ No authorization required [[Back to README]](../README.md) +## TestBodyWithBinary + +> void TestBodyWithBinary (System.IO.Stream body) + + + +For this test, the body has to be a binary file. + +### Example + +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestBodyWithBinaryExample + { + public static void Main() + { + Configuration.Default.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(Configuration.Default); + var body = BINARY_DATA_HERE; // System.IO.Stream | image to upload + + try + { + apiInstance.TestBodyWithBinary(body); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestBodyWithBinary: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **System.IO.Stream**| image to upload | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: image/png +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + +[[Back to top]](#) +[[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + + ## TestBodyWithFileSchema > void TestBodyWithFileSchema (FileSchemaTestClass fileSchemaTestClass) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs index 6161aa33d32d..f9f9e77ca7e8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs @@ -178,7 +178,28 @@ public interface IFakeApi : IApiAccessor /// /// /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body has to be a binary file. + /// + /// Thrown when fails to make API call + /// image to upload + /// + void TestBodyWithBinary (System.IO.Stream body); + + /// + /// + /// + /// + /// For this test, the body has to be a binary file. + /// + /// Thrown when fails to make API call + /// image to upload + /// ApiResponse of Object(void) + ApiResponse TestBodyWithBinaryWithHttpInfo (System.IO.Stream body); + /// + /// + /// + /// + /// For this test, the body for this request must reference a schema named `File`. /// /// Thrown when fails to make API call /// @@ -189,7 +210,7 @@ public interface IFakeApi : IApiAccessor /// /// /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body for this request must reference a schema named `File`. /// /// Thrown when fails to make API call /// @@ -594,7 +615,30 @@ public interface IFakeApi : IApiAccessor /// /// /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body has to be a binary file. + /// + /// Thrown when fails to make API call + /// image to upload + /// Cancellation Token to cancel request (optional) + /// Task of void + System.Threading.Tasks.Task TestBodyWithBinaryAsync (System.IO.Stream body, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// + /// For this test, the body has to be a binary file. + /// + /// Thrown when fails to make API call + /// image to upload + /// Cancellation Token to cancel request (optional) + /// Task of ApiResponse + System.Threading.Tasks.Task> TestBodyWithBinaryWithHttpInfoAsync (System.IO.Stream body, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// + /// + /// + /// For this test, the body for this request must reference a schema named `File`. /// /// Thrown when fails to make API call /// @@ -606,7 +650,7 @@ public interface IFakeApi : IApiAccessor /// /// /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body for this request must reference a schema named `File`. /// /// Thrown when fails to make API call /// @@ -1988,7 +2032,154 @@ public ApiResponse FakePropertyEnumIntegerSerialize } /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body has to be a binary file. + /// + /// Thrown when fails to make API call + /// image to upload + /// + public void TestBodyWithBinary (System.IO.Stream body) + { + TestBodyWithBinaryWithHttpInfo(body); + } + + /// + /// For this test, the body has to be a binary file. + /// + /// Thrown when fails to make API call + /// image to upload + /// ApiResponse of Object(void) + public ApiResponse TestBodyWithBinaryWithHttpInfo (System.IO.Stream body) + { + // verify the required parameter 'body' is set + if (body == null) + throw new ApiException(400, "Missing required parameter 'body' when calling FakeApi->TestBodyWithBinary"); + + var localVarPath = "/fake/body-with-binary"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + var localVarHeaderParams = new Dictionary(this.Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "image/png" + }; + String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + }; + String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = this.Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) this.Configuration.ApiClient.CallApi(localVarPath, + Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("TestBodyWithBinary", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), + null); + } + + /// + /// For this test, the body has to be a binary file. + /// + /// Thrown when fails to make API call + /// image to upload + /// Cancellation Token to cancel request (optional) + /// Task of void + public async System.Threading.Tasks.Task TestBodyWithBinaryAsync (System.IO.Stream body, CancellationToken cancellationToken = default(CancellationToken)) + { + await TestBodyWithBinaryWithHttpInfoAsync(body, cancellationToken); + + } + + /// + /// For this test, the body has to be a binary file. + /// + /// Thrown when fails to make API call + /// image to upload + /// Cancellation Token to cancel request (optional) + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestBodyWithBinaryWithHttpInfoAsync (System.IO.Stream body, CancellationToken cancellationToken = default(CancellationToken)) + { + // verify the required parameter 'body' is set + if (body == null) + throw new ApiException(400, "Missing required parameter 'body' when calling FakeApi->TestBodyWithBinary"); + + var localVarPath = "/fake/body-with-binary"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + var localVarHeaderParams = new Dictionary(this.Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "image/png" + }; + String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + }; + String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = this.Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) await this.Configuration.ApiClient.CallApiAsync(localVarPath, + Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType, cancellationToken); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("TestBodyWithBinary", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), + null); + } + + /// + /// For this test, the body for this request must reference a schema named `File`. /// /// Thrown when fails to make API call /// @@ -1999,7 +2190,7 @@ public void TestBodyWithFileSchema (FileSchemaTestClass fileSchemaTestClass) } /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body for this request must reference a schema named `File`. /// /// Thrown when fails to make API call /// @@ -2060,7 +2251,7 @@ public ApiResponse TestBodyWithFileSchemaWithHttpInfo (FileSchemaTestCla } /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body for this request must reference a schema named `File`. /// /// Thrown when fails to make API call /// @@ -2073,7 +2264,7 @@ public ApiResponse TestBodyWithFileSchemaWithHttpInfo (FileSchemaTestCla } /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body for this request must reference a schema named `File`. /// /// Thrown when fails to make API call /// @@ -3394,7 +3585,7 @@ public ApiResponse TestQueryParameterCollectionFormatWithHttpInfo (List< if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); - if (pipe != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("multi", "pipe", pipe)); // query parameter + if (pipe != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("pipes", "pipe", pipe)); // query parameter if (ioutil != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("csv", "ioutil", ioutil)); // query parameter if (http != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("ssv", "http", http)); // query parameter if (url != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("csv", "url", url)); // query parameter @@ -3485,7 +3676,7 @@ public ApiResponse TestQueryParameterCollectionFormatWithHttpInfo (List< if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); - if (pipe != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("multi", "pipe", pipe)); // query parameter + if (pipe != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("pipes", "pipe", pipe)); // query parameter if (ioutil != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("csv", "ioutil", ioutil)); // query parameter if (http != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("ssv", "http", http)); // query parameter if (url != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("csv", "url", url)); // query parameter diff --git a/samples/client/petstore/elixir/.openapi-generator/VERSION b/samples/client/petstore/elixir/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/elixir/.openapi-generator/VERSION +++ b/samples/client/petstore/elixir/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/api/fake.ex b/samples/client/petstore/elixir/lib/openapi_petstore/api/fake.ex index 7d05057b3a62..407ff92dbbd2 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/api/fake.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/api/fake.ex @@ -215,7 +215,33 @@ defmodule OpenapiPetstore.Api.Fake do end @doc """ - For this test, the body for this request much reference a schema named `File`. + For this test, the body has to be a binary file. + + ## Parameters + + - connection (OpenapiPetstore.Connection): Connection to server + - body (String.t): image to upload + - opts (KeywordList): [optional] Optional parameters + ## Returns + + {:ok, nil} on success + {:error, Tesla.Env.t} on failure + """ + @spec test_body_with_binary(Tesla.Env.client, String.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} + def test_body_with_binary(connection, body, _opts \\ []) do + %{} + |> method(:put) + |> url("/fake/body-with-binary") + |> add_param(:body, :body, body) + |> Enum.into([]) + |> (&Connection.request(connection, &1)).() + |> evaluate_response([ + { 200, false} + ]) + end + + @doc """ + For this test, the body for this request must reference a schema named `File`. ## Parameters diff --git a/samples/client/petstore/go/go-petstore/.openapi-generator/VERSION b/samples/client/petstore/go/go-petstore/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/go/go-petstore/.openapi-generator/VERSION +++ b/samples/client/petstore/go/go-petstore/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/groovy/.openapi-generator/VERSION b/samples/client/petstore/groovy/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/groovy/.openapi-generator/VERSION +++ b/samples/client/petstore/groovy/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/.openapi-generator/VERSION b/samples/client/petstore/haskell-http-client/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/haskell-http-client/.openapi-generator/VERSION +++ b/samples/client/petstore/haskell-http-client/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/feign-no-nullable/.openapi-generator/VERSION b/samples/client/petstore/java/feign-no-nullable/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/feign-no-nullable/.openapi-generator/VERSION +++ b/samples/client/petstore/java/feign-no-nullable/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/feign/.openapi-generator/VERSION b/samples/client/petstore/java/feign/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/feign/.openapi-generator/VERSION +++ b/samples/client/petstore/java/feign/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/google-api-client/.openapi-generator/VERSION b/samples/client/petstore/java/google-api-client/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/google-api-client/.openapi-generator/VERSION +++ b/samples/client/petstore/java/google-api-client/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/jersey1/.openapi-generator/VERSION b/samples/client/petstore/java/jersey1/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/jersey1/.openapi-generator/VERSION +++ b/samples/client/petstore/java/jersey1/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2-java8-localdatetime/.openapi-generator/VERSION b/samples/client/petstore/java/jersey2-java8-localdatetime/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/jersey2-java8-localdatetime/.openapi-generator/VERSION +++ b/samples/client/petstore/java/jersey2-java8-localdatetime/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2-java8/.openapi-generator/VERSION b/samples/client/petstore/java/jersey2-java8/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/jersey2-java8/.openapi-generator/VERSION +++ b/samples/client/petstore/java/jersey2-java8/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/microprofile-rest-client/.openapi-generator/VERSION b/samples/client/petstore/java/microprofile-rest-client/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/microprofile-rest-client/.openapi-generator/VERSION +++ b/samples/client/petstore/java/microprofile-rest-client/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/native-async/.openapi-generator/VERSION b/samples/client/petstore/java/native-async/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/native-async/.openapi-generator/VERSION +++ b/samples/client/petstore/java/native-async/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/ApiClient.java index 98cdbf0646b1..4b5a1fb4bd34 100644 --- a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/ApiClient.java @@ -175,7 +175,7 @@ public ApiClient() { public ApiClient(HttpClient.Builder builder, ObjectMapper mapper, String baseUri) { this.builder = builder; this.mapper = mapper; - updateBaseUri(baseUri); + updateBaseUri(baseUri != null ? baseUri : getDefaultBaseUri()); interceptor = null; readTimeout = null; responseInterceptor = null; diff --git a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index 38c4a321f657..f2247d141bb1 100644 --- a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -67,6 +67,14 @@ private ApiException getApiException(String operationId, HttpResponseloc localVarResponse.body()); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * To test special tags * To test special tags and operation ID starting with number diff --git a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/FakeApi.java index 415e6a35a40c..388dce55a878 100644 --- a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/FakeApi.java @@ -75,6 +75,14 @@ private ApiException getApiException(String operationId, HttpResponseloc localVarResponse.body()); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * creates an XmlItem * this route creates an XmlItem diff --git a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index a04a5441414a..f8076cd69144 100644 --- a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -67,6 +67,14 @@ private ApiException getApiException(String operationId, HttpResponseloc localVarResponse.body()); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * To test class name in snake case * To test class name in snake case diff --git a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/PetApi.java index 4e9d6f34af79..2dcd304b1f5f 100644 --- a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/PetApi.java @@ -70,6 +70,14 @@ private ApiException getApiException(String operationId, HttpResponseloc localVarResponse.body()); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * Add a new pet to the store * diff --git a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/StoreApi.java index 41de754a4d95..ec19468ccefc 100644 --- a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/StoreApi.java @@ -67,6 +67,14 @@ private ApiException getApiException(String operationId, HttpResponseloc localVarResponse.body()); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors diff --git a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/UserApi.java index bb13d02a2030..ba2cad99cf84 100644 --- a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/UserApi.java @@ -67,6 +67,14 @@ private ApiException getApiException(String operationId, HttpResponseloc localVarResponse.body()); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * Create user * This can only be done by the logged in user. diff --git a/samples/client/petstore/java/native/.openapi-generator/VERSION b/samples/client/petstore/java/native/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/native/.openapi-generator/VERSION +++ b/samples/client/petstore/java/native/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/ApiClient.java index 98cdbf0646b1..4b5a1fb4bd34 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/ApiClient.java @@ -175,7 +175,7 @@ public ApiClient() { public ApiClient(HttpClient.Builder builder, ObjectMapper mapper, String baseUri) { this.builder = builder; this.mapper = mapper; - updateBaseUri(baseUri); + updateBaseUri(baseUri != null ? baseUri : getDefaultBaseUri()); interceptor = null; readTimeout = null; responseInterceptor = null; diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index 9124c1880fc1..2c0088e76d8b 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -58,6 +58,14 @@ public AnotherFakeApi(ApiClient apiClient) { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * To test special tags * To test special tags and operation ID starting with number @@ -87,10 +95,7 @@ public ApiResponse call123testSpecialTagsWithHttpInfo(Client body) throw memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "call123testSpecialTags call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "call123testSpecialTags call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java index c174f057dbe1..6d3b64d83446 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java @@ -66,6 +66,14 @@ public FakeApi(ApiClient apiClient) { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * creates an XmlItem * this route creates an XmlItem @@ -93,10 +101,7 @@ public ApiResponse createXmlItemWithHttpInfo(XmlItem xmlItem) throws ApiEx memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "createXmlItem call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "createXmlItem call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -170,10 +175,7 @@ public ApiResponse fakeOuterBooleanSerializeWithHttpInfo(Boolean body) memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "fakeOuterBooleanSerialize call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "fakeOuterBooleanSerialize call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -243,10 +245,7 @@ public ApiResponse fakeOuterCompositeSerializeWithHttpInfo(Outer memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "fakeOuterCompositeSerialize call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "fakeOuterCompositeSerialize call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -316,10 +315,7 @@ public ApiResponse fakeOuterNumberSerializeWithHttpInfo(BigDecimal b memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "fakeOuterNumberSerialize call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "fakeOuterNumberSerialize call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -389,10 +385,7 @@ public ApiResponse fakeOuterStringSerializeWithHttpInfo(String body) thr memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "fakeOuterStringSerialize call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "fakeOuterStringSerialize call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -460,10 +453,7 @@ public ApiResponse testBodyWithFileSchemaWithHttpInfo(FileSchemaTestClass memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "testBodyWithFileSchema call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "testBodyWithFileSchema call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -537,10 +527,7 @@ public ApiResponse testBodyWithQueryParamsWithHttpInfo(String query, User memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "testBodyWithQueryParams call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "testBodyWithQueryParams call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -627,10 +614,7 @@ public ApiResponse testClientModelWithHttpInfo(Client body) throws ApiEx memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "testClientModel call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "testClientModel call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -728,10 +712,7 @@ public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, D memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "testEndpointParameters call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "testEndpointParameters call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -823,10 +804,7 @@ public ApiResponse testEnumParametersWithHttpInfo(List enumHeaderS memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "testEnumParameters call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "testEnumParameters call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -949,10 +927,7 @@ public ApiResponse testGroupParametersWithHttpInfo(Integer requiredStringG memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "testGroupParameters call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "testGroupParameters call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -1121,10 +1096,7 @@ public ApiResponse testInlineAdditionalPropertiesWithHttpInfo(Map( localVarResponse.statusCode(), @@ -1198,10 +1170,7 @@ public ApiResponse testJsonFormDataWithHttpInfo(String param, String param memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "testJsonFormData call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "testJsonFormData call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -1279,10 +1248,7 @@ public ApiResponse testQueryParameterCollectionFormatWithHttpInfo(List( localVarResponse.statusCode(), diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index bc13e4b5cb72..b16a097a9c36 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -58,6 +58,14 @@ public FakeClassnameTags123Api(ApiClient apiClient) { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * To test class name in snake case * To test class name in snake case @@ -87,10 +95,7 @@ public ApiResponse testClassnameWithHttpInfo(Client body) throws ApiExce memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "testClassname call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "testClassname call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java index 78058c16ada1..ff744b272759 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java @@ -61,6 +61,14 @@ public PetApi(ApiClient apiClient) { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * Add a new pet to the store * @@ -88,10 +96,7 @@ public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "addPet call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "addPet call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -165,10 +170,7 @@ public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "deletePet call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "deletePet call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -240,10 +242,7 @@ public ApiResponse> findPetsByStatusWithHttpInfo(List status) memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "findPetsByStatus call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "findPetsByStatus call received non-success response"); } return new ApiResponse>( localVarResponse.statusCode(), @@ -324,10 +323,7 @@ public ApiResponse> findPetsByTagsWithHttpInfo(Set tags) throws memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "findPetsByTags call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "findPetsByTags call received non-success response"); } return new ApiResponse>( localVarResponse.statusCode(), @@ -404,10 +400,7 @@ public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "getPetById call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "getPetById call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -474,10 +467,7 @@ public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "updatePet call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "updatePet call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -553,10 +543,7 @@ public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "updatePetWithForm call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "updatePetWithForm call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -629,10 +616,7 @@ public ApiResponse uploadFileWithHttpInfo(Long petId, String a memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "uploadFile call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "uploadFile call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -705,10 +689,7 @@ public ApiResponse uploadFileWithRequiredFileWithHttpInfo(Long memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "uploadFileWithRequiredFile call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "uploadFileWithRequiredFile call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java index 845c1567b0c1..caffb9cd6ff0 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java @@ -58,6 +58,14 @@ public StoreApi(ApiClient apiClient) { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -85,10 +93,7 @@ public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiExcep memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "deleteOrder call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "deleteOrder call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -155,10 +160,7 @@ public ApiResponse> getInventoryWithHttpInfo() throws ApiEx memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "getInventory call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "getInventory call received non-success response"); } return new ApiResponse>( localVarResponse.statusCode(), @@ -222,10 +224,7 @@ public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiExcep memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "getOrderById call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "getOrderById call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -294,10 +293,7 @@ public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "placeOrder call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "placeOrder call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java index 6e5b6a147090..e841c2cd1e60 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java @@ -58,6 +58,14 @@ public UserApi(ApiClient apiClient) { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * Create user * This can only be done by the logged in user. @@ -85,10 +93,7 @@ public ApiResponse createUserWithHttpInfo(User body) throws ApiException { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "createUser call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "createUser call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -160,10 +165,7 @@ public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "createUsersWithArrayInput call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "createUsersWithArrayInput call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -235,10 +237,7 @@ public ApiResponse createUsersWithListInputWithHttpInfo(List body) t memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "createUsersWithListInput call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "createUsersWithListInput call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -310,10 +309,7 @@ public ApiResponse deleteUserWithHttpInfo(String username) throws ApiExcep memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "deleteUser call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "deleteUser call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -382,10 +378,7 @@ public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiEx memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "getUserByName call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "getUserByName call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -456,10 +449,7 @@ public ApiResponse loginUserWithHttpInfo(String username, String passwor memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "loginUser call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "loginUser call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -537,10 +527,7 @@ public ApiResponse logoutUserWithHttpInfo() throws ApiException { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "logoutUser call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "logoutUser call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -604,10 +591,7 @@ public ApiResponse updateUserWithHttpInfo(String username, User body) thro memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "updateUser call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "updateUser call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/.openapi-generator/VERSION b/samples/client/petstore/java/okhttp-gson-dynamicOperations/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/.openapi-generator/VERSION +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.gradle b/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.gradle index 915c36674c31..9daaafc56616 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.gradle +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.gradle @@ -36,8 +36,8 @@ if(hasProperty('target') && target == 'android') { targetSdkVersion 25 } compileOptions { - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 } // Rename the aar correctly @@ -82,8 +82,8 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 install { repositories.mavenInstaller { @@ -100,8 +100,8 @@ if(hasProperty('target') && target == 'android') { dependencies { implementation 'io.swagger:swagger-annotations:1.5.24' implementation "com.google.code.findbugs:jsr305:3.0.2" - implementation 'com.squareup.okhttp3:okhttp:3.14.7' - implementation 'com.squareup.okhttp3:logging-interceptor:3.14.7' + implementation 'com.squareup.okhttp3:okhttp:4.9.1' + implementation 'com.squareup.okhttp3:logging-interceptor:4.9.1' implementation 'com.google.code.gson:gson:2.8.6' implementation 'io.gsonfire:gson-fire:1.8.4' implementation group: 'org.apache.oltu.oauth2', name: 'org.apache.oltu.oauth2.client', version: '1.0.1' diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.sbt b/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.sbt index 289532fdd680..020460f4527d 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.sbt +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.sbt @@ -10,8 +10,8 @@ lazy val root = (project in file(".")). resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( "io.swagger" % "swagger-annotations" % "1.5.24", - "com.squareup.okhttp3" % "okhttp" % "3.14.7", - "com.squareup.okhttp3" % "logging-interceptor" % "3.14.7", + "com.squareup.okhttp3" % "okhttp" % "4.9.1", + "com.squareup.okhttp3" % "logging-interceptor" % "4.9.1", "com.google.code.gson" % "gson" % "2.8.6", "org.apache.commons" % "commons-lang3" % "3.10", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1", diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/.openapi-generator/VERSION b/samples/client/petstore/java/okhttp-gson-parcelableModel/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/.openapi-generator/VERSION +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/build.gradle b/samples/client/petstore/java/okhttp-gson-parcelableModel/build.gradle index 615ed108d405..5809e790fce1 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/build.gradle +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/build.gradle @@ -36,8 +36,8 @@ if(hasProperty('target') && target == 'android') { targetSdkVersion 25 } compileOptions { - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 } // Rename the aar correctly @@ -82,8 +82,8 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 install { repositories.mavenInstaller { @@ -100,8 +100,8 @@ if(hasProperty('target') && target == 'android') { dependencies { implementation 'io.swagger:swagger-annotations:1.5.24' implementation "com.google.code.findbugs:jsr305:3.0.2" - implementation 'com.squareup.okhttp3:okhttp:3.14.7' - implementation 'com.squareup.okhttp3:logging-interceptor:3.14.7' + implementation 'com.squareup.okhttp3:okhttp:4.9.1' + implementation 'com.squareup.okhttp3:logging-interceptor:4.9.1' implementation 'com.google.code.gson:gson:2.8.6' implementation 'io.gsonfire:gson-fire:1.8.4' implementation group: 'org.apache.oltu.oauth2', name: 'org.apache.oltu.oauth2.client', version: '1.0.1' diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/build.sbt b/samples/client/petstore/java/okhttp-gson-parcelableModel/build.sbt index d3bf50f4d7f6..c36bbc5ca081 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/build.sbt +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/build.sbt @@ -10,8 +10,8 @@ lazy val root = (project in file(".")). resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( "io.swagger" % "swagger-annotations" % "1.5.24", - "com.squareup.okhttp3" % "okhttp" % "3.14.7", - "com.squareup.okhttp3" % "logging-interceptor" % "3.14.7", + "com.squareup.okhttp3" % "okhttp" % "4.9.1", + "com.squareup.okhttp3" % "logging-interceptor" % "4.9.1", "com.google.code.gson" % "gson" % "2.8.6", "org.apache.commons" % "commons-lang3" % "3.10", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1", diff --git a/samples/client/petstore/java/okhttp-gson/.openapi-generator/VERSION b/samples/client/petstore/java/okhttp-gson/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/okhttp-gson/.openapi-generator/VERSION +++ b/samples/client/petstore/java/okhttp-gson/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/build.gradle b/samples/client/petstore/java/okhttp-gson/build.gradle index 08cb8effd2d1..3488028c4669 100644 --- a/samples/client/petstore/java/okhttp-gson/build.gradle +++ b/samples/client/petstore/java/okhttp-gson/build.gradle @@ -36,8 +36,8 @@ if(hasProperty('target') && target == 'android') { targetSdkVersion 25 } compileOptions { - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 } // Rename the aar correctly @@ -82,8 +82,8 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 install { repositories.mavenInstaller { @@ -100,8 +100,8 @@ if(hasProperty('target') && target == 'android') { dependencies { implementation 'io.swagger:swagger-annotations:1.5.24' implementation "com.google.code.findbugs:jsr305:3.0.2" - implementation 'com.squareup.okhttp3:okhttp:3.14.7' - implementation 'com.squareup.okhttp3:logging-interceptor:3.14.7' + implementation 'com.squareup.okhttp3:okhttp:4.9.1' + implementation 'com.squareup.okhttp3:logging-interceptor:4.9.1' implementation 'com.google.code.gson:gson:2.8.6' implementation 'io.gsonfire:gson-fire:1.8.4' implementation group: 'org.apache.oltu.oauth2', name: 'org.apache.oltu.oauth2.client', version: '1.0.1' diff --git a/samples/client/petstore/java/okhttp-gson/build.sbt b/samples/client/petstore/java/okhttp-gson/build.sbt index ae1791028e0f..6dfd0d7f733b 100644 --- a/samples/client/petstore/java/okhttp-gson/build.sbt +++ b/samples/client/petstore/java/okhttp-gson/build.sbt @@ -10,8 +10,8 @@ lazy val root = (project in file(".")). resolvers += Resolver.mavenLocal, libraryDependencies ++= Seq( "io.swagger" % "swagger-annotations" % "1.5.24", - "com.squareup.okhttp3" % "okhttp" % "3.14.7", - "com.squareup.okhttp3" % "logging-interceptor" % "3.14.7", + "com.squareup.okhttp3" % "okhttp" % "4.9.1", + "com.squareup.okhttp3" % "logging-interceptor" % "4.9.1", "com.google.code.gson" % "gson" % "2.8.6", "org.apache.commons" % "commons-lang3" % "3.10", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1", diff --git a/samples/client/petstore/java/rest-assured-jackson/.openapi-generator/VERSION b/samples/client/petstore/java/rest-assured-jackson/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/rest-assured-jackson/.openapi-generator/VERSION +++ b/samples/client/petstore/java/rest-assured-jackson/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/rest-assured/.openapi-generator/VERSION b/samples/client/petstore/java/rest-assured/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/rest-assured/.openapi-generator/VERSION +++ b/samples/client/petstore/java/rest-assured/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/resteasy/.openapi-generator/VERSION b/samples/client/petstore/java/resteasy/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/resteasy/.openapi-generator/VERSION +++ b/samples/client/petstore/java/resteasy/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/resttemplate-withXml/.openapi-generator/VERSION b/samples/client/petstore/java/resttemplate-withXml/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/resttemplate-withXml/.openapi-generator/VERSION +++ b/samples/client/petstore/java/resttemplate-withXml/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/ApiClient.java index 11da16b2e48d..ae98ba62fdcd 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/ApiClient.java @@ -36,6 +36,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.openapitools.jackson.nullable.JsonNullableModule; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index 6cd06d48e579..dee726fce33a 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -89,11 +89,11 @@ public ResponseEntity call123testSpecialTagsWithHttpInfo(Client body) th final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/FakeApi.java index a4388e7f41d6..045664b3bbbf 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/FakeApi.java @@ -94,12 +94,12 @@ public ResponseEntity createXmlItemWithHttpInfo(XmlItem xmlItem) throws Re final String[] contentTypes = { "application/xml", "application/xml; charset=utf-8", "application/xml; charset=utf-16", "text/xml", "text/xml; charset=utf-8", "text/xml; charset=utf-16" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -136,12 +136,12 @@ public ResponseEntity fakeOuterBooleanSerializeWithHttpInfo(Boolean bod }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -178,12 +178,12 @@ public ResponseEntity fakeOuterCompositeSerializeWithHttpInfo(Ou }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -220,12 +220,12 @@ public ResponseEntity fakeOuterNumberSerializeWithHttpInfo(BigDecima }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -262,12 +262,12 @@ public ResponseEntity fakeOuterStringSerializeWithHttpInfo(String body) }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -308,12 +308,12 @@ public ResponseEntity testBodyWithFileSchemaWithHttpInfo(FileSchemaTestCla final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -363,12 +363,12 @@ public ResponseEntity testBodyWithQueryParamsWithHttpInfo(String query, Us final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * To test \"client\" model @@ -412,12 +412,12 @@ public ResponseEntity testClientModelWithHttpInfo(Client body) throws Re final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -530,12 +530,12 @@ public ResponseEntity testEndpointParametersWithHttpInfo(BigDecimal number final String[] contentTypes = { "application/x-www-form-urlencoded" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "http_basic_test" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * To test enum parameters @@ -602,12 +602,12 @@ public ResponseEntity testEnumParametersWithHttpInfo(List enumHead final String[] contentTypes = { "application/x-www-form-urlencoded" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Fake endpoint to test group parameters (optional) @@ -676,12 +676,12 @@ public ResponseEntity testGroupParametersWithHttpInfo(Integer requiredStri final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * test inline additionalProperties @@ -722,12 +722,12 @@ public ResponseEntity testInlineAdditionalPropertiesWithHttpInfo(Map returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * test json serialization of form data @@ -780,12 +780,12 @@ public ResponseEntity testJsonFormDataWithHttpInfo(String param, String pa final String[] contentTypes = { "application/x-www-form-urlencoded" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -858,11 +858,11 @@ public ResponseEntity testQueryParameterCollectionFormatWithHttpInfo(List< final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index 1aaa79e9b97c..26ad7b235468 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -89,11 +89,11 @@ public ResponseEntity testClassnameWithHttpInfo(Client body) throws Rest final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "api_key_query" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/PetApi.java index 6e44289f45e0..b5ff30e3cf28 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/PetApi.java @@ -91,12 +91,12 @@ public ResponseEntity addPetWithHttpInfo(Pet body) throws RestClientExcept final String[] contentTypes = { "application/json", "application/xml" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Deletes a pet @@ -145,12 +145,12 @@ public ResponseEntity deletePetWithHttpInfo(Long petId, String apiKey) thr final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Finds Pets by status @@ -196,12 +196,12 @@ public ResponseEntity> findPetsByStatusWithHttpInfo(List statu }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Finds Pets by tags @@ -249,12 +249,12 @@ public ResponseEntity> findPetsByTagsWithHttpInfo(Set tags) thr }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Find pet by ID @@ -303,12 +303,12 @@ public ResponseEntity getPetByIdWithHttpInfo(Long petId) throws RestClientE }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "api_key" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Update an existing pet @@ -355,12 +355,12 @@ public ResponseEntity updatePetWithHttpInfo(Pet body) throws RestClientExc final String[] contentTypes = { "application/json", "application/xml" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Updates a pet in the store with form data @@ -413,12 +413,12 @@ public ResponseEntity updatePetWithFormWithHttpInfo(Long petId, String nam final String[] contentTypes = { "application/x-www-form-urlencoded" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * uploads an image @@ -474,12 +474,12 @@ public ResponseEntity uploadFileWithHttpInfo(Long petId, Strin final String[] contentTypes = { "multipart/form-data" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * uploads an image (required) @@ -540,11 +540,11 @@ public ResponseEntity uploadFileWithRequiredFileWithHttpInfo(L final String[] contentTypes = { "multipart/form-data" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/StoreApi.java index 1f1cbc751efe..63aa265f38e4 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/StoreApi.java @@ -89,12 +89,12 @@ public ResponseEntity deleteOrderWithHttpInfo(String orderId) throws RestC final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Returns pet inventories by status @@ -129,12 +129,12 @@ public ResponseEntity> getInventoryWithHttpInfo() throws Re }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "api_key" }; ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Find purchase order by ID @@ -183,12 +183,12 @@ public ResponseEntity getOrderByIdWithHttpInfo(Long orderId) throws RestC }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Place an order for a pet @@ -232,11 +232,11 @@ public ResponseEntity placeOrderWithHttpInfo(Order body) throws RestClien }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/UserApi.java index 35f6e6609633..46be8cbbd613 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/UserApi.java @@ -84,12 +84,12 @@ public ResponseEntity createUserWithHttpInfo(User body) throws RestClientE final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Creates list of users with given input array @@ -128,12 +128,12 @@ public ResponseEntity createUsersWithArrayInputWithHttpInfo(List bod final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Creates list of users with given input array @@ -172,12 +172,12 @@ public ResponseEntity createUsersWithListInputWithHttpInfo(List body final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Delete user @@ -221,12 +221,12 @@ public ResponseEntity deleteUserWithHttpInfo(String username) throws RestC final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Get user by user name @@ -275,12 +275,12 @@ public ResponseEntity getUserByNameWithHttpInfo(String username) throws Re }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Logs user into the system @@ -334,12 +334,12 @@ public ResponseEntity loginUserWithHttpInfo(String username, String pass }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Logs out current logged in user session @@ -371,12 +371,12 @@ public ResponseEntity logoutUserWithHttpInfo() throws RestClientException final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Updated user @@ -427,11 +427,11 @@ public ResponseEntity updateUserWithHttpInfo(String username, User body) t final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/resttemplate/.openapi-generator/VERSION b/samples/client/petstore/java/resttemplate/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/resttemplate/.openapi-generator/VERSION +++ b/samples/client/petstore/java/resttemplate/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java index 11c1b8349355..ff33cd2248ff 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java @@ -31,6 +31,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.openapitools.jackson.nullable.JsonNullableModule; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index 6cd06d48e579..dee726fce33a 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -89,11 +89,11 @@ public ResponseEntity call123testSpecialTagsWithHttpInfo(Client body) th final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/FakeApi.java index a4388e7f41d6..045664b3bbbf 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/FakeApi.java @@ -94,12 +94,12 @@ public ResponseEntity createXmlItemWithHttpInfo(XmlItem xmlItem) throws Re final String[] contentTypes = { "application/xml", "application/xml; charset=utf-8", "application/xml; charset=utf-16", "text/xml", "text/xml; charset=utf-8", "text/xml; charset=utf-16" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -136,12 +136,12 @@ public ResponseEntity fakeOuterBooleanSerializeWithHttpInfo(Boolean bod }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -178,12 +178,12 @@ public ResponseEntity fakeOuterCompositeSerializeWithHttpInfo(Ou }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -220,12 +220,12 @@ public ResponseEntity fakeOuterNumberSerializeWithHttpInfo(BigDecima }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -262,12 +262,12 @@ public ResponseEntity fakeOuterStringSerializeWithHttpInfo(String body) }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -308,12 +308,12 @@ public ResponseEntity testBodyWithFileSchemaWithHttpInfo(FileSchemaTestCla final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -363,12 +363,12 @@ public ResponseEntity testBodyWithQueryParamsWithHttpInfo(String query, Us final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * To test \"client\" model @@ -412,12 +412,12 @@ public ResponseEntity testClientModelWithHttpInfo(Client body) throws Re final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -530,12 +530,12 @@ public ResponseEntity testEndpointParametersWithHttpInfo(BigDecimal number final String[] contentTypes = { "application/x-www-form-urlencoded" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "http_basic_test" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * To test enum parameters @@ -602,12 +602,12 @@ public ResponseEntity testEnumParametersWithHttpInfo(List enumHead final String[] contentTypes = { "application/x-www-form-urlencoded" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Fake endpoint to test group parameters (optional) @@ -676,12 +676,12 @@ public ResponseEntity testGroupParametersWithHttpInfo(Integer requiredStri final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * test inline additionalProperties @@ -722,12 +722,12 @@ public ResponseEntity testInlineAdditionalPropertiesWithHttpInfo(Map returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * test json serialization of form data @@ -780,12 +780,12 @@ public ResponseEntity testJsonFormDataWithHttpInfo(String param, String pa final String[] contentTypes = { "application/x-www-form-urlencoded" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -858,11 +858,11 @@ public ResponseEntity testQueryParameterCollectionFormatWithHttpInfo(List< final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index 1aaa79e9b97c..26ad7b235468 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -89,11 +89,11 @@ public ResponseEntity testClassnameWithHttpInfo(Client body) throws Rest final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "api_key_query" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/PetApi.java index 6e44289f45e0..b5ff30e3cf28 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/PetApi.java @@ -91,12 +91,12 @@ public ResponseEntity addPetWithHttpInfo(Pet body) throws RestClientExcept final String[] contentTypes = { "application/json", "application/xml" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Deletes a pet @@ -145,12 +145,12 @@ public ResponseEntity deletePetWithHttpInfo(Long petId, String apiKey) thr final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Finds Pets by status @@ -196,12 +196,12 @@ public ResponseEntity> findPetsByStatusWithHttpInfo(List statu }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Finds Pets by tags @@ -249,12 +249,12 @@ public ResponseEntity> findPetsByTagsWithHttpInfo(Set tags) thr }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Find pet by ID @@ -303,12 +303,12 @@ public ResponseEntity getPetByIdWithHttpInfo(Long petId) throws RestClientE }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "api_key" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Update an existing pet @@ -355,12 +355,12 @@ public ResponseEntity updatePetWithHttpInfo(Pet body) throws RestClientExc final String[] contentTypes = { "application/json", "application/xml" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Updates a pet in the store with form data @@ -413,12 +413,12 @@ public ResponseEntity updatePetWithFormWithHttpInfo(Long petId, String nam final String[] contentTypes = { "application/x-www-form-urlencoded" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * uploads an image @@ -474,12 +474,12 @@ public ResponseEntity uploadFileWithHttpInfo(Long petId, Strin final String[] contentTypes = { "multipart/form-data" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * uploads an image (required) @@ -540,11 +540,11 @@ public ResponseEntity uploadFileWithRequiredFileWithHttpInfo(L final String[] contentTypes = { "multipart/form-data" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/StoreApi.java index 1f1cbc751efe..63aa265f38e4 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/StoreApi.java @@ -89,12 +89,12 @@ public ResponseEntity deleteOrderWithHttpInfo(String orderId) throws RestC final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Returns pet inventories by status @@ -129,12 +129,12 @@ public ResponseEntity> getInventoryWithHttpInfo() throws Re }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "api_key" }; ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Find purchase order by ID @@ -183,12 +183,12 @@ public ResponseEntity getOrderByIdWithHttpInfo(Long orderId) throws RestC }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Place an order for a pet @@ -232,11 +232,11 @@ public ResponseEntity placeOrderWithHttpInfo(Order body) throws RestClien }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/UserApi.java index 35f6e6609633..46be8cbbd613 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/UserApi.java @@ -84,12 +84,12 @@ public ResponseEntity createUserWithHttpInfo(User body) throws RestClientE final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Creates list of users with given input array @@ -128,12 +128,12 @@ public ResponseEntity createUsersWithArrayInputWithHttpInfo(List bod final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Creates list of users with given input array @@ -172,12 +172,12 @@ public ResponseEntity createUsersWithListInputWithHttpInfo(List body final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Delete user @@ -221,12 +221,12 @@ public ResponseEntity deleteUserWithHttpInfo(String username) throws RestC final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Get user by user name @@ -275,12 +275,12 @@ public ResponseEntity getUserByNameWithHttpInfo(String username) throws Re }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Logs user into the system @@ -334,12 +334,12 @@ public ResponseEntity loginUserWithHttpInfo(String username, String pass }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Logs out current logged in user session @@ -371,12 +371,12 @@ public ResponseEntity logoutUserWithHttpInfo() throws RestClientException final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Updated user @@ -427,11 +427,11 @@ public ResponseEntity updateUserWithHttpInfo(String username, User body) t final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/retrofit2-play26/.openapi-generator/VERSION b/samples/client/petstore/java/retrofit2-play26/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/retrofit2-play26/.openapi-generator/VERSION +++ b/samples/client/petstore/java/retrofit2-play26/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2/.openapi-generator/VERSION b/samples/client/petstore/java/retrofit2/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/retrofit2/.openapi-generator/VERSION +++ b/samples/client/petstore/java/retrofit2/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx2/.openapi-generator/VERSION b/samples/client/petstore/java/retrofit2rx2/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/retrofit2rx2/.openapi-generator/VERSION +++ b/samples/client/petstore/java/retrofit2rx2/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx3/.openapi-generator/VERSION b/samples/client/petstore/java/retrofit2rx3/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/retrofit2rx3/.openapi-generator/VERSION +++ b/samples/client/petstore/java/retrofit2rx3/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/vertx-no-nullable/.openapi-generator/VERSION b/samples/client/petstore/java/vertx-no-nullable/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/vertx-no-nullable/.openapi-generator/VERSION +++ b/samples/client/petstore/java/vertx-no-nullable/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/vertx/.openapi-generator/VERSION b/samples/client/petstore/java/vertx/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/vertx/.openapi-generator/VERSION +++ b/samples/client/petstore/java/vertx/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/webclient/.openapi-generator/VERSION b/samples/client/petstore/java/webclient/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/java/webclient/.openapi-generator/VERSION +++ b/samples/client/petstore/java/webclient/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/ApiClient.java index c8b45d5a9038..b8a53e2f9470 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/ApiClient.java @@ -57,6 +57,9 @@ import java.util.Map; import java.util.Map.Entry; import java.util.TimeZone; + +import javax.annotation.Nullable; + import java.time.OffsetDateTime; import org.openapitools.client.auth.Authentication; @@ -87,43 +90,56 @@ private String collectionToString(Collection collection) { private final WebClient webClient; private final DateFormat dateFormat; + private final ObjectMapper objectMapper; private Map authentications; public ApiClient() { this.dateFormat = createDefaultDateFormat(); - ObjectMapper mapper = new ObjectMapper(); - mapper.setDateFormat(dateFormat); - mapper.registerModule(new JavaTimeModule()); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNullableModule jnm = new JsonNullableModule(); - mapper.registerModule(jnm); - - this.webClient = buildWebClient(mapper); + this.objectMapper = createDefaultObjectMapper(this.dateFormat); + this.webClient = buildWebClient(this.objectMapper); this.init(); } + public ApiClient(WebClient webClient) { + this(Optional.ofNullable(webClient).orElseGet(() -> buildWebClient()), createDefaultDateFormat()); + } + public ApiClient(ObjectMapper mapper, DateFormat format) { this(buildWebClient(mapper.copy()), format); } public ApiClient(WebClient webClient, ObjectMapper mapper, DateFormat format) { - this(Optional.ofNullable(webClient).orElseGet(() ->buildWebClient(mapper.copy())), format); + this(Optional.ofNullable(webClient).orElseGet(() -> buildWebClient(mapper.copy())), format); } private ApiClient(WebClient webClient, DateFormat format) { this.webClient = webClient; this.dateFormat = format; + this.objectMapper = createDefaultObjectMapper(format); this.init(); } - public DateFormat createDefaultDateFormat() { + public static DateFormat createDefaultDateFormat() { DateFormat dateFormat = new RFC3339DateFormat(); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return dateFormat; } + public static ObjectMapper createDefaultObjectMapper(@Nullable DateFormat dateFormat) { + if (null == dateFormat) { + dateFormat = createDefaultDateFormat(); + } + ObjectMapper mapper = new ObjectMapper(); + mapper.setDateFormat(dateFormat); + mapper.registerModule(new JavaTimeModule()); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNullableModule jnm = new JsonNullableModule(); + mapper.registerModule(jnm); + return mapper; + } + protected void init() { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); @@ -136,20 +152,45 @@ protected void init() { } /** - * Build the WebClient used to make HTTP requests. + * Build the WebClientBuilder used to make WebClient. + * @param mapper ObjectMapper used for serialize/deserialize * @return WebClient */ - public static WebClient buildWebClient(ObjectMapper mapper) { + public static WebClient.Builder buildWebClientBuilder(ObjectMapper mapper) { ExchangeStrategies strategies = ExchangeStrategies .builder() .codecs(clientDefaultCodecsConfigurer -> { clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(mapper, MediaType.APPLICATION_JSON)); clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(mapper, MediaType.APPLICATION_JSON)); }).build(); - WebClient.Builder webClient = WebClient.builder().exchangeStrategies(strategies); - return webClient.build(); + WebClient.Builder webClientBuilder = WebClient.builder().exchangeStrategies(strategies); + return webClientBuilder; + } + + /** + * Build the WebClientBuilder used to make WebClient. + * @return WebClient + */ + public static WebClient.Builder buildWebClientBuilder() { + return buildWebClientBuilder(createDefaultObjectMapper(null)); } + /** + * Build the WebClient used to make HTTP requests. + * @param mapper ObjectMapper used for serialize/deserialize + * @return WebClient + */ + public static WebClient buildWebClient(ObjectMapper mapper) { + return buildWebClientBuilder(mapper).build(); + } + + /** + * Build the WebClient used to make HTTP requests. + * @return WebClient + */ + public static WebClient buildWebClient() { + return buildWebClientBuilder(createDefaultObjectMapper(null)).build(); + } /** * Get the current base path @@ -337,6 +378,22 @@ public String formatDate(Date date) { return dateFormat.format(date); } + /** + * Get the ObjectMapper used to make HTTP requests. + * @return ObjectMapper objectMapper + */ + public ObjectMapper getObjectMapper() { + return objectMapper; + } + + /** + * Get the WebClient used to make HTTP requests. + * @return WebClient webClient + */ + public WebClient getWebClient() { + return webClient; + } + /** * Format the given parameter object into string. * @param param the object to convert @@ -640,10 +697,10 @@ public String collectionPathParameterToString(CollectionFormat collectionFormat, } // collectionFormat is assumed to be "csv" by default - if(collectionFormat == null) { - collectionFormat = CollectionFormat.CSV; - } + if(collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } - return collectionFormat.collectionToString(values); + return collectionFormat.collectionToString(values); } } diff --git a/samples/client/petstore/javascript-es6/.openapi-generator/VERSION b/samples/client/petstore/javascript-es6/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/javascript-es6/.openapi-generator/VERSION +++ b/samples/client/petstore/javascript-es6/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/javascript-es6/README.md b/samples/client/petstore/javascript-es6/README.md index 7484625b457e..736594bda699 100644 --- a/samples/client/petstore/javascript-es6/README.md +++ b/samples/client/petstore/javascript-es6/README.md @@ -129,6 +129,7 @@ Class | Method | HTTP request | Description *OpenApiPetstore.FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | *OpenApiPetstore.FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | *OpenApiPetstore.FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +*OpenApiPetstore.FakeApi* | [**testBodyWithBinary**](docs/FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | *OpenApiPetstore.FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *OpenApiPetstore.FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | *OpenApiPetstore.FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model diff --git a/samples/client/petstore/javascript-es6/docs/FakeApi.md b/samples/client/petstore/javascript-es6/docs/FakeApi.md index 95446d77d5e0..9ba9d28131bb 100644 --- a/samples/client/petstore/javascript-es6/docs/FakeApi.md +++ b/samples/client/petstore/javascript-es6/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +[**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model @@ -345,13 +346,58 @@ No authorization required - **Accept**: */* +## testBodyWithBinary + +> testBodyWithBinary(body) + + + +For this test, the body has to be a binary file. + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let body = "/path/to/file"; // File | image to upload +apiInstance.testBodyWithBinary(body, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **File**| image to upload | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: image/png +- **Accept**: Not defined + + ## testBodyWithFileSchema > testBodyWithFileSchema(fileSchemaTestClass) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example diff --git a/samples/client/petstore/javascript-es6/src/api/FakeApi.js b/samples/client/petstore/javascript-es6/src/api/FakeApi.js index 33f85635f091..3b9e1509ceff 100644 --- a/samples/client/petstore/javascript-es6/src/api/FakeApi.js +++ b/samples/client/petstore/javascript-es6/src/api/FakeApi.js @@ -319,6 +319,46 @@ export default class FakeApi { ); } + /** + * Callback function to receive the result of the testBodyWithBinary operation. + * @callback module:api/FakeApi~testBodyWithBinaryCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. + */ + + /** + * For this test, the body has to be a binary file. + * @param {File} body image to upload + * @param {module:api/FakeApi~testBodyWithBinaryCallback} callback The callback function, accepting three arguments: error, data, response + */ + testBodyWithBinary(body, callback) { + let postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling testBodyWithBinary"); + } + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['image/png']; + let accepts = []; + let returnType = null; + return this.apiClient.callApi( + '/fake/body-with-binary', 'PUT', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, null, callback + ); + } + /** * Callback function to receive the result of the testBodyWithFileSchema operation. * @callback module:api/FakeApi~testBodyWithFileSchemaCallback @@ -328,7 +368,7 @@ export default class FakeApi { */ /** - * For this test, the body for this request much reference a schema named `File`. + * For this test, the body for this request must reference a schema named `File`. * @param {module:model/FileSchemaTestClass} fileSchemaTestClass * @param {module:api/FakeApi~testBodyWithFileSchemaCallback} callback The callback function, accepting three arguments: error, data, response */ @@ -774,7 +814,7 @@ export default class FakeApi { let pathParams = { }; let queryParams = { - 'pipe': this.apiClient.buildCollectionParam(pipe, 'multi'), + 'pipe': this.apiClient.buildCollectionParam(pipe, 'pipes'), 'ioutil': this.apiClient.buildCollectionParam(ioutil, 'csv'), 'http': this.apiClient.buildCollectionParam(http, 'ssv'), 'url': this.apiClient.buildCollectionParam(url, 'csv'), diff --git a/samples/client/petstore/javascript-flowtyped/.openapi-generator/VERSION b/samples/client/petstore/javascript-flowtyped/.openapi-generator/VERSION index d99e7162d01f..6555596f9311 100644 --- a/samples/client/petstore/javascript-flowtyped/.openapi-generator/VERSION +++ b/samples/client/petstore/javascript-flowtyped/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/javascript-flowtyped/src/api.js b/samples/client/petstore/javascript-flowtyped/src/api.js index 7e681e862c77..bcf2a932d3bc 100644 --- a/samples/client/petstore/javascript-flowtyped/src/api.js +++ b/samples/client/petstore/javascript-flowtyped/src/api.js @@ -46,7 +46,6 @@ export type FetchArgs = { options: {}; } - /** * * @export @@ -310,9 +309,9 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const localVarAccessTokenValue = typeof configuration.accessToken === 'function' - ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) - : configuration.accessToken; + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } @@ -350,9 +349,9 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const localVarAccessTokenValue = typeof configuration.accessToken === 'function' - ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) - : configuration.accessToken; + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } @@ -389,9 +388,9 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const localVarAccessTokenValue = typeof configuration.accessToken === 'function' - ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) - : configuration.accessToken; + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } @@ -428,9 +427,9 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const localVarAccessTokenValue = typeof configuration.accessToken === 'function' - ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) - : configuration.accessToken; + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } @@ -468,8 +467,8 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) // authentication api_key required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("api_key") - : configuration.apiKey; + ? configuration.apiKey("api_key") + : configuration.apiKey; localVarHeaderParameter["api_key"] = localVarApiKeyValue; } @@ -502,9 +501,9 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const localVarAccessTokenValue = typeof configuration.accessToken === 'function' - ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) - : configuration.accessToken; + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } @@ -543,9 +542,9 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const localVarAccessTokenValue = typeof configuration.accessToken === 'function' - ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) - : configuration.accessToken; + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } @@ -589,9 +588,9 @@ export const PetApiFetchParamCreator = function (configuration?: Configuration) // authentication petstore_auth required // oauth required if (configuration && configuration.accessToken) { - const localVarAccessTokenValue = typeof configuration.accessToken === 'function' - ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) - : configuration.accessToken; + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]) + : configuration.accessToken; localVarHeaderParameter["Authorization"] = "Bearer " + localVarAccessTokenValue; } @@ -765,6 +764,7 @@ export const PetApi = function(configuration?: Configuration, fetch: FetchAPI = } }; + /** * StoreApi - fetch parameter creator * @export @@ -813,8 +813,8 @@ export const StoreApiFetchParamCreator = function (configuration?: Configuration // authentication api_key required if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === 'function' - ? configuration.apiKey("api_key") - : configuration.apiKey; + ? configuration.apiKey("api_key") + : configuration.apiKey; localVarHeaderParameter["api_key"] = localVarApiKeyValue; } @@ -968,6 +968,7 @@ export const StoreApi = function(configuration?: Configuration, fetch: FetchAPI } }; + /** * UserApi - fetch parameter creator * @export @@ -1364,6 +1365,7 @@ export const UserApi = function(configuration?: Configuration, fetch: FetchAPI = } }; + export type ApiTypes = { PetApi: PetApiType, diff --git a/samples/client/petstore/javascript-promise-es6/.openapi-generator/VERSION b/samples/client/petstore/javascript-promise-es6/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/javascript-promise-es6/.openapi-generator/VERSION +++ b/samples/client/petstore/javascript-promise-es6/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/javascript-promise-es6/README.md b/samples/client/petstore/javascript-promise-es6/README.md index ef092423575e..b13f89f2daca 100644 --- a/samples/client/petstore/javascript-promise-es6/README.md +++ b/samples/client/petstore/javascript-promise-es6/README.md @@ -127,6 +127,7 @@ Class | Method | HTTP request | Description *OpenApiPetstore.FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | *OpenApiPetstore.FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | *OpenApiPetstore.FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +*OpenApiPetstore.FakeApi* | [**testBodyWithBinary**](docs/FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | *OpenApiPetstore.FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *OpenApiPetstore.FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | *OpenApiPetstore.FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model diff --git a/samples/client/petstore/javascript-promise-es6/docs/FakeApi.md b/samples/client/petstore/javascript-promise-es6/docs/FakeApi.md index b6c5594e0ba1..a0cd0aefb424 100644 --- a/samples/client/petstore/javascript-promise-es6/docs/FakeApi.md +++ b/samples/client/petstore/javascript-promise-es6/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +[**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model @@ -338,13 +339,57 @@ No authorization required - **Accept**: */* +## testBodyWithBinary + +> testBodyWithBinary(body) + + + +For this test, the body has to be a binary file. + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let body = "/path/to/file"; // File | image to upload +apiInstance.testBodyWithBinary(body).then(() => { + console.log('API called successfully.'); +}, (error) => { + console.error(error); +}); + +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **File**| image to upload | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: image/png +- **Accept**: Not defined + + ## testBodyWithFileSchema > testBodyWithFileSchema(fileSchemaTestClass) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example diff --git a/samples/client/petstore/javascript-promise-es6/src/api/FakeApi.js b/samples/client/petstore/javascript-promise-es6/src/api/FakeApi.js index 0902c816dc4b..e635c42692ce 100644 --- a/samples/client/petstore/javascript-promise-es6/src/api/FakeApi.js +++ b/samples/client/petstore/javascript-promise-es6/src/api/FakeApi.js @@ -356,7 +356,52 @@ export default class FakeApi { /** - * For this test, the body for this request much reference a schema named `File`. + * For this test, the body has to be a binary file. + * @param {File} body image to upload + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing HTTP response + */ + testBodyWithBinaryWithHttpInfo(body) { + let postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling testBodyWithBinary"); + } + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['image/png']; + let accepts = []; + let returnType = null; + return this.apiClient.callApi( + '/fake/body-with-binary', 'PUT', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, null + ); + } + + /** + * For this test, the body has to be a binary file. + * @param {File} body image to upload + * @return {Promise} a {@link https://www.promisejs.org/|Promise} + */ + testBodyWithBinary(body) { + return this.testBodyWithBinaryWithHttpInfo(body) + .then(function(response_and_data) { + return response_and_data.data; + }); + } + + + /** + * For this test, the body for this request must reference a schema named `File`. * @param {module:model/FileSchemaTestClass} fileSchemaTestClass * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing HTTP response */ @@ -388,7 +433,7 @@ export default class FakeApi { } /** - * For this test, the body for this request much reference a schema named `File`. + * For this test, the body for this request must reference a schema named `File`. * @param {module:model/FileSchemaTestClass} fileSchemaTestClass * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ @@ -874,7 +919,7 @@ export default class FakeApi { let pathParams = { }; let queryParams = { - 'pipe': this.apiClient.buildCollectionParam(pipe, 'multi'), + 'pipe': this.apiClient.buildCollectionParam(pipe, 'pipes'), 'ioutil': this.apiClient.buildCollectionParam(ioutil, 'csv'), 'http': this.apiClient.buildCollectionParam(http, 'ssv'), 'url': this.apiClient.buildCollectionParam(url, 'csv'), diff --git a/samples/client/petstore/kotlin-gson/.openapi-generator/FILES b/samples/client/petstore/kotlin-gson/.openapi-generator/FILES index bf441309074d..1f38d3fbe2d3 100644 --- a/samples/client/petstore/kotlin-gson/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-gson/.openapi-generator/FILES @@ -20,7 +20,6 @@ src/main/kotlin/org/openapitools/client/apis/UserApi.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/DateAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt diff --git a/samples/client/petstore/kotlin-gson/.openapi-generator/VERSION b/samples/client/petstore/kotlin-gson/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/kotlin-gson/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-gson/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-gson/build.gradle b/samples/client/petstore/kotlin-gson/build.gradle index ae150592cbb1..5cad8581cb64 100644 --- a/samples/client/petstore/kotlin-gson/build.gradle +++ b/samples/client/petstore/kotlin-gson/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,8 +28,8 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "com.google.code.gson:gson:2.8.6" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "com.google.code.gson:gson:2.8.7" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index c8b93b33bf6f..28273cdf35d4 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("status", toMultiValue(status.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -218,7 +212,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +238,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("tags", toMultiValue(tags.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +269,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +294,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +321,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +346,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +375,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +402,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +432,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +459,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 215ed63420c9..56a23202f82c 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 53748b934636..9f93e853a122 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("username", listOf(username.toString())) put("password", listOf(password.toString())) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index bcbb1cf86273..8ba19ee8e157 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,14 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody +import java.io.BufferedWriter import java.io.File +import java.io.FileWriter import java.net.URLConnection -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -59,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -114,13 +114,22 @@ open class ApiClient(val baseUrl: String) { if (bodyContent.isEmpty()) { return null } + if (T::class.java == File::class.java) { + // return tempfile + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() + f.deleteOnExit() + val out = BufferedWriter(FileWriter(f)) + out.write(bodyContent) + out.close() + return f as T + } return when(mediaType) { JsonMediaType -> Serializer.gson.fromJson(bodyContent, T::class.java) else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -137,7 +146,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -171,7 +180,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -186,57 +195,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + else -> ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) } } - protected fun parameterToString(value: Any?): String { - when (value) { - null -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + protected fun parameterToString(value: Any?): String = when (value) { + null -> "" + is Array<*> -> toMultiValue(value, "csv").toString() + is Iterable<*> -> toMultiValue(value, "csv").toString() + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index 0f2790f370e2..7e948e1dd071 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jackson/.openapi-generator/FILES b/samples/client/petstore/kotlin-jackson/.openapi-generator/FILES index 6bfd310bbcad..816d952128d8 100644 --- a/samples/client/petstore/kotlin-jackson/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-jackson/.openapi-generator/FILES @@ -20,7 +20,6 @@ src/main/kotlin/org/openapitools/client/apis/UserApi.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt diff --git a/samples/client/petstore/kotlin-jackson/.openapi-generator/VERSION b/samples/client/petstore/kotlin-jackson/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/kotlin-jackson/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-jackson/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jackson/build.gradle b/samples/client/petstore/kotlin-jackson/build.gradle index 49a346f1cf9c..5cbe1fb014f9 100644 --- a/samples/client/petstore/kotlin-jackson/build.gradle +++ b/samples/client/petstore/kotlin-jackson/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,10 +28,10 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.fasterxml.jackson.module:jackson-module-kotlin:2.12.1" - compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.12.1" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.12.3" + implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.12.3" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index c8b93b33bf6f..28273cdf35d4 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("status", toMultiValue(status.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -218,7 +212,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +238,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("tags", toMultiValue(tags.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +269,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +294,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +321,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +346,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +375,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +402,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +432,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +459,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 215ed63420c9..56a23202f82c 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 53748b934636..9f93e853a122 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("username", listOf(username.toString())) put("password", listOf(password.toString())) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 637ca64c247b..6cf2ef9b0d10 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,14 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody +import java.io.BufferedWriter import java.io.File +import java.io.FileWriter import java.net.URLConnection -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -59,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -114,13 +114,22 @@ open class ApiClient(val baseUrl: String) { if (bodyContent.isEmpty()) { return null } + if (T::class.java == File::class.java) { + // return tempfile + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() + f.deleteOnExit() + val out = BufferedWriter(FileWriter(f)) + out.write(bodyContent) + out.close() + return f as T + } return when(mediaType) { JsonMediaType -> Serializer.jacksonObjectMapper.readValue(bodyContent, T::class.java) else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -137,7 +146,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -171,7 +180,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -186,57 +195,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + else -> ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) } } - protected fun parameterToString(value: Any?): String { - when (value) { - null -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + protected fun parameterToString(value: Any?): String = when (value) { + null -> "" + is Array<*> -> toMultiValue(value, "csv").toString() + is Iterable<*> -> toMultiValue(value, "csv").toString() + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index 0f2790f370e2..7e948e1dd071 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-json-request-string/.openapi-generator/FILES b/samples/client/petstore/kotlin-json-request-string/.openapi-generator/FILES index 8182d28d1951..16c712325f82 100644 --- a/samples/client/petstore/kotlin-json-request-string/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-json-request-string/.openapi-generator/FILES @@ -20,7 +20,8 @@ src/main/kotlin/org/openapitools/client/apis/UserApi.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -30,6 +31,7 @@ src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt src/main/kotlin/org/openapitools/client/models/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin-json-request-string/.openapi-generator/VERSION b/samples/client/petstore/kotlin-json-request-string/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/kotlin-json-request-string/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-json-request-string/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-json-request-string/build.gradle b/samples/client/petstore/kotlin-json-request-string/build.gradle index 60e5056e0316..189e54f81959 100644 --- a/samples/client/petstore/kotlin-json-request-string/build.gradle +++ b/samples/client/petstore/kotlin-json-request-string/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -18,6 +18,7 @@ buildscript { } apply plugin: 'kotlin' +apply plugin: 'kotlin-parcelize' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,9 +29,9 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index d939e3d5a43e..5197d04b8dfe 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -160,7 +156,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -186,23 +182,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("tags", toMultiValue(tags.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -219,7 +213,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getAllPets(lastUpdated: java.time.OffsetDateTime?) : kotlin.collections.List { val localVariableConfig = getAllPetsRequestConfig(lastUpdated = lastUpdated) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,8 +238,8 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param lastUpdated When this endpoint was hit last to help indentify if the client already has the latest copy. (optional) * @return RequestConfig */ - fun getAllPetsRequestConfig(lastUpdated: java.time.OffsetDateTime?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getAllPetsRequestConfig(lastUpdated: java.time.OffsetDateTime?) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { if (lastUpdated != null) { @@ -253,16 +247,14 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { } } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/getAll", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -279,7 +271,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -304,20 +296,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -333,7 +323,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -358,20 +348,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -389,7 +377,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -416,20 +404,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -448,7 +434,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -475,20 +461,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 215ed63420c9..56a23202f82c 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 53748b934636..9f93e853a122 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("username", listOf(username.toString())) put("password", listOf(password.toString())) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index e1d5bc9c412c..fc1578908831 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -1,6 +1,6 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials +import android.os.Build import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,14 +12,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody +import java.io.BufferedWriter import java.io.File +import java.io.FileWriter import java.net.URLConnection -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -59,9 +62,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -114,13 +115,27 @@ open class ApiClient(val baseUrl: String) { if (bodyContent.isEmpty()) { return null } + if (T::class.java == File::class.java) { + // return tempfile + val f = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + java.nio.file.Files.createTempFile("tmp.net.medicineone.teleconsultationandroid.openapi.openapicommon", null).toFile() + } else { + @Suppress("DEPRECATION") + createTempFile("tmp.net.medicineone.teleconsultationandroid.openapi.openapicommon", null) + } + f.deleteOnExit() + val out = BufferedWriter(FileWriter(f)) + out.write(bodyContent) + out.close() + return f as T + } return when(mediaType) { JsonMediaType -> Serializer.moshi.adapter(T::class.java).fromJson(bodyContent) else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -137,7 +152,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -171,7 +186,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -186,57 +201,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + else -> ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) } } - protected fun parameterToString(value: Any?): String { - when (value) { - null -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + protected fun parameterToString(value: Any?): String = when (value) { + null -> "" + is Array<*> -> toMultiValue(value, "csv").toString() + is Iterable<*> -> toMultiValue(value, "csv").toString() + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt new file mode 100644 index 000000000000..fb2c972cf8d4 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigDecimal + +class BigDecimalAdapter { + @ToJson + fun toJson(value: BigDecimal): String { + return value.toPlainString() + } + + @FromJson + fun fromJson(value: String): BigDecimal { + return BigDecimal(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt new file mode 100644 index 000000000000..4b6963110c9e --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigInteger + +class BigIntegerAdapter { + @ToJson + fun toJson(value: BigInteger): String { + return value.toString() + } + + @FromJson + fun fromJson(value: String): BigInteger { + return BigInteger(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index 0f2790f370e2..7e948e1dd071 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 9a45b67d9b1a..e77581231c31 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,7 +12,10 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) + .add(BigDecimalAdapter()) + .add(BigIntegerAdapter()) @JvmStatic val moshi: Moshi by lazy { diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 000000000000..927522757da9 --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.net.URI + +class URIAdapter { + @ToJson + fun toJson(uri: URI) = uri.toString() + + @FromJson + fun fromJson(s: String): URI = URI.create(s) +} diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b73..7ccf7dc25d2d 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt index fafca8738f66..5e349f9f96e0 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/ApiResponse.kt @@ -13,6 +13,8 @@ package org.openapitools.client.models import com.squareup.moshi.Json +import android.os.Parcelable +import kotlinx.parcelize.Parcelize /** * Describes the result of uploading an image resource @@ -20,6 +22,7 @@ import com.squareup.moshi.Json * @param type * @param message */ +@Parcelize data class ApiResponse ( @Json(name = "code") @@ -28,5 +31,5 @@ data class ApiResponse ( val type: kotlin.String? = null, @Json(name = "message") val message: kotlin.String? = null -) +) : Parcelable diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Category.kt index a4c17c3b49dd..38cc22268468 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -13,17 +13,20 @@ package org.openapitools.client.models import com.squareup.moshi.Json +import android.os.Parcelable +import kotlinx.parcelize.Parcelize /** * A category for a pet * @param id * @param name */ +@Parcelize data class Category ( @Json(name = "id") val id: kotlin.Long? = null, @Json(name = "name") val name: kotlin.String? = null -) +) : Parcelable diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Order.kt index 2bdaec85131d..7e9d9fc46441 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -13,6 +13,8 @@ package org.openapitools.client.models import com.squareup.moshi.Json +import android.os.Parcelable +import kotlinx.parcelize.Parcelize /** * An order for a pets from the pet store @@ -23,6 +25,7 @@ import com.squareup.moshi.Json * @param status Order Status * @param complete */ +@Parcelize data class Order ( @Json(name = "id") @@ -38,7 +41,7 @@ data class Order ( val status: Order.Status? = null, @Json(name = "complete") val complete: kotlin.Boolean? = null -) { +) : Parcelable { /** * Order Status diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Pet.kt index 0e38da34b79e..35de5ef28a2a 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -15,6 +15,8 @@ import org.openapitools.client.models.Category import org.openapitools.client.models.Tag import com.squareup.moshi.Json +import android.os.Parcelable +import kotlinx.parcelize.Parcelize /** * A pet for sale in the pet store @@ -25,6 +27,7 @@ import com.squareup.moshi.Json * @param tags * @param status pet status in the store */ +@Parcelize data class Pet ( @Json(name = "name") @@ -40,7 +43,7 @@ data class Pet ( /* pet status in the store */ @Json(name = "status") val status: Pet.Status? = null -) { +) : Parcelable { /** * pet status in the store diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Tag.kt index 6e619023a5c9..dc72586b9919 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -13,17 +13,20 @@ package org.openapitools.client.models import com.squareup.moshi.Json +import android.os.Parcelable +import kotlinx.parcelize.Parcelize /** * A tag for a pet * @param id * @param name */ +@Parcelize data class Tag ( @Json(name = "id") val id: kotlin.Long? = null, @Json(name = "name") val name: kotlin.String? = null -) +) : Parcelable diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/User.kt index af1e270325de..9a840f06e7fa 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/models/User.kt @@ -13,6 +13,8 @@ package org.openapitools.client.models import com.squareup.moshi.Json +import android.os.Parcelable +import kotlinx.parcelize.Parcelize /** * A User who is purchasing from the pet store @@ -25,6 +27,7 @@ import com.squareup.moshi.Json * @param phone * @param userStatus User Status */ +@Parcelize data class User ( @Json(name = "id") @@ -44,5 +47,5 @@ data class User ( /* User Status */ @Json(name = "userStatus") val userStatus: kotlin.Int? = null -) +) : Parcelable diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/.openapi-generator/FILES b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/.openapi-generator/FILES index bf441309074d..1f38d3fbe2d3 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/.openapi-generator/FILES @@ -20,7 +20,6 @@ src/main/kotlin/org/openapitools/client/apis/UserApi.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/DateAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/.openapi-generator/VERSION b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/build.gradle b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/build.gradle index ae150592cbb1..5cad8581cb64 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/build.gradle +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,8 +28,8 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "com.google.code.gson:gson:2.8.6" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "com.google.code.gson:gson:2.8.7" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 78223583f645..1e40497d817b 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("status", toMultiValue(status.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -218,7 +212,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +238,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("tags", toMultiValue(tags.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +269,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +294,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +321,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +346,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +375,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +402,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +432,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +459,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 4ab794d66081..e4ed2245f6f3 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) suspend fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) suspend fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) suspend fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) suspend fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 911bbee5b6b3..44f24c941f8f 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("username", listOf(username.toString())) put("password", listOf(password.toString())) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index bcbb1cf86273..8ba19ee8e157 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,14 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody +import java.io.BufferedWriter import java.io.File +import java.io.FileWriter import java.net.URLConnection -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -59,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -114,13 +114,22 @@ open class ApiClient(val baseUrl: String) { if (bodyContent.isEmpty()) { return null } + if (T::class.java == File::class.java) { + // return tempfile + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() + f.deleteOnExit() + val out = BufferedWriter(FileWriter(f)) + out.write(bodyContent) + out.close() + return f as T + } return when(mediaType) { JsonMediaType -> Serializer.gson.fromJson(bodyContent, T::class.java) else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -137,7 +146,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -171,7 +180,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -186,57 +195,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + else -> ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) } } - protected fun parameterToString(value: Any?): String { - when (value) { - null -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + protected fun parameterToString(value: Any?): String = when (value) { + null -> "" + is Array<*> -> toMultiValue(value, "csv").toString() + is Iterable<*> -> toMultiValue(value, "csv").toString() + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index 0f2790f370e2..7e948e1dd071 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/FILES b/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/FILES index 8182d28d1951..16c712325f82 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/FILES @@ -20,7 +20,8 @@ src/main/kotlin/org/openapitools/client/apis/UserApi.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -30,6 +31,7 @@ src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt src/main/kotlin/org/openapitools/client/models/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/VERSION b/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-moshi-codegen/build.gradle b/samples/client/petstore/kotlin-moshi-codegen/build.gradle index 5e86b0b1a362..ff73803f4b61 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/build.gradle +++ b/samples/client/petstore/kotlin-moshi-codegen/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -29,9 +29,9 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "com.squareup.moshi:moshi:1.11.0" - kapt "com.squareup.moshi:moshi-kotlin-codegen:1.11.0" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "com.squareup.moshi:moshi:1.12.0" + kapt "com.squareup.moshi:moshi-kotlin-codegen:1.12.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index c8b93b33bf6f..28273cdf35d4 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("status", toMultiValue(status.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -218,7 +212,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +238,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("tags", toMultiValue(tags.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +269,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +294,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +321,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +346,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +375,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +402,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +432,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +459,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 215ed63420c9..56a23202f82c 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 53748b934636..9f93e853a122 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("username", listOf(username.toString())) put("password", listOf(password.toString())) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 7a8dcc91cd4b..ae6e80e95062 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,14 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody +import java.io.BufferedWriter import java.io.File +import java.io.FileWriter import java.net.URLConnection -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -59,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -114,13 +114,22 @@ open class ApiClient(val baseUrl: String) { if (bodyContent.isEmpty()) { return null } + if (T::class.java == File::class.java) { + // return tempfile + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() + f.deleteOnExit() + val out = BufferedWriter(FileWriter(f)) + out.write(bodyContent) + out.close() + return f as T + } return when(mediaType) { JsonMediaType -> Serializer.moshi.adapter(T::class.java).fromJson(bodyContent) else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -137,7 +146,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -171,7 +180,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -186,57 +195,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + else -> ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) } } - protected fun parameterToString(value: Any?): String { - when (value) { - null -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + protected fun parameterToString(value: Any?): String = when (value) { + null -> "" + is Array<*> -> toMultiValue(value, "csv").toString() + is Iterable<*> -> toMultiValue(value, "csv").toString() + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt new file mode 100644 index 000000000000..fb2c972cf8d4 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigDecimal + +class BigDecimalAdapter { + @ToJson + fun toJson(value: BigDecimal): String { + return value.toPlainString() + } + + @FromJson + fun fromJson(value: String): BigDecimal { + return BigDecimal(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt new file mode 100644 index 000000000000..4b6963110c9e --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigInteger + +class BigIntegerAdapter { + @ToJson + fun toJson(value: BigInteger): String { + return value.toString() + } + + @FromJson + fun fromJson(value: String): BigInteger { + return BigInteger(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index 0f2790f370e2..7e948e1dd071 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 25447c818e66..ebd1a2a526b0 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -11,6 +11,9 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) + .add(BigDecimalAdapter()) + .add(BigIntegerAdapter()) @JvmStatic val moshi: Moshi by lazy { diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 000000000000..927522757da9 --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.net.URI + +class URIAdapter { + @ToJson + fun toJson(uri: URI) = uri.toString() + + @FromJson + fun fromJson(s: String): URI = URI.create(s) +} diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b73..7ccf7dc25d2d 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-multiplatform/.openapi-generator/VERSION b/samples/client/petstore/kotlin-multiplatform/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/kotlin-multiplatform/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-multiplatform/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index fe8434be2100..42d2a68d5b44 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -155,7 +155,7 @@ open class ApiClient( else request(requestConfig, authNames = authNames) } - protected suspend fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent, authNames: kotlin.collections.List): HttpResponse { + protected suspend inline fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent, authNames: kotlin.collections.List): HttpResponse { requestConfig.updateForAuth(authNames) val headers = requestConfig.headers diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index 0f2790f370e2..7e948e1dd071 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-nonpublic/.openapi-generator/FILES b/samples/client/petstore/kotlin-nonpublic/.openapi-generator/FILES index 8182d28d1951..16c712325f82 100644 --- a/samples/client/petstore/kotlin-nonpublic/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-nonpublic/.openapi-generator/FILES @@ -20,7 +20,8 @@ src/main/kotlin/org/openapitools/client/apis/UserApi.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -30,6 +31,7 @@ src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt src/main/kotlin/org/openapitools/client/models/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin-nonpublic/.openapi-generator/VERSION b/samples/client/petstore/kotlin-nonpublic/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/kotlin-nonpublic/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-nonpublic/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-nonpublic/build.gradle b/samples/client/petstore/kotlin-nonpublic/build.gradle index 60e5056e0316..bb575e6e4bf7 100644 --- a/samples/client/petstore/kotlin-nonpublic/build.gradle +++ b/samples/client/petstore/kotlin-nonpublic/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,9 +28,9 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index b6b38fa42f34..aa38ba8d6918 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("status", toMultiValue(status.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -218,7 +212,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +238,21 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("tags", toMultiValue(tags.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +269,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +294,18 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +321,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +346,18 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +375,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +402,18 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +432,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +459,18 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 19b7acdbd31e..10e2b9460056 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(b fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(b * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(b fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(b * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(b fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(b * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(b fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(b * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 979bb1b81f86..4983dc73feb7 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("username", listOf(username.toString())) put("password", listOf(password.toString())) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index c4da8e3989b8..ed34dce24467 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,14 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody +import java.io.BufferedWriter import java.io.File +import java.io.FileWriter import java.net.URLConnection -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale internal open class ApiClient(val baseUrl: String) { internal companion object { @@ -59,9 +61,7 @@ internal open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -114,13 +114,22 @@ internal open class ApiClient(val baseUrl: String) { if (bodyContent.isEmpty()) { return null } + if (T::class.java == File::class.java) { + // return tempfile + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() + f.deleteOnExit() + val out = BufferedWriter(FileWriter(f)) + out.write(bodyContent) + out.close() + return f as T + } return when(mediaType) { JsonMediaType -> Serializer.moshi.adapter(T::class.java).fromJson(bodyContent) else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -137,7 +146,7 @@ internal open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -171,7 +180,7 @@ internal open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -186,57 +195,46 @@ internal open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + else -> ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) } } - protected fun parameterToString(value: Any?): String { - when (value) { - null -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + protected fun parameterToString(value: Any?): String = when (value) { + null -> "" + is Array<*> -> toMultiValue(value, "csv").toString() + is Iterable<*> -> toMultiValue(value, "csv").toString() + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt new file mode 100644 index 000000000000..8aa11ef98577 --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigDecimal + +internal class BigDecimalAdapter { + @ToJson + fun toJson(value: BigDecimal): String { + return value.toPlainString() + } + + @FromJson + fun fromJson(value: String): BigDecimal { + return BigDecimal(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt new file mode 100644 index 000000000000..fbd0beed7f28 --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigInteger + +internal class BigIntegerAdapter { + @ToJson + fun toJson(value: BigInteger): String { + return value.toString() + } + + @FromJson + fun fromJson(value: String): BigInteger { + return BigInteger(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index 68f41c5497dd..70cb0b046157 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -internal data class RequestConfig( +internal data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 7265f7591428..acc0b33ae20c 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,7 +12,10 @@ internal object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) + .add(BigDecimalAdapter()) + .add(BigIntegerAdapter()) @JvmStatic val moshi: Moshi by lazy { diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 000000000000..3e509e9a8315 --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.net.URI + +internal class URIAdapter { + @ToJson + fun toJson(uri: URI) = uri.toString() + + @FromJson + fun fromJson(s: String): URI = URI.create(s) +} diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index 02fa692b57dc..b5de20257ba1 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ internal class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-nullable/.openapi-generator/FILES b/samples/client/petstore/kotlin-nullable/.openapi-generator/FILES index 8182d28d1951..16c712325f82 100644 --- a/samples/client/petstore/kotlin-nullable/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-nullable/.openapi-generator/FILES @@ -20,7 +20,8 @@ src/main/kotlin/org/openapitools/client/apis/UserApi.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -30,6 +31,7 @@ src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt src/main/kotlin/org/openapitools/client/models/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin-nullable/.openapi-generator/VERSION b/samples/client/petstore/kotlin-nullable/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/kotlin-nullable/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-nullable/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-nullable/build.gradle b/samples/client/petstore/kotlin-nullable/build.gradle index 60e5056e0316..bb575e6e4bf7 100644 --- a/samples/client/petstore/kotlin-nullable/build.gradle +++ b/samples/client/petstore/kotlin-nullable/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,9 +28,9 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 95f695cb9f48..5954c156bcd0 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List? { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("status", toMultiValue(status.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -218,7 +212,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List? { val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +238,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("tags", toMultiValue(tags.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +269,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet? { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +294,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +321,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +346,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +375,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +402,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +432,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse? { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +459,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index c442f8661003..d8b1ad578f5f 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map? { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order? { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order? { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 6e6c329144cc..a88481301162 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User? { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String? { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("username", listOf(username.toString())) put("password", listOf(password.toString())) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 7a8dcc91cd4b..ae6e80e95062 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,14 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody +import java.io.BufferedWriter import java.io.File +import java.io.FileWriter import java.net.URLConnection -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -59,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -114,13 +114,22 @@ open class ApiClient(val baseUrl: String) { if (bodyContent.isEmpty()) { return null } + if (T::class.java == File::class.java) { + // return tempfile + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() + f.deleteOnExit() + val out = BufferedWriter(FileWriter(f)) + out.write(bodyContent) + out.close() + return f as T + } return when(mediaType) { JsonMediaType -> Serializer.moshi.adapter(T::class.java).fromJson(bodyContent) else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -137,7 +146,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -171,7 +180,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -186,57 +195,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + else -> ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) } } - protected fun parameterToString(value: Any?): String { - when (value) { - null -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + protected fun parameterToString(value: Any?): String = when (value) { + null -> "" + is Array<*> -> toMultiValue(value, "csv").toString() + is Iterable<*> -> toMultiValue(value, "csv").toString() + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt new file mode 100644 index 000000000000..fb2c972cf8d4 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigDecimal + +class BigDecimalAdapter { + @ToJson + fun toJson(value: BigDecimal): String { + return value.toPlainString() + } + + @FromJson + fun fromJson(value: String): BigDecimal { + return BigDecimal(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt new file mode 100644 index 000000000000..4b6963110c9e --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigInteger + +class BigIntegerAdapter { + @ToJson + fun toJson(value: BigInteger): String { + return value.toString() + } + + @FromJson + fun fromJson(value: String): BigInteger { + return BigInteger(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index 0f2790f370e2..7e948e1dd071 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 9a45b67d9b1a..e77581231c31 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,7 +12,10 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) + .add(BigDecimalAdapter()) + .add(BigIntegerAdapter()) @JvmStatic val moshi: Moshi by lazy { diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 000000000000..927522757da9 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.net.URI + +class URIAdapter { + @ToJson + fun toJson(uri: URI) = uri.toString() + + @FromJson + fun fromJson(s: String): URI = URI.create(s) +} diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b73..7ccf7dc25d2d 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-okhttp3/.openapi-generator/FILES b/samples/client/petstore/kotlin-okhttp3/.openapi-generator/FILES index 8182d28d1951..16c712325f82 100644 --- a/samples/client/petstore/kotlin-okhttp3/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-okhttp3/.openapi-generator/FILES @@ -20,7 +20,8 @@ src/main/kotlin/org/openapitools/client/apis/UserApi.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -30,6 +31,7 @@ src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt src/main/kotlin/org/openapitools/client/models/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin-okhttp3/.openapi-generator/VERSION b/samples/client/petstore/kotlin-okhttp3/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/kotlin-okhttp3/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-okhttp3/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-okhttp3/build.gradle b/samples/client/petstore/kotlin-okhttp3/build.gradle index 1da4409df35f..4d9f2f630d47 100644 --- a/samples/client/petstore/kotlin-okhttp3/build.gradle +++ b/samples/client/petstore/kotlin-okhttp3/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,9 +28,9 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "com.squareup.okhttp3:okhttp:3.12.13" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "com.squareup.okhttp3:okhttp:3.12.13" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index c8b93b33bf6f..28273cdf35d4 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("status", toMultiValue(status.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -218,7 +212,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +238,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("tags", toMultiValue(tags.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +269,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +294,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +321,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +346,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +375,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +402,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +432,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +459,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 215ed63420c9..56a23202f82c 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 53748b934636..9f93e853a122 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("username", listOf(username.toString())) put("password", listOf(password.toString())) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 9d526273d7ac..538c66cec2e3 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.MediaType @@ -10,14 +9,17 @@ import okhttp3.ResponseBody import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody +import java.io.BufferedWriter import java.io.File +import java.io.FileWriter import java.net.URLConnection -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -57,9 +59,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> RequestBody.create( - MediaType.parse(mediaType), content - ) + content is File -> RequestBody.create(MediaType.parse(mediaType), content) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -112,13 +112,22 @@ open class ApiClient(val baseUrl: String) { if (bodyContent.isEmpty()) { return null } + if (T::class.java == File::class.java) { + // return tempfile + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() + f.deleteOnExit() + val out = BufferedWriter(FileWriter(f)) + out.write(bodyContent) + out.close() + return f as T + } return when(mediaType) { JsonMediaType -> Serializer.moshi.adapter(T::class.java).fromJson(bodyContent) else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -135,7 +144,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = HttpUrl.parse(baseUrl) ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -169,7 +178,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -184,57 +193,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code(), - response.headers().toMultimap() + return when { + response.isRedirect -> Redirection( + response.code(), + response.headers().toMultimap() ) - response.isInformational -> return Informational( - response.message(), - response.code(), - response.headers().toMultimap() + response.isInformational -> Informational( + response.message(), + response.code(), + response.headers().toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body(), accept), - response.code(), - response.headers().toMultimap() + response.isSuccessful -> Success( + responseBody(response.body(), accept), + response.code(), + response.headers().toMultimap() ) - response.isClientError -> return ClientError( - response.message(), - response.body()?.string(), - response.code(), - response.headers().toMultimap() + response.isClientError -> ClientError( + response.message(), + response.body()?.string(), + response.code(), + response.headers().toMultimap() ) - else -> return ServerError( - response.message(), - response.body()?.string(), - response.code(), - response.headers().toMultimap() + else -> ServerError( + response.message(), + response.body()?.string(), + response.code(), + response.headers().toMultimap() ) } } - protected fun parameterToString(value: Any?): String { - when (value) { - null -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + protected fun parameterToString(value: Any?): String = when (value) { + null -> "" + is Array<*> -> toMultiValue(value, "csv").toString() + is Iterable<*> -> toMultiValue(value, "csv").toString() + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt new file mode 100644 index 000000000000..fb2c972cf8d4 --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigDecimal + +class BigDecimalAdapter { + @ToJson + fun toJson(value: BigDecimal): String { + return value.toPlainString() + } + + @FromJson + fun fromJson(value: String): BigDecimal { + return BigDecimal(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt new file mode 100644 index 000000000000..4b6963110c9e --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigInteger + +class BigIntegerAdapter { + @ToJson + fun toJson(value: BigInteger): String { + return value.toString() + } + + @FromJson + fun fromJson(value: String): BigInteger { + return BigInteger(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index 0f2790f370e2..7e948e1dd071 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 9a45b67d9b1a..e77581231c31 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,7 +12,10 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) + .add(BigDecimalAdapter()) + .add(BigIntegerAdapter()) @JvmStatic val moshi: Moshi by lazy { diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 000000000000..927522757da9 --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.net.URI + +class URIAdapter { + @ToJson + fun toJson(uri: URI) = uri.toString() + + @FromJson + fun fromJson(s: String): URI = URI.create(s) +} diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b73..7ccf7dc25d2d 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/.openapi-generator/VERSION b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/build.gradle b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/build.gradle index f4436bd7b3d5..60257e316011 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/build.gradle +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/build.gradle @@ -7,8 +7,8 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' - ext.retrofitVersion = '2.7.2' + ext.kotlin_version = '1.5.10' + ext.retrofitVersion = '2.9.0' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -31,12 +31,18 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlinx:kotlinx-serialization-json:1.1.0" - compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.0" - compile "com.squareup.okhttp3:logging-interceptor:4.9.0" - compile "com.squareup.retrofit2:retrofit:$retrofitVersion" - compile "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0" - compile "com.squareup.retrofit2:converter-scalars:$retrofitVersion" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.1" + implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2" + implementation "com.squareup.okhttp3:logging-interceptor:4.9.1" + implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" + implementation "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0" + implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" +} + +tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach { + kotlinOptions { + freeCompilerArgs += "-Xopt-in=kotlinx.serialization.ExperimentalSerializationApi" + } } diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index e8b980bc8727..d30336f02e9e 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -34,7 +34,7 @@ interface PetApi { * @return [Call]<[Unit]> */ @DELETE("pet/{petId}") - fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String): Call + fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String? = null): Call /** * Finds Pets by status @@ -104,7 +104,7 @@ interface PetApi { */ @FormUrlEncoded @POST("pet/{petId}") - fun updatePetWithForm(@Path("petId") petId: kotlin.Long, @Field("name") name: kotlin.String, @Field("status") status: kotlin.String): Call + fun updatePetWithForm(@Path("petId") petId: kotlin.Long, @Field("name") name: kotlin.String? = null, @Field("status") status: kotlin.String? = null): Call /** * uploads an image @@ -119,6 +119,6 @@ interface PetApi { */ @Multipart @POST("pet/{petId}/uploadImage") - fun uploadFile(@Path("petId") petId: kotlin.Long, @Part("additionalMetadata") additionalMetadata: kotlin.String, @Part file: MultipartBody.Part): Call + fun uploadFile(@Path("petId") petId: kotlin.Long, @Part("additionalMetadata") additionalMetadata: kotlin.String? = null, @Part file: MultipartBody.Part? = null): Call } diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt index 93adbda3fc98..aa70ca9d2f18 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt @@ -13,14 +13,13 @@ import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody +import okhttp3.RequestBody.Companion.toRequestBody class OAuthOkHttpClient( - private var client: OkHttpClient + private var client: OkHttpClient = OkHttpClient() ) : HttpClient { - constructor() : this(OkHttpClient()) - @Throws(OAuthSystemException::class, OAuthProblemException::class) override fun execute( request: OAuthClientRequest, @@ -39,7 +38,7 @@ class OAuthOkHttpClient( } } - val body: RequestBody? = if (request.body != null) RequestBody.create(mediaType, request.body) else null + val body: RequestBody? = if (request.body != null) request.body.toRequestBody(mediaType) else null requestBuilder.method(requestMethod, body) try { @@ -48,6 +47,7 @@ class OAuthOkHttpClient( response.body?.string(), response.body?.contentType()?.toString(), response.code, + response.headers.toMultimap(), responseClass) } catch (e: IOException) { throw OAuthSystemException(e) diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index b721ee141b04..3bb7d9c4d663 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -7,10 +7,12 @@ import org.openapitools.client.auth.OAuth import org.openapitools.client.auth.OAuth.AccessTokenListener import org.openapitools.client.auth.OAuthFlow +import okhttp3.Call import okhttp3.Interceptor import okhttp3.OkHttpClient import retrofit2.Retrofit import okhttp3.logging.HttpLoggingInterceptor +import retrofit2.Converter import retrofit2.converter.scalars.ScalarsConverterFactory import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory @@ -20,7 +22,8 @@ import okhttp3.MediaType.Companion.toMediaType class ApiClient( private var baseUrl: String = defaultBasePath, private val okHttpClientBuilder: OkHttpClient.Builder? = null, - private val okHttpClient : OkHttpClient? = null + private val callFactory : Call.Factory? = null, + private val converterFactory: Converter.Factory? = null, ) { private val apiAuthorizations = mutableMapOf() var logger: ((String) -> Unit)? = null @@ -30,6 +33,11 @@ class ApiClient( .baseUrl(baseUrl) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(jvmJson.asConverterFactory("application/json".toMediaType())) + .apply { + if (converterFactory != null) { + addConverterFactory(converterFactory) + } + } } private val clientBuilder: OkHttpClient.Builder by lazy { @@ -173,8 +181,8 @@ class ApiClient( } fun createService(serviceClass: Class): S { - val usedClient = this.okHttpClient ?: clientBuilder.build() - return retrofitBuilder.client(usedClient).build().create(serviceClass) + val usedCallFactory = this.callFactory ?: clientBuilder.build() + return retrofitBuilder.callFactory(usedCallFactory).build().create(serviceClass) } private fun normalizeBaseUrl() { diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt index cf19653787d5..f0bedb18ea86 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -12,8 +12,6 @@ import java.math.BigDecimal @Serializer(forClass = BigDecimal::class) object BigDecimalAdapter : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("BigDecimal", PrimitiveKind.STRING) - override fun deserialize(decoder: Decoder): BigDecimal = BigDecimal(decoder.decodeString()) - override fun serialize(encoder: Encoder, value: BigDecimal) = encoder.encodeString(value.toPlainString()) } \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt index a904de643a74..ca8cc56f0643 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -12,7 +12,6 @@ import java.math.BigInteger @Serializer(forClass = BigInteger::class) object BigIntegerAdapter : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("BigInteger", PrimitiveKind.STRING) - override fun deserialize(decoder: Decoder): BigInteger { return BigInteger(decoder.decodeString()) } diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 624053c30742..e769dec78ea3 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -28,8 +28,8 @@ object Serializer { contextual(AtomicInteger::class, AtomicIntegerAdapter) contextual(AtomicLong::class, AtomicLongAdapter) contextual(AtomicBoolean::class, AtomicBooleanAdapter) - contextual(URI::class, UriAdapter) - contextual(URL::class, UrlAdapter) + contextual(URI::class, URIAdapter) + contextual(URL::class, URLAdapter) contextual(StringBuilder::class, StringBuilderAdapter) } diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt index ef3c2b387bec..0856c99813c1 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt @@ -10,7 +10,7 @@ import kotlinx.serialization.descriptors.SerialDescriptor import java.net.URI @Serializer(forClass = URI::class) -object UriAdapter : KSerializer { +object URIAdapter : KSerializer { override fun serialize(encoder: Encoder, value: URI) { encoder.encodeString(value.toASCIIString()) } @@ -18,4 +18,4 @@ object UriAdapter : KSerializer { override fun deserialize(decoder: Decoder): URI = URI(decoder.decodeString()) override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("URI", PrimitiveKind.STRING) -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt index 29546fc3ce9e..2df3308b76a3 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt @@ -10,7 +10,7 @@ import kotlinx.serialization.descriptors.SerialDescriptor import java.net.URL @Serializer(forClass = URL::class) -object UrlAdapter : KSerializer { +object URLAdapter : KSerializer { override fun serialize(encoder: Encoder, value: URL) { encoder.encodeString(value.toExternalForm()) } diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Order.kt index 879fd5c733aa..4121b6fbbbbe 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -50,6 +50,7 @@ data class Order ( * Order Status * Values: PLACED,APPROVED,DELIVERED */ + @KSerializable enum class Status(val value: kotlin.String) { @SerialName(value = "placed") PLACED("placed"), @SerialName(value = "approved") APPROVED("approved"), diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Pet.kt index 1fd2d15f8545..ea1cd27b2627 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -52,6 +52,7 @@ data class Pet ( * pet status in the store * Values: AVAILABLE,PENDING,SOLD */ + @KSerializable enum class Status(val value: kotlin.String) { @SerialName(value = "available") AVAILABLE("available"), @SerialName(value = "pending") PENDING("pending"), diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/FILES b/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/FILES index 11915fbe03f5..04b505d1f173 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/FILES @@ -22,6 +22,8 @@ src/main/kotlin/org/openapitools/client/auth/OAuth.kt src/main/kotlin/org/openapitools/client/auth/OAuthFlow.kt src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -29,6 +31,7 @@ src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/ResponseExt.kt src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt src/main/kotlin/org/openapitools/client/models/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/VERSION b/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/build.gradle b/samples/client/petstore/kotlin-retrofit2-rx3/build.gradle index b55dfb35245f..2f5e94a4fcda 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/build.gradle +++ b/samples/client/petstore/kotlin-retrofit2-rx3/build.gradle @@ -7,9 +7,9 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' - ext.retrofitVersion = '2.7.2' - ext.rxJava3Version = '3.0.10' + ext.kotlin_version = '1.5.10' + ext.retrofitVersion = '2.9.0' + ext.rxJava3Version = '3.0.12' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,15 +30,15 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.0" - compile "com.squareup.okhttp3:logging-interceptor:4.9.0" - compile "io.reactivex.rxjava3:rxjava:$rxJava3Version" - compile "com.squareup.retrofit2:adapter-rxjava3:2.9.0" - compile "com.squareup.retrofit2:retrofit:$retrofitVersion" - compile "com.squareup.retrofit2:converter-moshi:$retrofitVersion" - compile "com.squareup.retrofit2:converter-scalars:$retrofitVersion" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2" + implementation "com.squareup.okhttp3:logging-interceptor:4.9.1" + implementation "io.reactivex.rxjava3:rxjava:$rxJava3Version" + implementation "com.squareup.retrofit2:adapter-rxjava3:2.9.0" + implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" + implementation "com.squareup.retrofit2:converter-moshi:$retrofitVersion" + implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 90e791f37afa..d90c3c85f92a 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -35,7 +35,7 @@ interface PetApi { * @return [Call]<[Unit]> */ @DELETE("pet/{petId}") - fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String): Completable + fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String? = null): Completable /** * Finds Pets by status @@ -105,7 +105,7 @@ interface PetApi { */ @FormUrlEncoded @POST("pet/{petId}") - fun updatePetWithForm(@Path("petId") petId: kotlin.Long, @Field("name") name: kotlin.String, @Field("status") status: kotlin.String): Completable + fun updatePetWithForm(@Path("petId") petId: kotlin.Long, @Field("name") name: kotlin.String? = null, @Field("status") status: kotlin.String? = null): Completable /** * uploads an image @@ -120,6 +120,6 @@ interface PetApi { */ @Multipart @POST("pet/{petId}/uploadImage") - fun uploadFile(@Path("petId") petId: kotlin.Long, @Part("additionalMetadata") additionalMetadata: kotlin.String, @Part file: MultipartBody.Part): Single + fun uploadFile(@Path("petId") petId: kotlin.Long, @Part("additionalMetadata") additionalMetadata: kotlin.String? = null, @Part file: MultipartBody.Part? = null): Single } diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt index 93adbda3fc98..aa70ca9d2f18 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt @@ -13,14 +13,13 @@ import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody +import okhttp3.RequestBody.Companion.toRequestBody class OAuthOkHttpClient( - private var client: OkHttpClient + private var client: OkHttpClient = OkHttpClient() ) : HttpClient { - constructor() : this(OkHttpClient()) - @Throws(OAuthSystemException::class, OAuthProblemException::class) override fun execute( request: OAuthClientRequest, @@ -39,7 +38,7 @@ class OAuthOkHttpClient( } } - val body: RequestBody? = if (request.body != null) RequestBody.create(mediaType, request.body) else null + val body: RequestBody? = if (request.body != null) request.body.toRequestBody(mediaType) else null requestBuilder.method(requestMethod, body) try { @@ -48,6 +47,7 @@ class OAuthOkHttpClient( response.body?.string(), response.body?.contentType()?.toString(), response.code, + response.headers.toMultimap(), responseClass) } catch (e: IOException) { throw OAuthSystemException(e) diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 1b1edd60ae21..51a186e48faa 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -7,10 +7,12 @@ import org.openapitools.client.auth.OAuth import org.openapitools.client.auth.OAuth.AccessTokenListener import org.openapitools.client.auth.OAuthFlow +import okhttp3.Call import okhttp3.Interceptor import okhttp3.OkHttpClient import retrofit2.Retrofit import okhttp3.logging.HttpLoggingInterceptor +import retrofit2.Converter import retrofit2.converter.scalars.ScalarsConverterFactory import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory import com.squareup.moshi.Moshi @@ -21,7 +23,8 @@ class ApiClient( private var baseUrl: String = defaultBasePath, private val okHttpClientBuilder: OkHttpClient.Builder? = null, private val serializerBuilder: Moshi.Builder = Serializer.moshiBuilder, - private val okHttpClient : OkHttpClient? = null + private val callFactory : Call.Factory? = null, + private val converterFactory: Converter.Factory? = null, ) { private val apiAuthorizations = mutableMapOf() var logger: ((String) -> Unit)? = null @@ -33,6 +36,11 @@ class ApiClient( .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) .addConverterFactory(MoshiConverterFactory.create(serializerBuilder.build())) + .apply { + if (converterFactory != null) { + addConverterFactory(converterFactory) + } + } } private val clientBuilder: OkHttpClient.Builder by lazy { @@ -176,8 +184,8 @@ class ApiClient( } fun createService(serviceClass: Class): S { - val usedClient = this.okHttpClient ?: clientBuilder.build() - return retrofitBuilder.client(usedClient).build().create(serviceClass) + val usedCallFactory = this.callFactory ?: clientBuilder.build() + return retrofitBuilder.callFactory(usedCallFactory).build().create(serviceClass) } private fun normalizeBaseUrl() { diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt new file mode 100644 index 000000000000..fb2c972cf8d4 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigDecimal + +class BigDecimalAdapter { + @ToJson + fun toJson(value: BigDecimal): String { + return value.toPlainString() + } + + @FromJson + fun fromJson(value: String): BigDecimal { + return BigDecimal(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt new file mode 100644 index 000000000000..4b6963110c9e --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigInteger + +class BigIntegerAdapter { + @ToJson + fun toJson(value: BigInteger): String { + return value.toString() + } + + @FromJson + fun fromJson(value: String): BigInteger { + return BigInteger(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 9a45b67d9b1a..e77581231c31 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,7 +12,10 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) + .add(BigDecimalAdapter()) + .add(BigIntegerAdapter()) @JvmStatic val moshi: Moshi by lazy { diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 000000000000..927522757da9 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.net.URI + +class URIAdapter { + @ToJson + fun toJson(uri: URI) = uri.toString() + + @FromJson + fun fromJson(s: String): URI = URI.create(s) +} diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b73..7ccf7dc25d2d 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-retrofit2/.openapi-generator/FILES b/samples/client/petstore/kotlin-retrofit2/.openapi-generator/FILES index 11915fbe03f5..04b505d1f173 100644 --- a/samples/client/petstore/kotlin-retrofit2/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-retrofit2/.openapi-generator/FILES @@ -22,6 +22,8 @@ src/main/kotlin/org/openapitools/client/auth/OAuth.kt src/main/kotlin/org/openapitools/client/auth/OAuthFlow.kt src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -29,6 +31,7 @@ src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/ResponseExt.kt src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt src/main/kotlin/org/openapitools/client/models/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin-retrofit2/.openapi-generator/VERSION b/samples/client/petstore/kotlin-retrofit2/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/kotlin-retrofit2/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-retrofit2/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2/build.gradle b/samples/client/petstore/kotlin-retrofit2/build.gradle index 109eb2ca069f..ec9a8e9ac245 100644 --- a/samples/client/petstore/kotlin-retrofit2/build.gradle +++ b/samples/client/petstore/kotlin-retrofit2/build.gradle @@ -7,8 +7,8 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' - ext.retrofitVersion = '2.7.2' + ext.kotlin_version = '1.5.10' + ext.retrofitVersion = '2.9.0' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -29,13 +29,13 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.0" - compile "com.squareup.okhttp3:logging-interceptor:4.9.0" - compile "com.squareup.retrofit2:retrofit:$retrofitVersion" - compile "com.squareup.retrofit2:converter-moshi:$retrofitVersion" - compile "com.squareup.retrofit2:converter-scalars:$retrofitVersion" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2" + implementation "com.squareup.okhttp3:logging-interceptor:4.9.1" + implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" + implementation "com.squareup.retrofit2:converter-moshi:$retrofitVersion" + implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index e8b980bc8727..d30336f02e9e 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -34,7 +34,7 @@ interface PetApi { * @return [Call]<[Unit]> */ @DELETE("pet/{petId}") - fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String): Call + fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String? = null): Call /** * Finds Pets by status @@ -104,7 +104,7 @@ interface PetApi { */ @FormUrlEncoded @POST("pet/{petId}") - fun updatePetWithForm(@Path("petId") petId: kotlin.Long, @Field("name") name: kotlin.String, @Field("status") status: kotlin.String): Call + fun updatePetWithForm(@Path("petId") petId: kotlin.Long, @Field("name") name: kotlin.String? = null, @Field("status") status: kotlin.String? = null): Call /** * uploads an image @@ -119,6 +119,6 @@ interface PetApi { */ @Multipart @POST("pet/{petId}/uploadImage") - fun uploadFile(@Path("petId") petId: kotlin.Long, @Part("additionalMetadata") additionalMetadata: kotlin.String, @Part file: MultipartBody.Part): Call + fun uploadFile(@Path("petId") petId: kotlin.Long, @Part("additionalMetadata") additionalMetadata: kotlin.String? = null, @Part file: MultipartBody.Part? = null): Call } diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt index 93adbda3fc98..aa70ca9d2f18 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt @@ -13,14 +13,13 @@ import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody +import okhttp3.RequestBody.Companion.toRequestBody class OAuthOkHttpClient( - private var client: OkHttpClient + private var client: OkHttpClient = OkHttpClient() ) : HttpClient { - constructor() : this(OkHttpClient()) - @Throws(OAuthSystemException::class, OAuthProblemException::class) override fun execute( request: OAuthClientRequest, @@ -39,7 +38,7 @@ class OAuthOkHttpClient( } } - val body: RequestBody? = if (request.body != null) RequestBody.create(mediaType, request.body) else null + val body: RequestBody? = if (request.body != null) request.body.toRequestBody(mediaType) else null requestBuilder.method(requestMethod, body) try { @@ -48,6 +47,7 @@ class OAuthOkHttpClient( response.body?.string(), response.body?.contentType()?.toString(), response.code, + response.headers.toMultimap(), responseClass) } catch (e: IOException) { throw OAuthSystemException(e) diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 667359c1f227..4aa4323fc5b2 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -7,10 +7,12 @@ import org.openapitools.client.auth.OAuth import org.openapitools.client.auth.OAuth.AccessTokenListener import org.openapitools.client.auth.OAuthFlow +import okhttp3.Call import okhttp3.Interceptor import okhttp3.OkHttpClient import retrofit2.Retrofit import okhttp3.logging.HttpLoggingInterceptor +import retrofit2.Converter import retrofit2.converter.scalars.ScalarsConverterFactory import com.squareup.moshi.Moshi import retrofit2.converter.moshi.MoshiConverterFactory @@ -20,7 +22,8 @@ class ApiClient( private var baseUrl: String = defaultBasePath, private val okHttpClientBuilder: OkHttpClient.Builder? = null, private val serializerBuilder: Moshi.Builder = Serializer.moshiBuilder, - private val okHttpClient : OkHttpClient? = null + private val callFactory : Call.Factory? = null, + private val converterFactory: Converter.Factory? = null, ) { private val apiAuthorizations = mutableMapOf() var logger: ((String) -> Unit)? = null @@ -30,6 +33,11 @@ class ApiClient( .baseUrl(baseUrl) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(MoshiConverterFactory.create(serializerBuilder.build())) + .apply { + if (converterFactory != null) { + addConverterFactory(converterFactory) + } + } } private val clientBuilder: OkHttpClient.Builder by lazy { @@ -173,8 +181,8 @@ class ApiClient( } fun createService(serviceClass: Class): S { - val usedClient = this.okHttpClient ?: clientBuilder.build() - return retrofitBuilder.client(usedClient).build().create(serviceClass) + val usedCallFactory = this.callFactory ?: clientBuilder.build() + return retrofitBuilder.callFactory(usedCallFactory).build().create(serviceClass) } private fun normalizeBaseUrl() { diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt new file mode 100644 index 000000000000..fb2c972cf8d4 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigDecimal + +class BigDecimalAdapter { + @ToJson + fun toJson(value: BigDecimal): String { + return value.toPlainString() + } + + @FromJson + fun fromJson(value: String): BigDecimal { + return BigDecimal(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt new file mode 100644 index 000000000000..4b6963110c9e --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigInteger + +class BigIntegerAdapter { + @ToJson + fun toJson(value: BigInteger): String { + return value.toString() + } + + @FromJson + fun fromJson(value: String): BigInteger { + return BigInteger(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 9a45b67d9b1a..e77581231c31 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,7 +12,10 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) + .add(BigDecimalAdapter()) + .add(BigIntegerAdapter()) @JvmStatic val moshi: Moshi by lazy { diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 000000000000..927522757da9 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.net.URI + +class URIAdapter { + @ToJson + fun toJson(uri: URI) = uri.toString() + + @FromJson + fun fromJson(s: String): URI = URI.create(s) +} diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b73..7ccf7dc25d2d 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-string/.openapi-generator/FILES b/samples/client/petstore/kotlin-string/.openapi-generator/FILES index 8182d28d1951..16c712325f82 100644 --- a/samples/client/petstore/kotlin-string/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-string/.openapi-generator/FILES @@ -20,7 +20,8 @@ src/main/kotlin/org/openapitools/client/apis/UserApi.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -30,6 +31,7 @@ src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt src/main/kotlin/org/openapitools/client/models/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin-string/.openapi-generator/VERSION b/samples/client/petstore/kotlin-string/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/kotlin-string/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-string/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-string/build.gradle b/samples/client/petstore/kotlin-string/build.gradle index 60e5056e0316..bb575e6e4bf7 100644 --- a/samples/client/petstore/kotlin-string/build.gradle +++ b/samples/client/petstore/kotlin-string/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,9 +28,9 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 4fbeccdbc00a..de97218c9e8e 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(apiKey: kotlin.String?, petId: kotlin.Long) : Unit { val localVariableConfig = deletePetRequestConfig(apiKey = apiKey, petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId Pet id to delete * @return RequestConfig */ - fun deletePetRequestConfig(apiKey: kotlin.String?, petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deletePetRequestConfig(apiKey: kotlin.String?, petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("status", toMultiValue(status.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -218,7 +212,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +238,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("tags", toMultiValue(tags.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +269,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +294,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +321,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +346,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +375,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +402,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +432,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +459,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 215ed63420c9..56a23202f82c 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 53748b934636..9f93e853a122 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("username", listOf(username.toString())) put("password", listOf(password.toString())) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 7a8dcc91cd4b..ae6e80e95062 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,14 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody +import java.io.BufferedWriter import java.io.File +import java.io.FileWriter import java.net.URLConnection -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -59,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -114,13 +114,22 @@ open class ApiClient(val baseUrl: String) { if (bodyContent.isEmpty()) { return null } + if (T::class.java == File::class.java) { + // return tempfile + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() + f.deleteOnExit() + val out = BufferedWriter(FileWriter(f)) + out.write(bodyContent) + out.close() + return f as T + } return when(mediaType) { JsonMediaType -> Serializer.moshi.adapter(T::class.java).fromJson(bodyContent) else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -137,7 +146,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -171,7 +180,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -186,57 +195,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + else -> ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) } } - protected fun parameterToString(value: Any?): String { - when (value) { - null -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + protected fun parameterToString(value: Any?): String = when (value) { + null -> "" + is Array<*> -> toMultiValue(value, "csv").toString() + is Iterable<*> -> toMultiValue(value, "csv").toString() + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt new file mode 100644 index 000000000000..fb2c972cf8d4 --- /dev/null +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigDecimal + +class BigDecimalAdapter { + @ToJson + fun toJson(value: BigDecimal): String { + return value.toPlainString() + } + + @FromJson + fun fromJson(value: String): BigDecimal { + return BigDecimal(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt new file mode 100644 index 000000000000..4b6963110c9e --- /dev/null +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigInteger + +class BigIntegerAdapter { + @ToJson + fun toJson(value: BigInteger): String { + return value.toString() + } + + @FromJson + fun fromJson(value: String): BigInteger { + return BigInteger(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index 0f2790f370e2..7e948e1dd071 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 9a45b67d9b1a..e77581231c31 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,7 +12,10 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) + .add(BigDecimalAdapter()) + .add(BigIntegerAdapter()) @JvmStatic val moshi: Moshi by lazy { diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 000000000000..927522757da9 --- /dev/null +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.net.URI + +class URIAdapter { + @ToJson + fun toJson(uri: URI) = uri.toString() + + @FromJson + fun fromJson(s: String): URI = URI.create(s) +} diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b73..7ccf7dc25d2d 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-threetenbp/.openapi-generator/FILES b/samples/client/petstore/kotlin-threetenbp/.openapi-generator/FILES index 8182d28d1951..16c712325f82 100644 --- a/samples/client/petstore/kotlin-threetenbp/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-threetenbp/.openapi-generator/FILES @@ -20,7 +20,8 @@ src/main/kotlin/org/openapitools/client/apis/UserApi.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -30,6 +31,7 @@ src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt src/main/kotlin/org/openapitools/client/models/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin-threetenbp/.openapi-generator/VERSION b/samples/client/petstore/kotlin-threetenbp/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/kotlin-threetenbp/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-threetenbp/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-threetenbp/build.gradle b/samples/client/petstore/kotlin-threetenbp/build.gradle index 87605daa9d22..b4e0d0acc7a9 100644 --- a/samples/client/petstore/kotlin-threetenbp/build.gradle +++ b/samples/client/petstore/kotlin-threetenbp/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,10 +28,10 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "com.squareup.okhttp3:okhttp:4.9.0" - compile "org.threeten:threetenbp:1.5.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "org.threeten:threetenbp:1.5.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index c8b93b33bf6f..28273cdf35d4 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("status", toMultiValue(status.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -218,7 +212,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +238,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("tags", toMultiValue(tags.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +269,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +294,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +321,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +346,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +375,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +402,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +432,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +459,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 215ed63420c9..56a23202f82c 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 53748b934636..9f93e853a122 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("username", listOf(username.toString())) put("password", listOf(password.toString())) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 135bcdc790e1..ad394bbefb02 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,9 +11,12 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody +import java.io.BufferedWriter import java.io.File +import java.io.FileWriter import java.net.URLConnection import java.util.Date +import java.util.Locale import org.threeten.bp.LocalDate import org.threeten.bp.LocalDateTime import org.threeten.bp.LocalTime @@ -59,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -114,13 +114,22 @@ open class ApiClient(val baseUrl: String) { if (bodyContent.isEmpty()) { return null } + if (T::class.java == File::class.java) { + // return tempfile + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() + f.deleteOnExit() + val out = BufferedWriter(FileWriter(f)) + out.write(bodyContent) + out.close() + return f as T + } return when(mediaType) { JsonMediaType -> Serializer.moshi.adapter(T::class.java).fromJson(bodyContent) else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -137,7 +146,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -171,7 +180,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -186,57 +195,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + else -> ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) } } - protected fun parameterToString(value: Any?): String { - when (value) { - null -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + protected fun parameterToString(value: Any?): String = when (value) { + null -> "" + is Array<*> -> toMultiValue(value, "csv").toString() + is Iterable<*> -> toMultiValue(value, "csv").toString() + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt new file mode 100644 index 000000000000..fb2c972cf8d4 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigDecimal + +class BigDecimalAdapter { + @ToJson + fun toJson(value: BigDecimal): String { + return value.toPlainString() + } + + @FromJson + fun fromJson(value: String): BigDecimal { + return BigDecimal(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt new file mode 100644 index 000000000000..4b6963110c9e --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigInteger + +class BigIntegerAdapter { + @ToJson + fun toJson(value: BigInteger): String { + return value.toString() + } + + @FromJson + fun fromJson(value: String): BigInteger { + return BigInteger(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index 0f2790f370e2..7e948e1dd071 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 9a45b67d9b1a..e77581231c31 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,7 +12,10 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) + .add(BigDecimalAdapter()) + .add(BigIntegerAdapter()) @JvmStatic val moshi: Moshi by lazy { diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 000000000000..927522757da9 --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.net.URI + +class URIAdapter { + @ToJson + fun toJson(uri: URI) = uri.toString() + + @FromJson + fun fromJson(s: String): URI = URI.create(s) +} diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b73..7ccf7dc25d2d 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/FILES b/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/FILES index 1b9665590f2e..c817d8024848 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/FILES @@ -11,7 +11,8 @@ src/main/kotlin/org/openapitools/client/apis/EnumApi.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -21,5 +22,6 @@ src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt src/main/kotlin/org/openapitools/client/models/PetEnum.kt diff --git a/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/VERSION b/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-uppercase-enum/build.gradle b/samples/client/petstore/kotlin-uppercase-enum/build.gradle index 60e5056e0316..bb575e6e4bf7 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/build.gradle +++ b/samples/client/petstore/kotlin-uppercase-enum/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,9 +28,9 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/apis/EnumApi.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/apis/EnumApi.kt index e504c876ce65..59cebc5d4b98 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/apis/EnumApi.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/apis/EnumApi.kt @@ -46,7 +46,7 @@ class EnumApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getEnum() : PetEnum { val localVariableConfig = getEnumRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -70,20 +70,18 @@ class EnumApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun getEnumRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getEnumRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/enum", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index c34e9e42d08c..e65bce97f7e6 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,14 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody +import java.io.BufferedWriter import java.io.File +import java.io.FileWriter import java.net.URLConnection -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -59,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -114,6 +114,15 @@ open class ApiClient(val baseUrl: String) { if (bodyContent.isEmpty()) { return null } + if (T::class.java == File::class.java) { + // return tempfile + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() + f.deleteOnExit() + val out = BufferedWriter(FileWriter(f)) + out.write(bodyContent) + out.close() + return f as T + } return when(mediaType) { JsonMediaType -> Serializer.moshi.adapter(T::class.java).fromJson(bodyContent) else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") @@ -121,7 +130,7 @@ open class ApiClient(val baseUrl: String) { } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") val url = httpUrl.newBuilder() @@ -152,7 +161,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -167,57 +176,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + else -> ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) } } - protected fun parameterToString(value: Any?): String { - when (value) { - null -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + protected fun parameterToString(value: Any?): String = when (value) { + null -> "" + is Array<*> -> toMultiValue(value, "csv").toString() + is Iterable<*> -> toMultiValue(value, "csv").toString() + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt new file mode 100644 index 000000000000..fb2c972cf8d4 --- /dev/null +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigDecimal + +class BigDecimalAdapter { + @ToJson + fun toJson(value: BigDecimal): String { + return value.toPlainString() + } + + @FromJson + fun fromJson(value: String): BigDecimal { + return BigDecimal(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt new file mode 100644 index 000000000000..4b6963110c9e --- /dev/null +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigInteger + +class BigIntegerAdapter { + @ToJson + fun toJson(value: BigInteger): String { + return value.toString() + } + + @FromJson + fun fromJson(value: String): BigInteger { + return BigInteger(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index 0f2790f370e2..7e948e1dd071 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 9a45b67d9b1a..e77581231c31 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,7 +12,10 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) + .add(BigDecimalAdapter()) + .add(BigIntegerAdapter()) @JvmStatic val moshi: Moshi by lazy { diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 000000000000..927522757da9 --- /dev/null +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.net.URI + +class URIAdapter { + @ToJson + fun toJson(uri: URI) = uri.toString() + + @FromJson + fun fromJson(s: String): URI = URI.create(s) +} diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b73..7ccf7dc25d2d 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin/.openapi-generator/FILES b/samples/client/petstore/kotlin/.openapi-generator/FILES index 8182d28d1951..16c712325f82 100644 --- a/samples/client/petstore/kotlin/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin/.openapi-generator/FILES @@ -20,7 +20,8 @@ src/main/kotlin/org/openapitools/client/apis/UserApi.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -30,6 +31,7 @@ src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt src/main/kotlin/org/openapitools/client/models/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin/.openapi-generator/VERSION b/samples/client/petstore/kotlin/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/kotlin/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin/build.gradle b/samples/client/petstore/kotlin/build.gradle index 60e5056e0316..bb575e6e4bf7 100644 --- a/samples/client/petstore/kotlin/build.gradle +++ b/samples/client/petstore/kotlin/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,9 +28,9 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index c8b93b33bf6f..28273cdf35d4 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("status", toMultiValue(status.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -218,7 +212,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +238,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("tags", toMultiValue(tags.toList(), "csv")) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +269,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +294,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +321,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +346,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +375,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +402,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +432,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +459,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 215ed63420c9..56a23202f82c 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 53748b934636..9f93e853a122 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { put("username", listOf(username.toString())) put("password", listOf(password.toString())) } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 7a8dcc91cd4b..ae6e80e95062 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,14 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody +import java.io.BufferedWriter import java.io.File +import java.io.FileWriter import java.net.URLConnection -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -59,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -114,13 +114,22 @@ open class ApiClient(val baseUrl: String) { if (bodyContent.isEmpty()) { return null } + if (T::class.java == File::class.java) { + // return tempfile + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() + f.deleteOnExit() + val out = BufferedWriter(FileWriter(f)) + out.write(bodyContent) + out.close() + return f as T + } return when(mediaType) { JsonMediaType -> Serializer.moshi.adapter(T::class.java).fromJson(bodyContent) else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -137,7 +146,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -171,7 +180,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -186,57 +195,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + else -> ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) } } - protected fun parameterToString(value: Any?): String { - when (value) { - null -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + protected fun parameterToString(value: Any?): String = when (value) { + null -> "" + is Array<*> -> toMultiValue(value, "csv").toString() + is Iterable<*> -> toMultiValue(value, "csv").toString() + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt new file mode 100644 index 000000000000..fb2c972cf8d4 --- /dev/null +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigDecimal + +class BigDecimalAdapter { + @ToJson + fun toJson(value: BigDecimal): String { + return value.toPlainString() + } + + @FromJson + fun fromJson(value: String): BigDecimal { + return BigDecimal(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt new file mode 100644 index 000000000000..4b6963110c9e --- /dev/null +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigInteger + +class BigIntegerAdapter { + @ToJson + fun toJson(value: BigInteger): String { + return value.toString() + } + + @FromJson + fun fromJson(value: String): BigInteger { + return BigInteger(value) + } +} \ No newline at end of file diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index 0f2790f370e2..7e948e1dd071 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 9a45b67d9b1a..e77581231c31 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,7 +12,10 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) + .add(BigDecimalAdapter()) + .add(BigIntegerAdapter()) @JvmStatic val moshi: Moshi by lazy { diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 000000000000..927522757da9 --- /dev/null +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.net.URI + +class URIAdapter { + @ToJson + fun toJson(uri: URI) = uri.toString() + + @FromJson + fun fromJson(s: String): URI = URI.create(s) +} diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b73..7ccf7dc25d2d 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/lua/.openapi-generator/VERSION b/samples/client/petstore/lua/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/lua/.openapi-generator/VERSION +++ b/samples/client/petstore/lua/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/nim/.openapi-generator/VERSION b/samples/client/petstore/nim/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/nim/.openapi-generator/VERSION +++ b/samples/client/petstore/nim/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/nim/petstore/apis/api_pet.nim b/samples/client/petstore/nim/petstore/apis/api_pet.nim index 9858c523647e..b2f77c2bdbb8 100644 --- a/samples/client/petstore/nim/petstore/apis/api_pet.nim +++ b/samples/client/petstore/nim/petstore/apis/api_pet.nim @@ -39,15 +39,17 @@ template constructResult[T](response: Response): untyped = (none(T.typedesc), response) -proc addPet*(httpClient: HttpClient, body: Pet): Response = +proc addPet*(httpClient: HttpClient, pet: Pet): (Option[Pet], Response) = ## Add a new pet to the store httpClient.headers["Content-Type"] = "application/json" - httpClient.post(basepath & "/pet", $(%body)) + + let response = httpClient.post(basepath & "/pet", $(%pet)) + constructResult[Pet](response) -proc deletePet*(httpClient: HttpClient, petId: int64, api_key: string): Response = +proc deletePet*(httpClient: HttpClient, petId: int64, apiKey: string): Response = ## Deletes a pet - httpClient.headers["api_key"] = api_key + httpClient.headers["api_key"] = apiKey httpClient.delete(basepath & fmt"/pet/{petId}") @@ -78,10 +80,12 @@ proc getPetById*(httpClient: HttpClient, petId: int64): (Option[Pet], Response) constructResult[Pet](response) -proc updatePet*(httpClient: HttpClient, body: Pet): Response = +proc updatePet*(httpClient: HttpClient, pet: Pet): (Option[Pet], Response) = ## Update an existing pet httpClient.headers["Content-Type"] = "application/json" - httpClient.put(basepath & "/pet", $(%body)) + + let response = httpClient.put(basepath & "/pet", $(%pet)) + constructResult[Pet](response) proc updatePetWithForm*(httpClient: HttpClient, petId: int64, name: string, status: string): Response = diff --git a/samples/client/petstore/nim/petstore/apis/api_store.nim b/samples/client/petstore/nim/petstore/apis/api_store.nim index 3c518e8dd31a..a2f018b7cf3d 100644 --- a/samples/client/petstore/nim/petstore/apis/api_store.nim +++ b/samples/client/petstore/nim/petstore/apis/api_store.nim @@ -57,10 +57,10 @@ proc getOrderById*(httpClient: HttpClient, orderId: int64): (Option[Order], Resp constructResult[Order](response) -proc placeOrder*(httpClient: HttpClient, body: Order): (Option[Order], Response) = +proc placeOrder*(httpClient: HttpClient, order: Order): (Option[Order], Response) = ## Place an order for a pet httpClient.headers["Content-Type"] = "application/json" - let response = httpClient.post(basepath & "/store/order", $(%body)) + let response = httpClient.post(basepath & "/store/order", $(%order)) constructResult[Order](response) diff --git a/samples/client/petstore/nim/petstore/apis/api_user.nim b/samples/client/petstore/nim/petstore/apis/api_user.nim index 87bef06818e4..618477db5954 100644 --- a/samples/client/petstore/nim/petstore/apis/api_user.nim +++ b/samples/client/petstore/nim/petstore/apis/api_user.nim @@ -38,22 +38,22 @@ template constructResult[T](response: Response): untyped = (none(T.typedesc), response) -proc createUser*(httpClient: HttpClient, body: User): Response = +proc createUser*(httpClient: HttpClient, user: User): Response = ## Create user httpClient.headers["Content-Type"] = "application/json" - httpClient.post(basepath & "/user", $(%body)) + httpClient.post(basepath & "/user", $(%user)) -proc createUsersWithArrayInput*(httpClient: HttpClient, body: seq[User]): Response = +proc createUsersWithArrayInput*(httpClient: HttpClient, user: seq[User]): Response = ## Creates list of users with given input array httpClient.headers["Content-Type"] = "application/json" - httpClient.post(basepath & "/user/createWithArray", $(%body)) + httpClient.post(basepath & "/user/createWithArray", $(%user)) -proc createUsersWithListInput*(httpClient: HttpClient, body: seq[User]): Response = +proc createUsersWithListInput*(httpClient: HttpClient, user: seq[User]): Response = ## Creates list of users with given input array httpClient.headers["Content-Type"] = "application/json" - httpClient.post(basepath & "/user/createWithList", $(%body)) + httpClient.post(basepath & "/user/createWithList", $(%user)) proc deleteUser*(httpClient: HttpClient, username: string): Response = @@ -84,8 +84,8 @@ proc logoutUser*(httpClient: HttpClient): Response = httpClient.get(basepath & "/user/logout") -proc updateUser*(httpClient: HttpClient, username: string, body: User): Response = +proc updateUser*(httpClient: HttpClient, username: string, user: User): Response = ## Updated user httpClient.headers["Content-Type"] = "application/json" - httpClient.put(basepath & fmt"/user/{username}", $(%body)) + httpClient.put(basepath & fmt"/user/{username}", $(%user)) diff --git a/samples/client/petstore/objc/core-data/.openapi-generator/VERSION b/samples/client/petstore/objc/core-data/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/objc/core-data/.openapi-generator/VERSION +++ b/samples/client/petstore/objc/core-data/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/objc/default/.openapi-generator/VERSION b/samples/client/petstore/objc/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/objc/default/.openapi-generator/VERSION +++ b/samples/client/petstore/objc/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/perl/.openapi-generator/VERSION b/samples/client/petstore/perl/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/perl/.openapi-generator/VERSION +++ b/samples/client/petstore/perl/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/perl/README.md b/samples/client/petstore/perl/README.md index 9dd81b461b1c..2a469ee47b72 100644 --- a/samples/client/petstore/perl/README.md +++ b/samples/client/petstore/perl/README.md @@ -385,6 +385,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | *FakeApi* | [**fake_outer_string_serialize**](docs/FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | *FakeApi* | [**fake_property_enum_integer_serialize**](docs/FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**test_body_with_binary**](docs/FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | *FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | *FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model diff --git a/samples/client/petstore/perl/docs/FakeApi.md b/samples/client/petstore/perl/docs/FakeApi.md index d1696217c594..9db900a571aa 100644 --- a/samples/client/petstore/perl/docs/FakeApi.md +++ b/samples/client/petstore/perl/docs/FakeApi.md @@ -16,6 +16,7 @@ Method | HTTP request | Description [**fake_outer_number_serialize**](FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | [**fake_outer_string_serialize**](FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | [**fake_property_enum_integer_serialize**](FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +[**test_body_with_binary**](FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | [**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | [**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model @@ -347,12 +348,57 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_body_with_binary** +> test_body_with_binary(body => $body) + + + +For this test, the body has to be a binary file. + +### Example +```perl +use Data::Dumper; +use WWW::OpenAPIClient::FakeApi; +my $api_instance = WWW::OpenAPIClient::FakeApi->new( +); + +my $body = WWW::OpenAPIClient::Object::string->new(); # string | image to upload + +eval { + $api_instance->test_body_with_binary(body => $body); +}; +if ($@) { + warn "Exception when calling FakeApi->test_body_with_binary: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **string****string**| image to upload | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: image/png + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_body_with_file_schema** > test_body_with_file_schema(file_schema_test_class => $file_schema_test_class) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example ```perl diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/FakeApi.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/FakeApi.pm index 8646aa3cc078..d3879045deea 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/FakeApi.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/FakeApi.pm @@ -485,6 +485,62 @@ sub fake_property_enum_integer_serialize { return $_response_object; } +# +# test_body_with_binary +# +# +# +# @param string $body image to upload (required) +{ + my $params = { + 'body' => { + data_type => 'string', + description => 'image to upload', + required => '1', + }, + }; + __PACKAGE__->method_documentation->{ 'test_body_with_binary' } = { + summary => '', + params => $params, + returns => undef, + }; +} +# @return void +# +sub test_body_with_binary { + my ($self, %args) = @_; + + # parse inputs + my $_resource_path = '/fake/body-with-binary'; + + my $_method = 'PUT'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept(); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('image/png'); + + my $_body_data; + # body params + if ( exists $args{'body'}) { + $_body_data = $args{'body'}; + } + + # authentication setting, if any + my $auth_settings = [qw()]; + + # make the API Call + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; +} + # # test_body_with_file_schema # diff --git a/samples/client/petstore/php/OpenAPIClient-php/.openapi-generator/VERSION b/samples/client/petstore/php/OpenAPIClient-php/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/.openapi-generator/VERSION +++ b/samples/client/petstore/php/OpenAPIClient-php/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/php/OpenAPIClient-php/README.md b/samples/client/petstore/php/OpenAPIClient-php/README.md index 2f4807ddee0b..6540cb639a54 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/README.md +++ b/samples/client/petstore/php/OpenAPIClient-php/README.md @@ -80,6 +80,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterNumberSerialize**](docs/Api/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | *FakeApi* | [**fakeOuterStringSerialize**](docs/Api/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | *FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/Api/FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**testBodyWithBinary**](docs/Api/FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | *FakeApi* | [**testBodyWithFileSchema**](docs/Api/FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/Api/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**testClientModel**](docs/Api/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model diff --git a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/FakeApi.md b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/FakeApi.md index 4319d48a4083..ce8d2050136e 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/FakeApi.md +++ b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**fakeOuterNumberSerialize()**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | [**fakeOuterStringSerialize()**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | [**fakePropertyEnumIntegerSerialize()**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +[**testBodyWithBinary()**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | [**testBodyWithFileSchema()**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams()**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | [**testClientModel()**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model @@ -412,6 +413,61 @@ No authorization required [[Back to Model list]](../../README.md#models) [[Back to README]](../../README.md) +## `testBodyWithBinary()` + +```php +testBodyWithBinary($body) +``` + + + +For this test, the body has to be a binary file. + +### Example + +```php +testBodyWithBinary($body); +} catch (Exception $e) { + echo 'Exception when calling FakeApi->testBodyWithBinary: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **\SplFileObject****\SplFileObject**| image to upload | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: `image/png` +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + ## `testBodyWithFileSchema()` ```php @@ -420,7 +476,7 @@ testBodyWithFileSchema($file_schema_test_class) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php index 56d6d46064d8..82512bbbbfc1 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/DefaultApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/DefaultApi.php index 6bd203664b52..32aaff8894b4 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/DefaultApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/DefaultApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php index bbb07a5052e0..0fe7bd9aa07f 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** @@ -1847,6 +1847,215 @@ public function fakePropertyEnumIntegerSerializeRequest($outer_object_with_enum_ ); } + /** + * Operation testBodyWithBinary + * + * @param \SplFileObject $body image to upload (required) + * + * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function testBodyWithBinary($body) + { + $this->testBodyWithBinaryWithHttpInfo($body); + } + + /** + * Operation testBodyWithBinaryWithHttpInfo + * + * @param \SplFileObject $body image to upload (required) + * + * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function testBodyWithBinaryWithHttpInfo($body) + { + $request = $this->testBodyWithBinaryRequest($body); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation testBodyWithBinaryAsync + * + * @param \SplFileObject $body image to upload (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testBodyWithBinaryAsync($body) + { + return $this->testBodyWithBinaryAsyncWithHttpInfo($body) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation testBodyWithBinaryAsyncWithHttpInfo + * + * @param \SplFileObject $body image to upload (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testBodyWithBinaryAsyncWithHttpInfo($body) + { + $returnType = ''; + $request = $this->testBodyWithBinaryRequest($body); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'testBodyWithBinary' + * + * @param \SplFileObject $body image to upload (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function testBodyWithBinaryRequest($body) + { + // verify the required parameter 'body' is set + if ($body === null || (is_array($body) && count($body) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $body when calling testBodyWithBinary' + ); + } + + $resourcePath = '/fake/body-with-binary'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + ['image/png'] + ); + } + + // for model (json/xml) + if (isset($body)) { + if ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($body)); + } else { + $httpBody = $body; + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'PUT', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + /** * Operation testBodyWithFileSchema * @@ -4217,15 +4426,11 @@ public function testQueryParameterCollectionFormatRequest($pipe, $ioutil, $http, $multipart = false; // query params + if (is_array($pipe)) { + $pipe = ObjectSerializer::serializeCollection($pipe, 'pipeDelimited', true); + } if ($pipe !== null) { - if('form' === 'form' && is_array($pipe)) { - foreach($pipe as $key => $value) { - $queryParams[$key] = $value; - } - } - else { - $queryParams['pipe'] = $pipe; - } + $queryParams['pipe'] = $pipe; } // query params if (is_array($ioutil)) { diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php index 54e0401ada01..2958cadbd4dc 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php index d6283a8c7527..55665ac20ad9 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php index 7d1042ec3b1f..30af05a38c94 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php index 6e3fa9a1bbb6..9ca62c9a05d9 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/ApiException.php b/samples/client/petstore/php/OpenAPIClient-php/lib/ApiException.php index 5ebab62f9451..e997b629e9be 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/ApiException.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Configuration.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Configuration.php index 72c04f73a918..b252ae5ef72e 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Configuration.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php b/samples/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php index ebb51d83207e..f6c880c66d4a 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AdditionalPropertiesClass.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AdditionalPropertiesClass.php index 91e73c485f7d..f17a767e8c1d 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AdditionalPropertiesClass.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AdditionalPropertiesClass.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Animal.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Animal.php index 38b133bb9b90..5b573b955ddf 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Animal.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Animal.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ApiResponse.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ApiResponse.php index a63bc06dacf5..98a7e1675c1e 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ApiResponse.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ApiResponse.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php index ef99db2a5bd9..7e5efea61b06 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfNumberOnly.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfNumberOnly.php index fb0d29ea91a3..fdb9ab4d80b5 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfNumberOnly.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfNumberOnly.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayTest.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayTest.php index 95d9c568e95c..e882d134f8d0 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayTest.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Capitalization.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Capitalization.php index 93a983226478..a817d7fc271c 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Capitalization.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Capitalization.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Cat.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Cat.php index eec5473d0a03..789214ceee74 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Cat.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Cat.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/CatAllOf.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/CatAllOf.php index c0a50ac3d205..c28e30e06477 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/CatAllOf.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/CatAllOf.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Category.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Category.php index 4f9f0cf8513a..fe14739688bf 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Category.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ClassModel.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ClassModel.php index 18f1d351cecd..5c572564fcfa 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ClassModel.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ClassModel.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Client.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Client.php index 72fd6b41f8a2..c9296011f490 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Client.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Client.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Dog.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Dog.php index 1cd94b6fcf22..69ad47d8bc78 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Dog.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Dog.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DogAllOf.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DogAllOf.php index 85189f46fbc6..8749ebfb71e6 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DogAllOf.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DogAllOf.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumArrays.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumArrays.php index 5eef1d571956..89dee9f0bc0a 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumArrays.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumArrays.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumClass.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumClass.php index 4e958e7e816b..2581be3f1485 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumClass.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumClass.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumTest.php index 33d29157892f..f332f71f424d 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumTest.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/File.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/File.php index 8309279cf219..843efaf3eaee 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/File.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/File.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FileSchemaTestClass.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FileSchemaTestClass.php index 7c453b90cb24..65eaad6cfa81 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FileSchemaTestClass.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FileSchemaTestClass.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Foo.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Foo.php index 4812d1bb550f..3458c88050b8 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Foo.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Foo.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FormatTest.php index 42cab9a02f22..d42e123e395b 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FormatTest.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HasOnlyReadOnly.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HasOnlyReadOnly.php index 4ac2aa823530..d8453ce363b6 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HasOnlyReadOnly.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HasOnlyReadOnly.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HealthCheckResult.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HealthCheckResult.php index f4c0f3b53a27..73eb87f37176 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HealthCheckResult.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HealthCheckResult.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/InlineResponseDefault.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/InlineResponseDefault.php index f4b9d7662e0d..442ebd36dce8 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/InlineResponseDefault.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/InlineResponseDefault.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MapTest.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MapTest.php index 90be9383d313..06b442f7f85a 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MapTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MapTest.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php index d1b24805fff8..c0bb79463d6b 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Model200Response.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Model200Response.php index 7d2cc3bea120..8208b69e7bda 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Model200Response.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Model200Response.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelInterface.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelInterface.php index 1a8d27e2f423..1717e0cfc834 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelInterface.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelInterface.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelList.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelList.php index e0d226b8e9c9..72b9ef4039fa 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelList.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelList.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelReturn.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelReturn.php index 8a5df6f83231..9dcbc31a7154 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelReturn.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Name.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Name.php index cea03c776f6f..7c795f931251 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Name.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Name.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NullableClass.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NullableClass.php index 353f25b955c4..5a33a1d812e2 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NullableClass.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NullableClass.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** @@ -254,7 +254,7 @@ public function __construct(array $data = null) */ public function listInvalidProperties() { - $invalidProperties = parent::listInvalidProperties(); + $invalidProperties = []; return $invalidProperties; } diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NumberOnly.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NumberOnly.php index 3ae8a58df99d..7d75b5245b23 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NumberOnly.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NumberOnly.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Order.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Order.php index bf77a0ea4fca..81561ed34cf7 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Order.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterComposite.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterComposite.php index 89949af919cc..9107917c48e8 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterComposite.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterComposite.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnum.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnum.php index 77daf309a47d..2db56f93296b 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnum.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnum.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumDefaultValue.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumDefaultValue.php index cca89e7f08cc..53fe34e2b38d 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumDefaultValue.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumDefaultValue.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumInteger.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumInteger.php index d9a996d15a61..a79e24efb971 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumInteger.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumInteger.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumIntegerDefaultValue.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumIntegerDefaultValue.php index 235bf204e711..5316f01f7135 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumIntegerDefaultValue.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumIntegerDefaultValue.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterObjectWithEnumProperty.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterObjectWithEnumProperty.php index c053f0acb686..45138c5731d8 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterObjectWithEnumProperty.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterObjectWithEnumProperty.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Pet.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Pet.php index 989dfa568e39..3d3021236147 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Pet.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ReadOnlyFirst.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ReadOnlyFirst.php index e5805c532dd0..9f75dae4c0a9 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ReadOnlyFirst.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ReadOnlyFirst.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/SpecialModelName.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/SpecialModelName.php index ab01d45aeeb9..cde888641f40 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/SpecialModelName.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/SpecialModelName.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Tag.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Tag.php index f074c5cb4fee..51cff7e4eb42 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Tag.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/User.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/User.php index bb8c18c2be95..b3f94cc8a145 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/User.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/OpenAPIClient-php/lib/ObjectSerializer.php index 37cb5423ba95..bb58f3bbb9f3 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/ObjectSerializer.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.1.1-SNAPSHOT + * OpenAPI Generator version: 5.2.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/powershell/.openapi-generator/VERSION b/samples/client/petstore/powershell/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/powershell/.openapi-generator/VERSION +++ b/samples/client/petstore/powershell/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/powershell/appveyor.yml b/samples/client/petstore/powershell/appveyor.yml index 9a8973b0d6eb..b6967a7c7b6f 100644 --- a/samples/client/petstore/powershell/appveyor.yml +++ b/samples/client/petstore/powershell/appveyor.yml @@ -7,24 +7,26 @@ version: 1.0.{build} image: - - Visual Studio 2019 # PS 6.x - #- Visual Studio 2017 # PS 5.x - #- Ubuntu # PS 6.x - # ref: https://www.appveyor.com/docs/build-environment/#build-worker-images + - Visual Studio 2019 # PWSH 7.x + #- Visual Studio 2017 # PS 5.x, PWSH 6.x + #- Ubuntu # PWSH 6.x + # ref: https://www.appveyor.com/docs/windows-images-software/ install: - - ps: $PSVersionTable.PSVersion - - ps: Install-Module Pester -Force -Scope CurrentUser + - pwsh: $PSVersionTable.PSVersion + - pwsh: Install-Module Pester -Force -Scope CurrentUser build: off test_script: - - ps: | + - pwsh: | + .\Build.ps1 + Import-Module -Name '.\src\PSPetstore' $Result = Invoke-Pester -PassThru if ($Result.FailedCount -gt 0) { $host.SetShouldExit($Result.FailedCount) exit $Result.FailedCount } deploy_script: - - ps: | - if ($env:APPVEYOR_REPO_TAG -eq $true -and $env:NuGetApiKey -ne $null -and $env:APPVEYOR_BUILD_WORKER_IMAGE -eq "Visual Studio 2019") { + - pwsh: | + if ($env:APPVEYOR_REPO_TAG -eq $true -and $env:NuGetApiKey -ne $null) { .\Build.ps1 try { Publish-Module -NuGetApiKey $env:NuGetApiKey -Path .\src\PSPetstore\ -Confirm:$False -Verbose diff --git a/samples/client/petstore/powershell/docs/PSPetApi.md b/samples/client/petstore/powershell/docs/PSPetApi.md index 3cebe2ba2687..5b8c2a0f2e3e 100644 --- a/samples/client/petstore/powershell/docs/PSPetApi.md +++ b/samples/client/petstore/powershell/docs/PSPetApi.md @@ -46,8 +46,8 @@ Name | Type | Description | Notes **Pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type -[**Pet**](Pet.md) + +[**Pet**](Pet.md) (PSCustomObject) ### Authorization @@ -95,7 +95,7 @@ Name | Type | Description | Notes **ApiKey** | **String**| | [optional] ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type + void (empty response body) ### Authorization @@ -143,8 +143,8 @@ Name | Type | Description | Notes **Status** | [**String[]**](String.md)| Status values that need to be considered for filter | ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type -[**Pet[]**](Pet.md) + +[**Pet[]**](Pet.md) (PSCustomObject) ### Authorization @@ -191,8 +191,8 @@ Name | Type | Description | Notes **Tags** | [**String[]**](String.md)| Tags to filter by | ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type -[**Pet[]**](Pet.md) + +[**Pet[]**](Pet.md) (PSCustomObject) ### Authorization @@ -241,8 +241,8 @@ Name | Type | Description | Notes **PetId** | **Int64**| ID of pet to return | ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type -[**Pet**](Pet.md) + +[**Pet**](Pet.md) (PSCustomObject) ### Authorization @@ -287,8 +287,8 @@ Name | Type | Description | Notes **Pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type -[**Pet**](Pet.md) + +[**Pet**](Pet.md) (PSCustomObject) ### Authorization @@ -339,7 +339,7 @@ Name | Type | Description | Notes **Status** | **String**| Updated status of the pet | [optional] ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type + void (empty response body) ### Authorization @@ -391,8 +391,8 @@ Name | Type | Description | Notes **File** | **System.IO.FileInfo****System.IO.FileInfo**| file to upload | [optional] ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type -[**ApiResponse**](ApiResponse.md) + +[**ApiResponse**](ApiResponse.md) (PSCustomObject) ### Authorization diff --git a/samples/client/petstore/powershell/docs/PSStoreApi.md b/samples/client/petstore/powershell/docs/PSStoreApi.md index 65d14db7eb41..33b3541ced6c 100644 --- a/samples/client/petstore/powershell/docs/PSStoreApi.md +++ b/samples/client/petstore/powershell/docs/PSStoreApi.md @@ -39,7 +39,7 @@ Name | Type | Description | Notes **OrderId** | **String**| ID of the order that needs to be deleted | ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type + void (empty response body) ### Authorization @@ -84,7 +84,7 @@ try { This endpoint does not need any parameter. ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type + **System.Collections.Hashtable** ### Authorization @@ -127,8 +127,8 @@ Name | Type | Description | Notes **OrderId** | **Int64**| ID of pet that needs to be fetched | ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type -[**Order**](Order.md) + +[**Order**](Order.md) (PSCustomObject) ### Authorization @@ -168,8 +168,8 @@ Name | Type | Description | Notes **Order** | [**Order**](Order.md)| order placed for purchasing the pet | ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type -[**Order**](Order.md) + +[**Order**](Order.md) (PSCustomObject) ### Authorization diff --git a/samples/client/petstore/powershell/docs/PSUserApi.md b/samples/client/petstore/powershell/docs/PSUserApi.md index be51a6c6f43e..f008e292f2cf 100644 --- a/samples/client/petstore/powershell/docs/PSUserApi.md +++ b/samples/client/petstore/powershell/docs/PSUserApi.md @@ -50,7 +50,7 @@ Name | Type | Description | Notes **User** | [**User**](User.md)| Created user object | ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type + void (empty response body) ### Authorization @@ -98,7 +98,7 @@ Name | Type | Description | Notes **User** | [**User[]**](User.md)| List of user object | ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type + void (empty response body) ### Authorization @@ -146,7 +146,7 @@ Name | Type | Description | Notes **User** | [**User[]**](User.md)| List of user object | ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type + void (empty response body) ### Authorization @@ -196,7 +196,7 @@ Name | Type | Description | Notes **Username** | **String**| The name that needs to be deleted | ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type + void (empty response body) ### Authorization @@ -237,8 +237,8 @@ Name | Type | Description | Notes **Username** | **String**| The name that needs to be fetched. Use user1 for testing. | ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type -[**User**](User.md) + +[**User**](User.md) (PSCustomObject) ### Authorization @@ -281,7 +281,7 @@ Name | Type | Description | Notes **Password** | **String**| The password for login in clear text | ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type + **String** ### Authorization @@ -324,7 +324,7 @@ try { This endpoint does not need any parameter. ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type + void (empty response body) ### Authorization @@ -377,7 +377,7 @@ Name | Type | Description | Notes **User** | [**User**](User.md)| Updated user object | ### Return type -# cmdlet returns PSCustomObject, the return object contains the properties of below type + void (empty response body) ### Authorization diff --git a/samples/client/petstore/python-asyncio/.openapi-generator/VERSION b/samples/client/petstore/python-asyncio/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/python-asyncio/.openapi-generator/VERSION +++ b/samples/client/petstore/python-asyncio/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_any_type.py b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_any_type.py index 30e6e9b81766..01457faa3a33 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_any_type.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_any_type.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_array.py b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_array.py index 2f939711e0af..c7283e161360 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_array.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_array.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_boolean.py b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_boolean.py index 32b58c24ffa8..3a8ec8f66aac 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_boolean.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_boolean.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_class.py b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_class.py index dff689699744..52c475c4460c 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_class.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -339,7 +342,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_integer.py b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_integer.py index bba82b9c8cf9..d9ee889d7a33 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_integer.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_integer.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_number.py b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_number.py index 9adeedb7e792..756fc037970f 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_number.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_number.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_object.py b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_object.py index 85f94ac205df..bfbe2db1bef9 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_object.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_object.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_string.py b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_string.py index ee8d6383348c..7c33a16fe8fc 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_string.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/additional_properties_string.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/animal.py b/samples/client/petstore/python-asyncio/petstore_api/models/animal.py index a791a5173ba1..eee29f37f881 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/animal.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/animal.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -118,7 +121,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/api_response.py b/samples/client/petstore/python-asyncio/petstore_api/models/api_response.py index ab5e7999dd2f..bddac1eb10a3 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/api_response.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/api_response.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/array_of_array_of_number_only.py b/samples/client/petstore/python-asyncio/petstore_api/models/array_of_array_of_number_only.py index c9b65c7e5315..2975adc20e31 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/array_of_array_of_number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/array_of_number_only.py b/samples/client/petstore/python-asyncio/petstore_api/models/array_of_number_only.py index 870286e0fc08..2a3400e76660 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/array_of_number_only.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/array_of_number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/array_test.py b/samples/client/petstore/python-asyncio/petstore_api/models/array_test.py index 04d2cb6ec602..11394dcb7bc1 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/array_test.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/array_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/big_cat.py b/samples/client/petstore/python-asyncio/petstore_api/models/big_cat.py index 7136aa867207..9a108ce3717e 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/big_cat.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/big_cat.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -85,7 +88,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/big_cat_all_of.py b/samples/client/petstore/python-asyncio/petstore_api/models/big_cat_all_of.py index 127e7c6da31a..6d6c9aeb5c0c 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/big_cat_all_of.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/big_cat_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -85,7 +88,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/capitalization.py b/samples/client/petstore/python-asyncio/petstore_api/models/capitalization.py index 064dc2eb2ff5..cb8b0d985842 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/capitalization.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/capitalization.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -211,7 +214,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/cat.py b/samples/client/petstore/python-asyncio/petstore_api/models/cat.py index 3b6e6aa4c2e8..0d9a0b20bf1a 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/cat.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/cat.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/cat_all_of.py b/samples/client/petstore/python-asyncio/petstore_api/models/cat_all_of.py index 7755fd65b0c3..0633bbf58d0d 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/cat_all_of.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/cat_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/category.py b/samples/client/petstore/python-asyncio/petstore_api/models/category.py index c3dd5a4b9a17..ef52dcbf8c91 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/category.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/category.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -106,7 +109,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/class_model.py b/samples/client/petstore/python-asyncio/petstore_api/models/class_model.py index cd9439763d20..84c0de65b472 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/class_model.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/class_model.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/client.py b/samples/client/petstore/python-asyncio/petstore_api/models/client.py index f896b35240c7..8d7c83ecfe6b 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/client.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/client.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/dog.py b/samples/client/petstore/python-asyncio/petstore_api/models/dog.py index 39514284d5f2..61acd35cdfe2 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/dog.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/dog.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/dog_all_of.py b/samples/client/petstore/python-asyncio/petstore_api/models/dog_all_of.py index 207103a48745..3a052c3258ae 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/dog_all_of.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/dog_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/enum_arrays.py b/samples/client/petstore/python-asyncio/petstore_api/models/enum_arrays.py index b87cd37456e1..eb4f3ea4ca32 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/enum_arrays.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/enum_arrays.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -119,7 +122,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/enum_class.py b/samples/client/petstore/python-asyncio/petstore_api/models/enum_class.py index 4b11877863ac..79aac3570cb9 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/enum_class.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/enum_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/enum_test.py b/samples/client/petstore/python-asyncio/petstore_api/models/enum_test.py index d1778410dee2..1f3d7cb29b89 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/enum_test.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/enum_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -208,7 +211,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/file.py b/samples/client/petstore/python-asyncio/petstore_api/models/file.py index e40cd04b0149..2c1cccac0e11 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/file.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/file.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -81,7 +84,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/file_schema_test_class.py b/samples/client/petstore/python-asyncio/petstore_api/models/file_schema_test_class.py index d266755d260a..c5a23842d4f6 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/file_schema_test_class.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/file_schema_test_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/format_test.py b/samples/client/petstore/python-asyncio/petstore_api/models/format_test.py index c193f9313e96..452582251a59 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/format_test.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/format_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -463,7 +466,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/has_only_read_only.py b/samples/client/petstore/python-asyncio/petstore_api/models/has_only_read_only.py index dac8cfaff937..7175c2acc721 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/has_only_read_only.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/has_only_read_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/list.py b/samples/client/petstore/python-asyncio/petstore_api/models/list.py index b44257224741..6e1dea4e33b5 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/list.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/list.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/map_test.py b/samples/client/petstore/python-asyncio/petstore_api/models/map_test.py index 406f35db7500..21bd2ccda980 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/map_test.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/map_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -165,7 +168,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python-asyncio/petstore_api/models/mixed_properties_and_additional_properties_class.py index 14428a6536a8..9e727b07d5c7 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/model200_response.py b/samples/client/petstore/python-asyncio/petstore_api/models/model200_response.py index 5c90147467b5..db587fd24e2f 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/model200_response.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/model200_response.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/model_return.py b/samples/client/petstore/python-asyncio/petstore_api/models/model_return.py index 88174ef23083..5354fd56e2ce 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/model_return.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/model_return.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/name.py b/samples/client/petstore/python-asyncio/petstore_api/models/name.py index 528988ebd437..0191a3a934ae 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/name.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/name.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -158,7 +161,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/number_only.py b/samples/client/petstore/python-asyncio/petstore_api/models/number_only.py index ebbcc8996d01..59a252e0bb66 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/number_only.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/order.py b/samples/client/petstore/python-asyncio/petstore_api/models/order.py index 6513d48a3a5e..a267324d0d19 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/order.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/order.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -217,7 +220,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/outer_composite.py b/samples/client/petstore/python-asyncio/petstore_api/models/outer_composite.py index 44124e13c09b..e26160ab4302 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/outer_composite.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/outer_composite.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/outer_enum.py b/samples/client/petstore/python-asyncio/petstore_api/models/outer_enum.py index 77624ba15408..27cdfd1fb791 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/outer_enum.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/outer_enum.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/pet.py b/samples/client/petstore/python-asyncio/petstore_api/models/pet.py index e71589429ca0..22bb4a585e47 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/pet.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/pet.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -219,7 +222,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/read_only_first.py b/samples/client/petstore/python-asyncio/petstore_api/models/read_only_first.py index 3a320fe64f06..c2888eba7500 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/read_only_first.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/read_only_first.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/special_model_name.py b/samples/client/petstore/python-asyncio/petstore_api/models/special_model_name.py index 7669a508789f..4c848e1887c0 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/special_model_name.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/special_model_name.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/tag.py b/samples/client/petstore/python-asyncio/petstore_api/models/tag.py index dbac885ad8e9..a3e6789078d8 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/tag.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/tag.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/type_holder_default.py b/samples/client/petstore/python-asyncio/petstore_api/models/type_holder_default.py index c890f5531927..582b4c8d6dc2 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/type_holder_default.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/type_holder_default.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -188,7 +191,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/type_holder_example.py b/samples/client/petstore/python-asyncio/petstore_api/models/type_holder_example.py index d52425d442ea..268595ed8681 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/type_holder_example.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/type_holder_example.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -215,7 +218,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/user.py b/samples/client/petstore/python-asyncio/petstore_api/models/user.py index b70d84a6b40e..7ae2898f6c5a 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/user.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/user.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -263,7 +266,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/models/xml_item.py b/samples/client/petstore/python-asyncio/petstore_api/models/xml_item.py index d63ab77acfde..5e6fecdd71c8 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/models/xml_item.py +++ b/samples/client/petstore/python-asyncio/petstore_api/models/xml_item.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -807,7 +810,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/.openapi-generator/VERSION b/samples/client/petstore/python-legacy/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/python-legacy/.openapi-generator/VERSION +++ b/samples/client/petstore/python-legacy/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_any_type.py b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_any_type.py index 30e6e9b81766..01457faa3a33 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_any_type.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_any_type.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_array.py b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_array.py index 2f939711e0af..c7283e161360 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_array.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_array.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_boolean.py b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_boolean.py index 32b58c24ffa8..3a8ec8f66aac 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_boolean.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_boolean.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_class.py b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_class.py index dff689699744..52c475c4460c 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_class.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -339,7 +342,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_integer.py b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_integer.py index bba82b9c8cf9..d9ee889d7a33 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_integer.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_integer.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_number.py b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_number.py index 9adeedb7e792..756fc037970f 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_number.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_number.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_object.py b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_object.py index 85f94ac205df..bfbe2db1bef9 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_object.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_object.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_string.py b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_string.py index ee8d6383348c..7c33a16fe8fc 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_string.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/additional_properties_string.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/animal.py b/samples/client/petstore/python-legacy/petstore_api/models/animal.py index a791a5173ba1..eee29f37f881 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/animal.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/animal.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -118,7 +121,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/api_response.py b/samples/client/petstore/python-legacy/petstore_api/models/api_response.py index ab5e7999dd2f..bddac1eb10a3 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/api_response.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/api_response.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/array_of_array_of_number_only.py b/samples/client/petstore/python-legacy/petstore_api/models/array_of_array_of_number_only.py index c9b65c7e5315..2975adc20e31 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/array_of_array_of_number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/array_of_number_only.py b/samples/client/petstore/python-legacy/petstore_api/models/array_of_number_only.py index 870286e0fc08..2a3400e76660 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/array_of_number_only.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/array_of_number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/array_test.py b/samples/client/petstore/python-legacy/petstore_api/models/array_test.py index 04d2cb6ec602..11394dcb7bc1 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/array_test.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/array_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/big_cat.py b/samples/client/petstore/python-legacy/petstore_api/models/big_cat.py index 7136aa867207..9a108ce3717e 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/big_cat.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/big_cat.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -85,7 +88,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/big_cat_all_of.py b/samples/client/petstore/python-legacy/petstore_api/models/big_cat_all_of.py index 127e7c6da31a..6d6c9aeb5c0c 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/big_cat_all_of.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/big_cat_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -85,7 +88,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/capitalization.py b/samples/client/petstore/python-legacy/petstore_api/models/capitalization.py index 064dc2eb2ff5..cb8b0d985842 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/capitalization.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/capitalization.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -211,7 +214,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/cat.py b/samples/client/petstore/python-legacy/petstore_api/models/cat.py index 3b6e6aa4c2e8..0d9a0b20bf1a 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/cat.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/cat.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/cat_all_of.py b/samples/client/petstore/python-legacy/petstore_api/models/cat_all_of.py index 7755fd65b0c3..0633bbf58d0d 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/cat_all_of.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/cat_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/category.py b/samples/client/petstore/python-legacy/petstore_api/models/category.py index c3dd5a4b9a17..ef52dcbf8c91 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/category.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/category.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -106,7 +109,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/class_model.py b/samples/client/petstore/python-legacy/petstore_api/models/class_model.py index cd9439763d20..84c0de65b472 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/class_model.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/class_model.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/client.py b/samples/client/petstore/python-legacy/petstore_api/models/client.py index f896b35240c7..8d7c83ecfe6b 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/client.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/client.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/dog.py b/samples/client/petstore/python-legacy/petstore_api/models/dog.py index 39514284d5f2..61acd35cdfe2 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/dog.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/dog.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/dog_all_of.py b/samples/client/petstore/python-legacy/petstore_api/models/dog_all_of.py index 207103a48745..3a052c3258ae 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/dog_all_of.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/dog_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/enum_arrays.py b/samples/client/petstore/python-legacy/petstore_api/models/enum_arrays.py index b87cd37456e1..eb4f3ea4ca32 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/enum_arrays.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/enum_arrays.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -119,7 +122,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/enum_class.py b/samples/client/petstore/python-legacy/petstore_api/models/enum_class.py index 4b11877863ac..79aac3570cb9 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/enum_class.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/enum_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/enum_test.py b/samples/client/petstore/python-legacy/petstore_api/models/enum_test.py index d1778410dee2..1f3d7cb29b89 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/enum_test.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/enum_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -208,7 +211,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/file.py b/samples/client/petstore/python-legacy/petstore_api/models/file.py index e40cd04b0149..2c1cccac0e11 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/file.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/file.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -81,7 +84,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/file_schema_test_class.py b/samples/client/petstore/python-legacy/petstore_api/models/file_schema_test_class.py index d266755d260a..c5a23842d4f6 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/file_schema_test_class.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/file_schema_test_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/format_test.py b/samples/client/petstore/python-legacy/petstore_api/models/format_test.py index c193f9313e96..452582251a59 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/format_test.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/format_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -463,7 +466,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/has_only_read_only.py b/samples/client/petstore/python-legacy/petstore_api/models/has_only_read_only.py index dac8cfaff937..7175c2acc721 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/has_only_read_only.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/has_only_read_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/list.py b/samples/client/petstore/python-legacy/petstore_api/models/list.py index b44257224741..6e1dea4e33b5 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/list.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/list.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/map_test.py b/samples/client/petstore/python-legacy/petstore_api/models/map_test.py index 406f35db7500..21bd2ccda980 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/map_test.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/map_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -165,7 +168,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python-legacy/petstore_api/models/mixed_properties_and_additional_properties_class.py index 14428a6536a8..9e727b07d5c7 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/model200_response.py b/samples/client/petstore/python-legacy/petstore_api/models/model200_response.py index 5c90147467b5..db587fd24e2f 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/model200_response.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/model200_response.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/model_return.py b/samples/client/petstore/python-legacy/petstore_api/models/model_return.py index 88174ef23083..5354fd56e2ce 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/model_return.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/model_return.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/name.py b/samples/client/petstore/python-legacy/petstore_api/models/name.py index 528988ebd437..0191a3a934ae 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/name.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/name.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -158,7 +161,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/number_only.py b/samples/client/petstore/python-legacy/petstore_api/models/number_only.py index ebbcc8996d01..59a252e0bb66 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/number_only.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/order.py b/samples/client/petstore/python-legacy/petstore_api/models/order.py index 6513d48a3a5e..a267324d0d19 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/order.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/order.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -217,7 +220,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/outer_composite.py b/samples/client/petstore/python-legacy/petstore_api/models/outer_composite.py index 44124e13c09b..e26160ab4302 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/outer_composite.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/outer_composite.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/outer_enum.py b/samples/client/petstore/python-legacy/petstore_api/models/outer_enum.py index 77624ba15408..27cdfd1fb791 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/outer_enum.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/outer_enum.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/pet.py b/samples/client/petstore/python-legacy/petstore_api/models/pet.py index e71589429ca0..22bb4a585e47 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/pet.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/pet.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -219,7 +222,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/read_only_first.py b/samples/client/petstore/python-legacy/petstore_api/models/read_only_first.py index 3a320fe64f06..c2888eba7500 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/read_only_first.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/read_only_first.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/special_model_name.py b/samples/client/petstore/python-legacy/petstore_api/models/special_model_name.py index 7669a508789f..4c848e1887c0 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/special_model_name.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/special_model_name.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/tag.py b/samples/client/petstore/python-legacy/petstore_api/models/tag.py index dbac885ad8e9..a3e6789078d8 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/tag.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/tag.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/type_holder_default.py b/samples/client/petstore/python-legacy/petstore_api/models/type_holder_default.py index c890f5531927..582b4c8d6dc2 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/type_holder_default.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/type_holder_default.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -188,7 +191,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/type_holder_example.py b/samples/client/petstore/python-legacy/petstore_api/models/type_holder_example.py index d52425d442ea..268595ed8681 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/type_holder_example.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/type_holder_example.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -215,7 +218,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/user.py b/samples/client/petstore/python-legacy/petstore_api/models/user.py index b70d84a6b40e..7ae2898f6c5a 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/user.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/user.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -263,7 +266,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-legacy/petstore_api/models/xml_item.py b/samples/client/petstore/python-legacy/petstore_api/models/xml_item.py index d63ab77acfde..5e6fecdd71c8 100644 --- a/samples/client/petstore/python-legacy/petstore_api/models/xml_item.py +++ b/samples/client/petstore/python-legacy/petstore_api/models/xml_item.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -807,7 +810,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/.openapi-generator/VERSION b/samples/client/petstore/python-tornado/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/python-tornado/.openapi-generator/VERSION +++ b/samples/client/petstore/python-tornado/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_any_type.py b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_any_type.py index 30e6e9b81766..01457faa3a33 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_any_type.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_any_type.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_array.py b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_array.py index 2f939711e0af..c7283e161360 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_array.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_array.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_boolean.py b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_boolean.py index 32b58c24ffa8..3a8ec8f66aac 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_boolean.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_boolean.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_class.py b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_class.py index dff689699744..52c475c4460c 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_class.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -339,7 +342,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_integer.py b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_integer.py index bba82b9c8cf9..d9ee889d7a33 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_integer.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_integer.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_number.py b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_number.py index 9adeedb7e792..756fc037970f 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_number.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_number.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_object.py b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_object.py index 85f94ac205df..bfbe2db1bef9 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_object.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_object.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_string.py b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_string.py index ee8d6383348c..7c33a16fe8fc 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_string.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/additional_properties_string.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/animal.py b/samples/client/petstore/python-tornado/petstore_api/models/animal.py index a791a5173ba1..eee29f37f881 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/animal.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/animal.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -118,7 +121,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/api_response.py b/samples/client/petstore/python-tornado/petstore_api/models/api_response.py index ab5e7999dd2f..bddac1eb10a3 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/api_response.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/api_response.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/array_of_array_of_number_only.py b/samples/client/petstore/python-tornado/petstore_api/models/array_of_array_of_number_only.py index c9b65c7e5315..2975adc20e31 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/array_of_array_of_number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/array_of_number_only.py b/samples/client/petstore/python-tornado/petstore_api/models/array_of_number_only.py index 870286e0fc08..2a3400e76660 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/array_of_number_only.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/array_of_number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/array_test.py b/samples/client/petstore/python-tornado/petstore_api/models/array_test.py index 04d2cb6ec602..11394dcb7bc1 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/array_test.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/array_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/big_cat.py b/samples/client/petstore/python-tornado/petstore_api/models/big_cat.py index 7136aa867207..9a108ce3717e 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/big_cat.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/big_cat.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -85,7 +88,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/big_cat_all_of.py b/samples/client/petstore/python-tornado/petstore_api/models/big_cat_all_of.py index 127e7c6da31a..6d6c9aeb5c0c 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/big_cat_all_of.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/big_cat_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -85,7 +88,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/capitalization.py b/samples/client/petstore/python-tornado/petstore_api/models/capitalization.py index 064dc2eb2ff5..cb8b0d985842 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/capitalization.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/capitalization.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -211,7 +214,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/cat.py b/samples/client/petstore/python-tornado/petstore_api/models/cat.py index 3b6e6aa4c2e8..0d9a0b20bf1a 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/cat.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/cat.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/cat_all_of.py b/samples/client/petstore/python-tornado/petstore_api/models/cat_all_of.py index 7755fd65b0c3..0633bbf58d0d 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/cat_all_of.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/cat_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/category.py b/samples/client/petstore/python-tornado/petstore_api/models/category.py index c3dd5a4b9a17..ef52dcbf8c91 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/category.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/category.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -106,7 +109,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/class_model.py b/samples/client/petstore/python-tornado/petstore_api/models/class_model.py index cd9439763d20..84c0de65b472 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/class_model.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/class_model.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/client.py b/samples/client/petstore/python-tornado/petstore_api/models/client.py index f896b35240c7..8d7c83ecfe6b 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/client.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/client.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/dog.py b/samples/client/petstore/python-tornado/petstore_api/models/dog.py index 39514284d5f2..61acd35cdfe2 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/dog.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/dog.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/dog_all_of.py b/samples/client/petstore/python-tornado/petstore_api/models/dog_all_of.py index 207103a48745..3a052c3258ae 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/dog_all_of.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/dog_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/enum_arrays.py b/samples/client/petstore/python-tornado/petstore_api/models/enum_arrays.py index b87cd37456e1..eb4f3ea4ca32 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/enum_arrays.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/enum_arrays.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -119,7 +122,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/enum_class.py b/samples/client/petstore/python-tornado/petstore_api/models/enum_class.py index 4b11877863ac..79aac3570cb9 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/enum_class.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/enum_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/enum_test.py b/samples/client/petstore/python-tornado/petstore_api/models/enum_test.py index d1778410dee2..1f3d7cb29b89 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/enum_test.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/enum_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -208,7 +211,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/file.py b/samples/client/petstore/python-tornado/petstore_api/models/file.py index e40cd04b0149..2c1cccac0e11 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/file.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/file.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -81,7 +84,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/file_schema_test_class.py b/samples/client/petstore/python-tornado/petstore_api/models/file_schema_test_class.py index d266755d260a..c5a23842d4f6 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/file_schema_test_class.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/file_schema_test_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/format_test.py b/samples/client/petstore/python-tornado/petstore_api/models/format_test.py index c193f9313e96..452582251a59 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/format_test.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/format_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -463,7 +466,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/has_only_read_only.py b/samples/client/petstore/python-tornado/petstore_api/models/has_only_read_only.py index dac8cfaff937..7175c2acc721 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/has_only_read_only.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/has_only_read_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/list.py b/samples/client/petstore/python-tornado/petstore_api/models/list.py index b44257224741..6e1dea4e33b5 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/list.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/list.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/map_test.py b/samples/client/petstore/python-tornado/petstore_api/models/map_test.py index 406f35db7500..21bd2ccda980 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/map_test.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/map_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -165,7 +168,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python-tornado/petstore_api/models/mixed_properties_and_additional_properties_class.py index 14428a6536a8..9e727b07d5c7 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/model200_response.py b/samples/client/petstore/python-tornado/petstore_api/models/model200_response.py index 5c90147467b5..db587fd24e2f 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/model200_response.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/model200_response.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/model_return.py b/samples/client/petstore/python-tornado/petstore_api/models/model_return.py index 88174ef23083..5354fd56e2ce 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/model_return.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/model_return.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/name.py b/samples/client/petstore/python-tornado/petstore_api/models/name.py index 528988ebd437..0191a3a934ae 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/name.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/name.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -158,7 +161,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/number_only.py b/samples/client/petstore/python-tornado/petstore_api/models/number_only.py index ebbcc8996d01..59a252e0bb66 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/number_only.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/order.py b/samples/client/petstore/python-tornado/petstore_api/models/order.py index 6513d48a3a5e..a267324d0d19 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/order.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/order.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -217,7 +220,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/outer_composite.py b/samples/client/petstore/python-tornado/petstore_api/models/outer_composite.py index 44124e13c09b..e26160ab4302 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/outer_composite.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/outer_composite.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/outer_enum.py b/samples/client/petstore/python-tornado/petstore_api/models/outer_enum.py index 77624ba15408..27cdfd1fb791 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/outer_enum.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/outer_enum.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/pet.py b/samples/client/petstore/python-tornado/petstore_api/models/pet.py index e71589429ca0..22bb4a585e47 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/pet.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/pet.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -219,7 +222,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/read_only_first.py b/samples/client/petstore/python-tornado/petstore_api/models/read_only_first.py index 3a320fe64f06..c2888eba7500 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/read_only_first.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/read_only_first.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/special_model_name.py b/samples/client/petstore/python-tornado/petstore_api/models/special_model_name.py index 7669a508789f..4c848e1887c0 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/special_model_name.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/special_model_name.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/tag.py b/samples/client/petstore/python-tornado/petstore_api/models/tag.py index dbac885ad8e9..a3e6789078d8 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/tag.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/tag.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/type_holder_default.py b/samples/client/petstore/python-tornado/petstore_api/models/type_holder_default.py index c890f5531927..582b4c8d6dc2 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/type_holder_default.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/type_holder_default.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -188,7 +191,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/type_holder_example.py b/samples/client/petstore/python-tornado/petstore_api/models/type_holder_example.py index d52425d442ea..268595ed8681 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/type_holder_example.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/type_holder_example.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -215,7 +218,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/user.py b/samples/client/petstore/python-tornado/petstore_api/models/user.py index b70d84a6b40e..7ae2898f6c5a 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/user.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/user.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -263,7 +266,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python-tornado/petstore_api/models/xml_item.py b/samples/client/petstore/python-tornado/petstore_api/models/xml_item.py index d63ab77acfde..5e6fecdd71c8 100644 --- a/samples/client/petstore/python-tornado/petstore_api/models/xml_item.py +++ b/samples/client/petstore/python-tornado/petstore_api/models/xml_item.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -807,7 +810,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/client/petstore/python/.openapi-generator/VERSION b/samples/client/petstore/python/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/python/.openapi-generator/VERSION +++ b/samples/client/petstore/python/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/python/docs/AdditionalPropertiesAnyType.md b/samples/client/petstore/python/docs/AdditionalPropertiesAnyType.md index a69ff4928f44..d31d12de0822 100644 --- a/samples/client/petstore/python/docs/AdditionalPropertiesAnyType.md +++ b/samples/client/petstore/python/docs/AdditionalPropertiesAnyType.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | [optional] -**any string name** | **bool, date, datetime, dict, float, int, list, str** | any string name can be used but the value must be the correct type | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/AdditionalPropertiesArray.md b/samples/client/petstore/python/docs/AdditionalPropertiesArray.md index 697494b373ff..40537cbf8384 100644 --- a/samples/client/petstore/python/docs/AdditionalPropertiesArray.md +++ b/samples/client/petstore/python/docs/AdditionalPropertiesArray.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | [optional] -**any string name** | **[bool, date, datetime, dict, float, int, list, str]** | any string name can be used but the value must be the correct type | [optional] +**any string name** | **[bool, date, datetime, dict, float, int, list, str, none_type]** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/AdditionalPropertiesClass.md b/samples/client/petstore/python/docs/AdditionalPropertiesClass.md index 3646837b853b..3ba7bab6f3d0 100644 --- a/samples/client/petstore/python/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/python/docs/AdditionalPropertiesClass.md @@ -9,12 +9,13 @@ Name | Type | Description | Notes **map_integer** | **{str: (int,)}** | | [optional] **map_boolean** | **{str: (bool,)}** | | [optional] **map_array_integer** | **{str: ([int],)}** | | [optional] -**map_array_anytype** | **{str: ([bool, date, datetime, dict, float, int, list, str],)}** | | [optional] +**map_array_anytype** | **{str: ([bool, date, datetime, dict, float, int, list, str, none_type],)}** | | [optional] **map_map_string** | **{str: ({str: (str,)},)}** | | [optional] -**map_map_anytype** | **{str: ({str: (bool, date, datetime, dict, float, int, list, str,)},)}** | | [optional] -**anytype_1** | **bool, date, datetime, dict, float, int, list, str** | | [optional] -**anytype_2** | **bool, date, datetime, dict, float, int, list, str** | | [optional] -**anytype_3** | **bool, date, datetime, dict, float, int, list, str** | | [optional] +**map_map_anytype** | **{str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type,)},)}** | | [optional] +**anytype_1** | **bool, date, datetime, dict, float, int, list, str, none_type** | | [optional] +**anytype_2** | **bool, date, datetime, dict, float, int, list, str, none_type** | no type is set for this | [optional] +**anytype_3** | **bool, date, datetime, dict, float, int, list, str, none_type** | because of a bug in swagger-parser, this should have values {str: (str, int, float...)} but instead we get any type. See https://github.com/swagger-api/swagger-parser/issues/1378 | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/AdditionalPropertiesObject.md b/samples/client/petstore/python/docs/AdditionalPropertiesObject.md index 73ba59147122..dc64a0d91c24 100644 --- a/samples/client/petstore/python/docs/AdditionalPropertiesObject.md +++ b/samples/client/petstore/python/docs/AdditionalPropertiesObject.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | [optional] -**any string name** | **{str: (bool, date, datetime, dict, float, int, list, str,)}** | any string name can be used but the value must be the correct type | [optional] +**any string name** | **{str: (bool, date, datetime, dict, float, int, list, str, none_type,)}** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/Animal.md b/samples/client/petstore/python/docs/Animal.md index 1d1c77c01abc..d36c66a5d882 100644 --- a/samples/client/petstore/python/docs/Animal.md +++ b/samples/client/petstore/python/docs/Animal.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **str** | | **color** | **str** | | [optional] if omitted the server will use the default value of "red" +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/AnimalFarm.md b/samples/client/petstore/python/docs/AnimalFarm.md index fc299cf27d34..fb3b33c9c9c2 100644 --- a/samples/client/petstore/python/docs/AnimalFarm.md +++ b/samples/client/petstore/python/docs/AnimalFarm.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **value** | [**[Animal]**](Animal.md) | | +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/ApiResponse.md b/samples/client/petstore/python/docs/ApiResponse.md index 81a7d0d85227..bedefea9a9cb 100644 --- a/samples/client/petstore/python/docs/ApiResponse.md +++ b/samples/client/petstore/python/docs/ApiResponse.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **code** | **int** | | [optional] **type** | **str** | | [optional] **message** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md index 6ab77963788b..11cd25c98ee4 100644 --- a/samples/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md +++ b/samples/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **array_array_number** | **[[float]]** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/ArrayOfNumberOnly.md b/samples/client/petstore/python/docs/ArrayOfNumberOnly.md index ebc65a54ba7e..1e9bb12e4e8b 100644 --- a/samples/client/petstore/python/docs/ArrayOfNumberOnly.md +++ b/samples/client/petstore/python/docs/ArrayOfNumberOnly.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **array_number** | **[float]** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/ArrayTest.md b/samples/client/petstore/python/docs/ArrayTest.md index 4e1bda8fc3af..9eac1f8874c4 100644 --- a/samples/client/petstore/python/docs/ArrayTest.md +++ b/samples/client/petstore/python/docs/ArrayTest.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **array_of_string** | **[str]** | | [optional] **array_array_of_integer** | **[[int]]** | | [optional] **array_array_of_model** | [**[[ReadOnlyFirst]]**](ReadOnlyFirst.md) | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/Capitalization.md b/samples/client/petstore/python/docs/Capitalization.md index 1ddeadeb3f46..df9989f8db57 100644 --- a/samples/client/petstore/python/docs/Capitalization.md +++ b/samples/client/petstore/python/docs/Capitalization.md @@ -10,6 +10,7 @@ Name | Type | Description | Notes **capital_snake** | **str** | | [optional] **sca_eth_flow_points** | **str** | | [optional] **att_name** | **str** | Name of the pet | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/Cat.md b/samples/client/petstore/python/docs/Cat.md index e9ce235cd632..082715a28421 100644 --- a/samples/client/petstore/python/docs/Cat.md +++ b/samples/client/petstore/python/docs/Cat.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **class_name** | **str** | | **declawed** | **bool** | | [optional] **color** | **str** | | [optional] if omitted the server will use the default value of "red" +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/CatAllOf.md b/samples/client/petstore/python/docs/CatAllOf.md index 0ff7809a99ac..6fd1390a749b 100644 --- a/samples/client/petstore/python/docs/CatAllOf.md +++ b/samples/client/petstore/python/docs/CatAllOf.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **declawed** | **bool** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/Category.md b/samples/client/petstore/python/docs/Category.md index 940f6a45e641..7650eccafba5 100644 --- a/samples/client/petstore/python/docs/Category.md +++ b/samples/client/petstore/python/docs/Category.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | defaults to "default-name" **id** | **int** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/Child.md b/samples/client/petstore/python/docs/Child.md index eb4392445710..6bf6903fb203 100644 --- a/samples/client/petstore/python/docs/Child.md +++ b/samples/client/petstore/python/docs/Child.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **radio_waves** | **bool** | | [optional] **tele_vision** | **bool** | | [optional] **inter_net** | **bool** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/ChildAllOf.md b/samples/client/petstore/python/docs/ChildAllOf.md index f9ae99c7c157..bae8ced90067 100644 --- a/samples/client/petstore/python/docs/ChildAllOf.md +++ b/samples/client/petstore/python/docs/ChildAllOf.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **inter_net** | **bool** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/ChildCat.md b/samples/client/petstore/python/docs/ChildCat.md index 9e3a0fb4b51a..513903ac5793 100644 --- a/samples/client/petstore/python/docs/ChildCat.md +++ b/samples/client/petstore/python/docs/ChildCat.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **pet_type** | **str** | | **name** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/ChildCatAllOf.md b/samples/client/petstore/python/docs/ChildCatAllOf.md index c5883b9a87c8..c5b2f58f28ce 100644 --- a/samples/client/petstore/python/docs/ChildCatAllOf.md +++ b/samples/client/petstore/python/docs/ChildCatAllOf.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/ChildDog.md b/samples/client/petstore/python/docs/ChildDog.md index 9a6e5b372664..e5b410ce1e79 100644 --- a/samples/client/petstore/python/docs/ChildDog.md +++ b/samples/client/petstore/python/docs/ChildDog.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **pet_type** | **str** | | **bark** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/ChildDogAllOf.md b/samples/client/petstore/python/docs/ChildDogAllOf.md index 673050667cb3..45928c57ef2a 100644 --- a/samples/client/petstore/python/docs/ChildDogAllOf.md +++ b/samples/client/petstore/python/docs/ChildDogAllOf.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **bark** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/ChildLizard.md b/samples/client/petstore/python/docs/ChildLizard.md index e881ee0a1d1b..d2e22826e77f 100644 --- a/samples/client/petstore/python/docs/ChildLizard.md +++ b/samples/client/petstore/python/docs/ChildLizard.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **pet_type** | **str** | | **loves_rocks** | **bool** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/ChildLizardAllOf.md b/samples/client/petstore/python/docs/ChildLizardAllOf.md index 6e2b70c01505..6effcfd9313f 100644 --- a/samples/client/petstore/python/docs/ChildLizardAllOf.md +++ b/samples/client/petstore/python/docs/ChildLizardAllOf.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **loves_rocks** | **bool** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/ClassModel.md b/samples/client/petstore/python/docs/ClassModel.md index 48ed7cbf2ff0..6605a16d74a9 100644 --- a/samples/client/petstore/python/docs/ClassModel.md +++ b/samples/client/petstore/python/docs/ClassModel.md @@ -6,6 +6,7 @@ Model for testing model with \"_class\" property Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **_class** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/Client.md b/samples/client/petstore/python/docs/Client.md index c3986008d6c3..1b293140f348 100644 --- a/samples/client/petstore/python/docs/Client.md +++ b/samples/client/petstore/python/docs/Client.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **client** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/Dog.md b/samples/client/petstore/python/docs/Dog.md index 7065c4c983d9..51b5b32bdacb 100644 --- a/samples/client/petstore/python/docs/Dog.md +++ b/samples/client/petstore/python/docs/Dog.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **class_name** | **str** | | **breed** | **str** | | [optional] **color** | **str** | | [optional] if omitted the server will use the default value of "red" +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/DogAllOf.md b/samples/client/petstore/python/docs/DogAllOf.md index 6382bbd80671..2907a9fd5c43 100644 --- a/samples/client/petstore/python/docs/DogAllOf.md +++ b/samples/client/petstore/python/docs/DogAllOf.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **breed** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/EnumArrays.md b/samples/client/petstore/python/docs/EnumArrays.md index 9be5c645a809..ad4e9d2fcb7c 100644 --- a/samples/client/petstore/python/docs/EnumArrays.md +++ b/samples/client/petstore/python/docs/EnumArrays.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **just_symbol** | **str** | | [optional] **array_enum** | **[str]** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/EnumClass.md b/samples/client/petstore/python/docs/EnumClass.md index a1f9aae58190..39bb0e1644c5 100644 --- a/samples/client/petstore/python/docs/EnumClass.md +++ b/samples/client/petstore/python/docs/EnumClass.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **value** | **str** | | defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/EnumTest.md b/samples/client/petstore/python/docs/EnumTest.md index eb8842241390..052596bfd045 100644 --- a/samples/client/petstore/python/docs/EnumTest.md +++ b/samples/client/petstore/python/docs/EnumTest.md @@ -9,6 +9,7 @@ Name | Type | Description | Notes **enum_integer** | **int** | | [optional] **enum_number** | **float** | | [optional] **string_enum** | [**StringEnum**](StringEnum.md) | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/File.md b/samples/client/petstore/python/docs/File.md index 63b1d1a65186..f84547d19331 100644 --- a/samples/client/petstore/python/docs/File.md +++ b/samples/client/petstore/python/docs/File.md @@ -6,6 +6,7 @@ Must be named `File` for test. Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **source_uri** | **str** | Test capitalization | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/FileSchemaTestClass.md b/samples/client/petstore/python/docs/FileSchemaTestClass.md index caf2440821da..4572aa0905b3 100644 --- a/samples/client/petstore/python/docs/FileSchemaTestClass.md +++ b/samples/client/petstore/python/docs/FileSchemaTestClass.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **file** | [**File**](File.md) | | [optional] **files** | [**[File]**](File.md) | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/FormatTest.md b/samples/client/petstore/python/docs/FormatTest.md index aef09bfcc83e..dbb4c3e6683d 100644 --- a/samples/client/petstore/python/docs/FormatTest.md +++ b/samples/client/petstore/python/docs/FormatTest.md @@ -17,6 +17,7 @@ Name | Type | Description | Notes **binary** | **file_type** | | [optional] **date_time** | **datetime** | | [optional] **uuid** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/Grandparent.md b/samples/client/petstore/python/docs/Grandparent.md index b6d80a719457..af143938ab51 100644 --- a/samples/client/petstore/python/docs/Grandparent.md +++ b/samples/client/petstore/python/docs/Grandparent.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **radio_waves** | **bool** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/GrandparentAnimal.md b/samples/client/petstore/python/docs/GrandparentAnimal.md index 15db0708bb1a..a1c340378106 100644 --- a/samples/client/petstore/python/docs/GrandparentAnimal.md +++ b/samples/client/petstore/python/docs/GrandparentAnimal.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **pet_type** | **str** | | +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/HasOnlyReadOnly.md b/samples/client/petstore/python/docs/HasOnlyReadOnly.md index 0e1334519a8b..88bc03d4ff5c 100644 --- a/samples/client/petstore/python/docs/HasOnlyReadOnly.md +++ b/samples/client/petstore/python/docs/HasOnlyReadOnly.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **bar** | **str** | | [optional] [readonly] **foo** | **str** | | [optional] [readonly] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/List.md b/samples/client/petstore/python/docs/List.md index 4b60956971aa..13f2694de358 100644 --- a/samples/client/petstore/python/docs/List.md +++ b/samples/client/petstore/python/docs/List.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **_123_list** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/MapTest.md b/samples/client/petstore/python/docs/MapTest.md index 15228ee1f282..e6584f3811e0 100644 --- a/samples/client/petstore/python/docs/MapTest.md +++ b/samples/client/petstore/python/docs/MapTest.md @@ -8,6 +8,7 @@ Name | Type | Description | Notes **map_of_enum_string** | **{str: (str,)}** | | [optional] **direct_map** | **{str: (bool,)}** | | [optional] **indirect_map** | [**StringBooleanMap**](StringBooleanMap.md) | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md index f489944a20af..f32c4e04134b 100644 --- a/samples/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **uuid** | **str** | | [optional] **date_time** | **datetime** | | [optional] **map** | [**{str: (Animal,)}**](Animal.md) | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/Model200Response.md b/samples/client/petstore/python/docs/Model200Response.md index c958bd4b33f8..f7ef7d79acf6 100644 --- a/samples/client/petstore/python/docs/Model200Response.md +++ b/samples/client/petstore/python/docs/Model200Response.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **int** | | [optional] **_class** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/ModelReturn.md b/samples/client/petstore/python/docs/ModelReturn.md index 043e9d466fab..75fb39a88698 100644 --- a/samples/client/petstore/python/docs/ModelReturn.md +++ b/samples/client/petstore/python/docs/ModelReturn.md @@ -6,6 +6,7 @@ Model for testing reserved words Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **_return** | **int** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/Name.md b/samples/client/petstore/python/docs/Name.md index 3be719cdbfba..6e58fae6d0bb 100644 --- a/samples/client/petstore/python/docs/Name.md +++ b/samples/client/petstore/python/docs/Name.md @@ -9,6 +9,7 @@ Name | Type | Description | Notes **snake_case** | **int** | | [optional] [readonly] **_property** | **str** | | [optional] **_123_number** | **int** | | [optional] [readonly] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/NumberOnly.md b/samples/client/petstore/python/docs/NumberOnly.md index 37195c5d8994..172e86163a44 100644 --- a/samples/client/petstore/python/docs/NumberOnly.md +++ b/samples/client/petstore/python/docs/NumberOnly.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **just_number** | **float** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/NumberWithValidations.md b/samples/client/petstore/python/docs/NumberWithValidations.md index 119e0f678239..cc6f77c152c6 100644 --- a/samples/client/petstore/python/docs/NumberWithValidations.md +++ b/samples/client/petstore/python/docs/NumberWithValidations.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **value** | **float** | | +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/ObjectModelWithRefProps.md b/samples/client/petstore/python/docs/ObjectModelWithRefProps.md index 5ff4e52033d6..a0d15f4bbd15 100644 --- a/samples/client/petstore/python/docs/ObjectModelWithRefProps.md +++ b/samples/client/petstore/python/docs/ObjectModelWithRefProps.md @@ -8,6 +8,7 @@ Name | Type | Description | Notes **my_number** | [**NumberWithValidations**](NumberWithValidations.md) | | [optional] **my_string** | **str** | | [optional] **my_boolean** | **bool** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/Order.md b/samples/client/petstore/python/docs/Order.md index d29e1a381de8..0423082932d5 100644 --- a/samples/client/petstore/python/docs/Order.md +++ b/samples/client/petstore/python/docs/Order.md @@ -10,6 +10,7 @@ Name | Type | Description | Notes **ship_date** | **datetime** | | [optional] **status** | **str** | Order Status | [optional] **complete** | **bool** | | [optional] if omitted the server will use the default value of False +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/Parent.md b/samples/client/petstore/python/docs/Parent.md index 9d3f02d68b31..9db770844ee1 100644 --- a/samples/client/petstore/python/docs/Parent.md +++ b/samples/client/petstore/python/docs/Parent.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **radio_waves** | **bool** | | [optional] **tele_vision** | **bool** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/ParentAllOf.md b/samples/client/petstore/python/docs/ParentAllOf.md index 569a5e4af14f..84ac2c066eed 100644 --- a/samples/client/petstore/python/docs/ParentAllOf.md +++ b/samples/client/petstore/python/docs/ParentAllOf.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **tele_vision** | **bool** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/ParentPet.md b/samples/client/petstore/python/docs/ParentPet.md index 09e409c8fcf1..111ada88b3d1 100644 --- a/samples/client/petstore/python/docs/ParentPet.md +++ b/samples/client/petstore/python/docs/ParentPet.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **pet_type** | **str** | | +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/Pet.md b/samples/client/petstore/python/docs/Pet.md index 6e78495272e4..e0b129784564 100644 --- a/samples/client/petstore/python/docs/Pet.md +++ b/samples/client/petstore/python/docs/Pet.md @@ -10,6 +10,7 @@ Name | Type | Description | Notes **category** | [**Category**](Category.md) | | [optional] **tags** | [**[Tag]**](Tag.md) | | [optional] **status** | **str** | pet status in the store | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/Player.md b/samples/client/petstore/python/docs/Player.md index 2014198aa1bd..97441ae316bb 100644 --- a/samples/client/petstore/python/docs/Player.md +++ b/samples/client/petstore/python/docs/Player.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | **enemy_player** | [**Player**](Player.md) | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/ReadOnlyFirst.md b/samples/client/petstore/python/docs/ReadOnlyFirst.md index 53b4c61d8445..ba39ec3d04e4 100644 --- a/samples/client/petstore/python/docs/ReadOnlyFirst.md +++ b/samples/client/petstore/python/docs/ReadOnlyFirst.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **bar** | **str** | | [optional] [readonly] **baz** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/SpecialModelName.md b/samples/client/petstore/python/docs/SpecialModelName.md index 268e1134192d..4a1c86ff4de0 100644 --- a/samples/client/petstore/python/docs/SpecialModelName.md +++ b/samples/client/petstore/python/docs/SpecialModelName.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **special_property_name** | **int** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/StringEnum.md b/samples/client/petstore/python/docs/StringEnum.md index bb195ec0e453..1ac6df2fb797 100644 --- a/samples/client/petstore/python/docs/StringEnum.md +++ b/samples/client/petstore/python/docs/StringEnum.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **value** | **str** | | must be one of ["placed", "approved", "delivered", ] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/Tag.md b/samples/client/petstore/python/docs/Tag.md index b9fe1e0944c4..bfe06d1c5bfe 100644 --- a/samples/client/petstore/python/docs/Tag.md +++ b/samples/client/petstore/python/docs/Tag.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **id** | **int** | | [optional] **name** | **str** | | [optional] **full_name** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/TypeHolderDefault.md b/samples/client/petstore/python/docs/TypeHolderDefault.md index 904915aec010..f15c61cc4618 100644 --- a/samples/client/petstore/python/docs/TypeHolderDefault.md +++ b/samples/client/petstore/python/docs/TypeHolderDefault.md @@ -12,6 +12,7 @@ Name | Type | Description | Notes **bool_item** | **bool** | | defaults to True **date_item** | **date** | | [optional] **datetime_item** | **datetime** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/TypeHolderExample.md b/samples/client/petstore/python/docs/TypeHolderExample.md index d2954c64dcef..d707ca3af203 100644 --- a/samples/client/petstore/python/docs/TypeHolderExample.md +++ b/samples/client/petstore/python/docs/TypeHolderExample.md @@ -10,6 +10,7 @@ Name | Type | Description | Notes **string_item** | **str** | | defaults to "what" **number_item** | **float** | | defaults to 1.234 **integer_item** | **int** | | defaults to -2 +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/User.md b/samples/client/petstore/python/docs/User.md index b0079f591b6e..8e677b63cca6 100644 --- a/samples/client/petstore/python/docs/User.md +++ b/samples/client/petstore/python/docs/User.md @@ -12,6 +12,7 @@ Name | Type | Description | Notes **password** | **str** | | [optional] **phone** | **str** | | [optional] **user_status** | **int** | User Status | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/XmlItem.md b/samples/client/petstore/python/docs/XmlItem.md index ea3d7f92804b..9852234a7367 100644 --- a/samples/client/petstore/python/docs/XmlItem.md +++ b/samples/client/petstore/python/docs/XmlItem.md @@ -33,6 +33,7 @@ Name | Type | Description | Notes **prefix_ns_boolean** | **bool** | | [optional] **prefix_ns_array** | **[int]** | | [optional] **prefix_ns_wrapped_array** | **[int]** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_any_type.py b/samples/client/petstore/python/petstore_api/model/additional_properties_any_type.py index 4531d8f2d862..34ae88833fbe 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_any_type.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_any_type.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesAnyType(ModelNormal): @@ -63,7 +66,7 @@ def additional_properties_type(): This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ - return (bool, date, datetime, dict, float, int, list, str,) # noqa: E501 + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -90,8 +93,85 @@ def discriminator(): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesAnyType - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_array.py b/samples/client/petstore/python/petstore_api/model/additional_properties_array.py index 4a35500c63f3..55f44f411c27 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_array.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_array.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesArray(ModelNormal): @@ -63,7 +66,7 @@ def additional_properties_type(): This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ - return ([bool, date, datetime, dict, float, int, list, str],) # noqa: E501 + return ([bool, date, datetime, dict, float, int, list, str, none_type],) # noqa: E501 _nullable = False @@ -90,8 +93,85 @@ def discriminator(): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesArray - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_boolean.py b/samples/client/petstore/python/petstore_api/model/additional_properties_boolean.py index ca129b766ec5..b9c5c258e3cc 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_boolean.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_boolean.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesBoolean(ModelNormal): @@ -90,8 +93,85 @@ def discriminator(): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesBoolean - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_class.py b/samples/client/petstore/python/petstore_api/model/additional_properties_class.py index 743f3be54d44..7e4d3d93c5f5 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_class.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_class.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesClass(ModelNormal): @@ -57,7 +60,13 @@ class AdditionalPropertiesClass(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -77,12 +86,12 @@ def openapi_types(): 'map_integer': ({str: (int,)},), # noqa: E501 'map_boolean': ({str: (bool,)},), # noqa: E501 'map_array_integer': ({str: ([int],)},), # noqa: E501 - 'map_array_anytype': ({str: ([bool, date, datetime, dict, float, int, list, str],)},), # noqa: E501 + 'map_array_anytype': ({str: ([bool, date, datetime, dict, float, int, list, str, none_type],)},), # noqa: E501 'map_map_string': ({str: ({str: (str,)},)},), # noqa: E501 - 'map_map_anytype': ({str: ({str: (bool, date, datetime, dict, float, int, list, str,)},)},), # noqa: E501 - 'anytype_1': (bool, date, datetime, dict, float, int, list, str,), # noqa: E501 - 'anytype_2': (bool, date, datetime, dict, float, int, list, str,), # noqa: E501 - 'anytype_3': (bool, date, datetime, dict, float, int, list, str,), # noqa: E501 + 'map_map_anytype': ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type,)},)},), # noqa: E501 + 'anytype_1': (bool, date, datetime, dict, float, int, list, str, none_type,), # noqa: E501 + 'anytype_2': (bool, date, datetime, dict, float, int, list, str, none_type,), # noqa: E501 + 'anytype_3': (bool, date, datetime, dict, float, int, list, str, none_type,), # noqa: E501 } @cached_property @@ -104,8 +113,95 @@ def discriminator(): 'anytype_3': 'anytype_3', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_string ({str: (str,)}): [optional] # noqa: E501 + map_number ({str: (float,)}): [optional] # noqa: E501 + map_integer ({str: (int,)}): [optional] # noqa: E501 + map_boolean ({str: (bool,)}): [optional] # noqa: E501 + map_array_integer ({str: ([int],)}): [optional] # noqa: E501 + map_array_anytype ({str: ([bool, date, datetime, dict, float, int, list, str, none_type],)}): [optional] # noqa: E501 + map_map_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 + map_map_anytype ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type,)},)}): [optional] # noqa: E501 + anytype_1 (bool, date, datetime, dict, float, int, list, str, none_type): [optional] # noqa: E501 + anytype_2 (bool, date, datetime, dict, float, int, list, str, none_type): no type is set for this. [optional] # noqa: E501 + anytype_3 (bool, date, datetime, dict, float, int, list, str, none_type): because of a bug in swagger-parser, this should have values {str: (str, int, float...)} but instead we get any type. See https://github.com/swagger-api/swagger-parser/issues/1378. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -155,12 +251,12 @@ def __init__(self, *args, **kwargs): # noqa: E501 map_integer ({str: (int,)}): [optional] # noqa: E501 map_boolean ({str: (bool,)}): [optional] # noqa: E501 map_array_integer ({str: ([int],)}): [optional] # noqa: E501 - map_array_anytype ({str: ([bool, date, datetime, dict, float, int, list, str],)}): [optional] # noqa: E501 + map_array_anytype ({str: ([bool, date, datetime, dict, float, int, list, str, none_type],)}): [optional] # noqa: E501 map_map_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 - map_map_anytype ({str: ({str: (bool, date, datetime, dict, float, int, list, str,)},)}): [optional] # noqa: E501 - anytype_1 (bool, date, datetime, dict, float, int, list, str): [optional] # noqa: E501 - anytype_2 (bool, date, datetime, dict, float, int, list, str): [optional] # noqa: E501 - anytype_3 (bool, date, datetime, dict, float, int, list, str): [optional] # noqa: E501 + map_map_anytype ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type,)},)}): [optional] # noqa: E501 + anytype_1 (bool, date, datetime, dict, float, int, list, str, none_type): [optional] # noqa: E501 + anytype_2 (bool, date, datetime, dict, float, int, list, str, none_type): no type is set for this. [optional] # noqa: E501 + anytype_3 (bool, date, datetime, dict, float, int, list, str, none_type): because of a bug in swagger-parser, this should have values {str: (str, int, float...)} but instead we get any type. See https://github.com/swagger-api/swagger-parser/issues/1378. [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -194,3 +290,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_integer.py b/samples/client/petstore/python/petstore_api/model/additional_properties_integer.py index 87d78bf36005..f6f80f89c7ad 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_integer.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_integer.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesInteger(ModelNormal): @@ -90,8 +93,85 @@ def discriminator(): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesInteger - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_number.py b/samples/client/petstore/python/petstore_api/model/additional_properties_number.py index b10bd036ff3f..6c094699462a 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_number.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_number.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesNumber(ModelNormal): @@ -90,8 +93,85 @@ def discriminator(): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesNumber - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_object.py b/samples/client/petstore/python/petstore_api/model/additional_properties_object.py index 40e80e16044d..1fa671aff9b2 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_object.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_object.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesObject(ModelNormal): @@ -63,7 +66,7 @@ def additional_properties_type(): This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ - return ({str: (bool, date, datetime, dict, float, int, list, str,)},) # noqa: E501 + return ({str: (bool, date, datetime, dict, float, int, list, str, none_type,)},) # noqa: E501 _nullable = False @@ -90,8 +93,85 @@ def discriminator(): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesObject - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_string.py b/samples/client/petstore/python/petstore_api/model/additional_properties_string.py index 7f1f94aa6b6b..0afa8a9e6376 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_string.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_string.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesString(ModelNormal): @@ -90,8 +93,85 @@ def discriminator(): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesString - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/animal.py b/samples/client/petstore/python/petstore_api/model/animal.py index a3d48b6ea975..fda6c283ebdc 100644 --- a/samples/client/petstore/python/petstore_api/model/animal.py +++ b/samples/client/petstore/python/petstore_api/model/animal.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.cat import Cat @@ -63,7 +66,14 @@ class Animal(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -99,8 +109,89 @@ def discriminator(): 'color': 'color', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """Animal - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -183,3 +274,6 @@ def __init__(self, class_name, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/animal_farm.py b/samples/client/petstore/python/petstore_api/model/animal_farm.py index 838b18a12970..59bde51a2907 100644 --- a/samples/client/petstore/python/petstore_api/model/animal_farm.py +++ b/samples/client/petstore/python/petstore_api/model/animal_farm.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -57,7 +60,14 @@ class AnimalFarm(ModelSimple): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -83,6 +93,8 @@ def discriminator(): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -182,3 +194,97 @@ def __init__(self, *args, **kwargs): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """AnimalFarm - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] ([Animal]): # noqa: E501 + + Keyword Args: + value ([Animal]): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/client/petstore/python/petstore_api/model/api_response.py b/samples/client/petstore/python/petstore_api/model/api_response.py index 01e2175b8004..d1f3b363bef5 100644 --- a/samples/client/petstore/python/petstore_api/model/api_response.py +++ b/samples/client/petstore/python/petstore_api/model/api_response.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ApiResponse(ModelNormal): @@ -57,7 +60,13 @@ class ApiResponse(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -88,8 +97,87 @@ def discriminator(): 'message': 'message', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ApiResponse - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + code (int): [optional] # noqa: E501 + type (str): [optional] # noqa: E501 + message (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +258,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py b/samples/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py index 008b74dd42a3..16d9bda29f1f 100644 --- a/samples/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py +++ b/samples/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ArrayOfArrayOfNumberOnly(ModelNormal): @@ -57,7 +60,13 @@ class ArrayOfArrayOfNumberOnly(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'array_array_number': 'ArrayArrayNumber', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayOfArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_array_number ([[float]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/array_of_number_only.py b/samples/client/petstore/python/petstore_api/model/array_of_number_only.py index f2e080bc258e..0e44ab61aff5 100644 --- a/samples/client/petstore/python/petstore_api/model/array_of_number_only.py +++ b/samples/client/petstore/python/petstore_api/model/array_of_number_only.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ArrayOfNumberOnly(ModelNormal): @@ -57,7 +60,13 @@ class ArrayOfNumberOnly(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'array_number': 'ArrayNumber', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_number ([float]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/array_test.py b/samples/client/petstore/python/petstore_api/model/array_test.py index ac42b07b93c9..64c180d11bc5 100644 --- a/samples/client/petstore/python/petstore_api/model/array_test.py +++ b/samples/client/petstore/python/petstore_api/model/array_test.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.read_only_first import ReadOnlyFirst @@ -61,7 +64,14 @@ class ArrayTest(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -93,8 +103,87 @@ def discriminator(): 'array_array_of_model': 'array_array_of_model', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_of_string ([str]): [optional] # noqa: E501 + array_array_of_integer ([[int]]): [optional] # noqa: E501 + array_array_of_model ([[ReadOnlyFirst]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -175,3 +264,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/capitalization.py b/samples/client/petstore/python/petstore_api/model/capitalization.py index 710c17e51a56..2f1323481dca 100644 --- a/samples/client/petstore/python/petstore_api/model/capitalization.py +++ b/samples/client/petstore/python/petstore_api/model/capitalization.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Capitalization(ModelNormal): @@ -57,7 +60,13 @@ class Capitalization(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -94,8 +103,90 @@ def discriminator(): 'att_name': 'ATT_NAME', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Capitalization - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + small_camel (str): [optional] # noqa: E501 + capital_camel (str): [optional] # noqa: E501 + small_snake (str): [optional] # noqa: E501 + capital_snake (str): [optional] # noqa: E501 + sca_eth_flow_points (str): [optional] # noqa: E501 + att_name (str): Name of the pet . [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -179,3 +270,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/cat.py b/samples/client/petstore/python/petstore_api/model/cat.py index 8b5c46413b99..be46fe5abd8c 100644 --- a/samples/client/petstore/python/petstore_api/model/cat.py +++ b/samples/client/petstore/python/petstore_api/model/cat.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -63,7 +66,14 @@ class Cat(ModelComposed): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -98,6 +108,100 @@ def discriminator(): 'color': 'color', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Cat - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + declawed (bool): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -111,13 +215,11 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, class_name, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """Cat - a model defined in OpenAPI - Args: - class_name (str): - Keyword Args: + class_name (str): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -182,29 +284,24 @@ def __init__(self, class_name, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'class_name': class_name, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python/petstore_api/model/cat_all_of.py b/samples/client/petstore/python/petstore_api/model/cat_all_of.py index 50b046510dfa..a5bef948f72b 100644 --- a/samples/client/petstore/python/petstore_api/model/cat_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/cat_all_of.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class CatAllOf(ModelNormal): @@ -57,7 +60,13 @@ class CatAllOf(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'declawed': 'declawed', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """CatAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + declawed (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/category.py b/samples/client/petstore/python/petstore_api/model/category.py index ed167471d356..b40329c9424d 100644 --- a/samples/client/petstore/python/petstore_api/model/category.py +++ b/samples/client/petstore/python/petstore_api/model/category.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Category(ModelNormal): @@ -57,7 +60,13 @@ class Category(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -86,8 +95,90 @@ def discriminator(): 'id': 'id', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Category - a model defined in OpenAPI + + Args: + + Keyword Args: + name (str): defaults to "default-name" # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + """ + + name = kwargs.get('name', "default-name") + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -171,3 +262,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/child.py b/samples/client/petstore/python/petstore_api/model/child.py index c8f0a70a1931..556f58a84d20 100644 --- a/samples/client/petstore/python/petstore_api/model/child.py +++ b/samples/client/petstore/python/petstore_api/model/child.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_all_of import ChildAllOf @@ -63,7 +66,14 @@ class Child(ModelComposed): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -95,6 +105,100 @@ def discriminator(): 'inter_net': 'interNet', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Child - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + radio_waves (bool): [optional] # noqa: E501 + tele_vision (bool): [optional] # noqa: E501 + inter_net (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -177,28 +281,24 @@ def __init__(self, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python/petstore_api/model/child_all_of.py b/samples/client/petstore/python/petstore_api/model/child_all_of.py index 2339e520bd65..e38d28f52d1b 100644 --- a/samples/client/petstore/python/petstore_api/model/child_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/child_all_of.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ChildAllOf(ModelNormal): @@ -57,7 +60,13 @@ class ChildAllOf(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'inter_net': 'interNet', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + inter_net (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/child_cat.py b/samples/client/petstore/python/petstore_api/model/child_cat.py index a7d52b48e8ac..3644df82fc54 100644 --- a/samples/client/petstore/python/petstore_api/model/child_cat.py +++ b/samples/client/petstore/python/petstore_api/model/child_cat.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_cat_all_of import ChildCatAllOf @@ -63,7 +66,14 @@ class ChildCat(ModelComposed): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -96,6 +106,99 @@ def discriminator(): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildCat - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -109,13 +212,11 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, pet_type, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """ChildCat - a model defined in OpenAPI - Args: - pet_type (str): - Keyword Args: + pet_type (str): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -179,29 +280,24 @@ def __init__(self, pet_type, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'pet_type': pet_type, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python/petstore_api/model/child_cat_all_of.py b/samples/client/petstore/python/petstore_api/model/child_cat_all_of.py index f0f1a1ae6bd4..48b725d7c3c6 100644 --- a/samples/client/petstore/python/petstore_api/model/child_cat_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/child_cat_all_of.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ChildCatAllOf(ModelNormal): @@ -57,7 +60,13 @@ class ChildCatAllOf(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildCatAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/child_dog.py b/samples/client/petstore/python/petstore_api/model/child_dog.py index 2bc0882ac2a9..65f1a37e3837 100644 --- a/samples/client/petstore/python/petstore_api/model/child_dog.py +++ b/samples/client/petstore/python/petstore_api/model/child_dog.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_dog_all_of import ChildDogAllOf @@ -63,7 +66,14 @@ class ChildDog(ModelComposed): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -96,6 +106,99 @@ def discriminator(): 'bark': 'bark', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildDog - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bark (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -109,13 +212,11 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, pet_type, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """ChildDog - a model defined in OpenAPI - Args: - pet_type (str): - Keyword Args: + pet_type (str): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -179,29 +280,24 @@ def __init__(self, pet_type, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'pet_type': pet_type, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python/petstore_api/model/child_dog_all_of.py b/samples/client/petstore/python/petstore_api/model/child_dog_all_of.py index d460b68b3d3a..40d4f048f87e 100644 --- a/samples/client/petstore/python/petstore_api/model/child_dog_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/child_dog_all_of.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ChildDogAllOf(ModelNormal): @@ -57,7 +60,13 @@ class ChildDogAllOf(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'bark': 'bark', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildDogAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bark (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/child_lizard.py b/samples/client/petstore/python/petstore_api/model/child_lizard.py index 6142b9c751fe..cfb0e5426f74 100644 --- a/samples/client/petstore/python/petstore_api/model/child_lizard.py +++ b/samples/client/petstore/python/petstore_api/model/child_lizard.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_lizard_all_of import ChildLizardAllOf @@ -63,7 +66,14 @@ class ChildLizard(ModelComposed): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -96,6 +106,99 @@ def discriminator(): 'loves_rocks': 'lovesRocks', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildLizard - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + loves_rocks (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -109,13 +212,11 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, pet_type, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """ChildLizard - a model defined in OpenAPI - Args: - pet_type (str): - Keyword Args: + pet_type (str): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -179,29 +280,24 @@ def __init__(self, pet_type, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'pet_type': pet_type, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python/petstore_api/model/child_lizard_all_of.py b/samples/client/petstore/python/petstore_api/model/child_lizard_all_of.py index 669b9338d796..b0e9771c5800 100644 --- a/samples/client/petstore/python/petstore_api/model/child_lizard_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/child_lizard_all_of.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ChildLizardAllOf(ModelNormal): @@ -57,7 +60,13 @@ class ChildLizardAllOf(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'loves_rocks': 'lovesRocks', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildLizardAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + loves_rocks (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/class_model.py b/samples/client/petstore/python/petstore_api/model/class_model.py index 18c16f89f908..a3f2b58f87f3 100644 --- a/samples/client/petstore/python/petstore_api/model/class_model.py +++ b/samples/client/petstore/python/petstore_api/model/class_model.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ClassModel(ModelNormal): @@ -57,7 +60,13 @@ class ClassModel(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): '_class': '_class', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ClassModel - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/client.py b/samples/client/petstore/python/petstore_api/model/client.py index da615c547731..3dca32f7926b 100644 --- a/samples/client/petstore/python/petstore_api/model/client.py +++ b/samples/client/petstore/python/petstore_api/model/client.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Client(ModelNormal): @@ -57,7 +60,13 @@ class Client(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'client': 'client', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Client - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + client (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/dog.py b/samples/client/petstore/python/petstore_api/model/dog.py index e9c201c983bb..4a20dafa46cc 100644 --- a/samples/client/petstore/python/petstore_api/model/dog.py +++ b/samples/client/petstore/python/petstore_api/model/dog.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -63,7 +66,14 @@ class Dog(ModelComposed): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -98,6 +108,100 @@ def discriminator(): 'color': 'color', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Dog - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + breed (str): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -111,13 +215,11 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, class_name, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """Dog - a model defined in OpenAPI - Args: - class_name (str): - Keyword Args: + class_name (str): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -182,29 +284,24 @@ def __init__(self, class_name, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'class_name': class_name, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python/petstore_api/model/dog_all_of.py b/samples/client/petstore/python/petstore_api/model/dog_all_of.py index b7b2e7db66d9..dbc36cb2c8f3 100644 --- a/samples/client/petstore/python/petstore_api/model/dog_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/dog_all_of.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class DogAllOf(ModelNormal): @@ -57,7 +60,13 @@ class DogAllOf(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'breed': 'breed', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """DogAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + breed (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/enum_arrays.py b/samples/client/petstore/python/petstore_api/model/enum_arrays.py index 43ebac57de38..da42763d9c32 100644 --- a/samples/client/petstore/python/petstore_api/model/enum_arrays.py +++ b/samples/client/petstore/python/petstore_api/model/enum_arrays.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class EnumArrays(ModelNormal): @@ -65,7 +68,13 @@ class EnumArrays(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -94,8 +103,86 @@ def discriminator(): 'array_enum': 'array_enum', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """EnumArrays - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_symbol (str): [optional] # noqa: E501 + array_enum ([str]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -175,3 +262,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/enum_class.py b/samples/client/petstore/python/petstore_api/model/enum_class.py index 14188ca31d28..a9e7723b255f 100644 --- a/samples/client/petstore/python/petstore_api/model/enum_class.py +++ b/samples/client/petstore/python/petstore_api/model/enum_class.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class EnumClass(ModelSimple): @@ -58,7 +61,13 @@ class EnumClass(ModelSimple): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -83,6 +92,8 @@ def discriminator(): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -178,3 +189,93 @@ def __init__(self, *args, **kwargs): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """EnumClass - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + + Keyword Args: + value (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = "-efg" + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/client/petstore/python/petstore_api/model/enum_test.py b/samples/client/petstore/python/petstore_api/model/enum_test.py index 79ba0f6a747c..a3f47184d1a0 100644 --- a/samples/client/petstore/python/petstore_api/model/enum_test.py +++ b/samples/client/petstore/python/petstore_api/model/enum_test.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.string_enum import StringEnum @@ -79,7 +82,14 @@ class EnumTest(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -115,8 +125,92 @@ def discriminator(): 'string_enum': 'stringEnum', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, enum_string_required, *args, **kwargs): # noqa: E501 + """EnumTest - a model defined in OpenAPI + + Args: + enum_string_required (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + enum_string (str): [optional] # noqa: E501 + enum_integer (int): [optional] # noqa: E501 + enum_number (float): [optional] # noqa: E501 + string_enum (StringEnum): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.enum_string_required = enum_string_required + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -202,3 +296,6 @@ def __init__(self, enum_string_required, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/file.py b/samples/client/petstore/python/petstore_api/model/file.py index a38cccacc6ab..849f5727dc9f 100644 --- a/samples/client/petstore/python/petstore_api/model/file.py +++ b/samples/client/petstore/python/petstore_api/model/file.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class File(ModelNormal): @@ -57,7 +60,13 @@ class File(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'source_uri': 'sourceURI', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """File - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + source_uri (str): Test capitalization. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/file_schema_test_class.py b/samples/client/petstore/python/petstore_api/model/file_schema_test_class.py index b8c519ed9c7c..f7e154e47b7c 100644 --- a/samples/client/petstore/python/petstore_api/model/file_schema_test_class.py +++ b/samples/client/petstore/python/petstore_api/model/file_schema_test_class.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.file import File @@ -61,7 +64,14 @@ class FileSchemaTestClass(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -91,8 +101,86 @@ def discriminator(): 'files': 'files', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """FileSchemaTestClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + file (File): [optional] # noqa: E501 + files ([File]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -172,3 +260,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/format_test.py b/samples/client/petstore/python/petstore_api/model/format_test.py index 494ce2646da0..1d3ef5f76b40 100644 --- a/samples/client/petstore/python/petstore_api/model/format_test.py +++ b/samples/client/petstore/python/petstore_api/model/format_test.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class FormatTest(ModelNormal): @@ -92,7 +95,13 @@ class FormatTest(ModelNormal): }, } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -143,8 +152,103 @@ def discriminator(): 'uuid': 'uuid', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, number, byte, date, password, *args, **kwargs): # noqa: E501 + """FormatTest - a model defined in OpenAPI + + Args: + number (float): + byte (str): + date (date): + password (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + integer (int): [optional] # noqa: E501 + int32 (int): [optional] # noqa: E501 + int64 (int): [optional] # noqa: E501 + float (float): [optional] # noqa: E501 + double (float): [optional] # noqa: E501 + string (str): [optional] # noqa: E501 + binary (file_type): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + uuid (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.number = number + self.byte = byte + self.date = date + self.password = password + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -241,3 +345,6 @@ def __init__(self, number, byte, date, password, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/grandparent.py b/samples/client/petstore/python/petstore_api/model/grandparent.py index a52744cc3e24..b92e3acdcf39 100644 --- a/samples/client/petstore/python/petstore_api/model/grandparent.py +++ b/samples/client/petstore/python/petstore_api/model/grandparent.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Grandparent(ModelNormal): @@ -57,7 +60,13 @@ class Grandparent(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'radio_waves': 'radioWaves', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Grandparent - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + radio_waves (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/grandparent_animal.py b/samples/client/petstore/python/petstore_api/model/grandparent_animal.py index 48d3f6d9f0b3..fd77a46211fe 100644 --- a/samples/client/petstore/python/petstore_api/model/grandparent_animal.py +++ b/samples/client/petstore/python/petstore_api/model/grandparent_animal.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_cat import ChildCat @@ -67,7 +70,14 @@ class GrandparentAnimal(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -103,8 +113,88 @@ def discriminator(): 'pet_type': 'pet_type', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, pet_type, *args, **kwargs): # noqa: E501 + """GrandparentAnimal - a model defined in OpenAPI + + Args: + pet_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.pet_type = pet_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -186,3 +276,6 @@ def __init__(self, pet_type, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/has_only_read_only.py b/samples/client/petstore/python/petstore_api/model/has_only_read_only.py index c94781ae2c46..33d1c15b58d9 100644 --- a/samples/client/petstore/python/petstore_api/model/has_only_read_only.py +++ b/samples/client/petstore/python/petstore_api/model/has_only_read_only.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class HasOnlyReadOnly(ModelNormal): @@ -57,7 +60,13 @@ class HasOnlyReadOnly(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -86,8 +95,88 @@ def discriminator(): 'foo': 'foo', # noqa: E501 } + read_only_vars = { + 'bar', # noqa: E501 + 'foo', # noqa: E501 + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """HasOnlyReadOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + foo (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +256,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/list.py b/samples/client/petstore/python/petstore_api/model/list.py index 09c762d6a794..4b71d9deec05 100644 --- a/samples/client/petstore/python/petstore_api/model/list.py +++ b/samples/client/petstore/python/petstore_api/model/list.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class List(ModelNormal): @@ -57,7 +60,13 @@ class List(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): '_123_list': '123-list', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """List - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _123_list (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/map_test.py b/samples/client/petstore/python/petstore_api/model/map_test.py index 169fb9d88ee0..39c3b180e88c 100644 --- a/samples/client/petstore/python/petstore_api/model/map_test.py +++ b/samples/client/petstore/python/petstore_api/model/map_test.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.string_boolean_map import StringBooleanMap @@ -65,7 +68,14 @@ class MapTest(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -99,8 +109,88 @@ def discriminator(): 'indirect_map': 'indirect_map', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """MapTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_map_of_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 + map_of_enum_string ({str: (str,)}): [optional] # noqa: E501 + direct_map ({str: (bool,)}): [optional] # noqa: E501 + indirect_map (StringBooleanMap): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -182,3 +272,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py index 01df80d9d62b..f46cd0b89726 100644 --- a/samples/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -61,7 +64,14 @@ class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -93,8 +103,87 @@ def discriminator(): 'map': 'map', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """MixedPropertiesAndAdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + uuid (str): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + map ({str: (Animal,)}): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -175,3 +264,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/model200_response.py b/samples/client/petstore/python/petstore_api/model/model200_response.py index 46b155b65239..41a8dee5fdf2 100644 --- a/samples/client/petstore/python/petstore_api/model/model200_response.py +++ b/samples/client/petstore/python/petstore_api/model/model200_response.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Model200Response(ModelNormal): @@ -57,7 +60,13 @@ class Model200Response(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -86,8 +95,86 @@ def discriminator(): '_class': 'class', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Model200Response - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (int): [optional] # noqa: E501 + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +254,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/model_return.py b/samples/client/petstore/python/petstore_api/model/model_return.py index 377b3507a8b3..f3720b05246f 100644 --- a/samples/client/petstore/python/petstore_api/model/model_return.py +++ b/samples/client/petstore/python/petstore_api/model/model_return.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ModelReturn(ModelNormal): @@ -57,7 +60,13 @@ class ModelReturn(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): '_return': 'return', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ModelReturn - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _return (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/name.py b/samples/client/petstore/python/petstore_api/model/name.py index 1432e185ad6b..d46618c88a14 100644 --- a/samples/client/petstore/python/petstore_api/model/name.py +++ b/samples/client/petstore/python/petstore_api/model/name.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Name(ModelNormal): @@ -57,7 +60,13 @@ class Name(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -90,8 +99,93 @@ def discriminator(): '_123_number': '123Number', # noqa: E501 } + read_only_vars = { + 'snake_case', # noqa: E501 + '_123_number', # noqa: E501 + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, *args, **kwargs): # noqa: E501 + """Name - a model defined in OpenAPI + + Args: + name (int): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + snake_case (int): [optional] # noqa: E501 + _property (str): [optional] # noqa: E501 + _123_number (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -176,3 +270,6 @@ def __init__(self, name, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/number_only.py b/samples/client/petstore/python/petstore_api/model/number_only.py index d4892dbede5b..a96d91650569 100644 --- a/samples/client/petstore/python/petstore_api/model/number_only.py +++ b/samples/client/petstore/python/petstore_api/model/number_only.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class NumberOnly(ModelNormal): @@ -57,7 +60,13 @@ class NumberOnly(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'just_number': 'JustNumber', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """NumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_number (float): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/number_with_validations.py b/samples/client/petstore/python/petstore_api/model/number_with_validations.py index 458a79459751..27bc46dbe442 100644 --- a/samples/client/petstore/python/petstore_api/model/number_with_validations.py +++ b/samples/client/petstore/python/petstore_api/model/number_with_validations.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class NumberWithValidations(ModelSimple): @@ -57,7 +60,13 @@ class NumberWithValidations(ModelSimple): }, } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -82,6 +91,8 @@ def discriminator(): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -181,3 +192,97 @@ def __init__(self, *args, **kwargs): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """NumberWithValidations - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (float): # noqa: E501 + + Keyword Args: + value (float): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/client/petstore/python/petstore_api/model/object_model_with_ref_props.py b/samples/client/petstore/python/petstore_api/model/object_model_with_ref_props.py index b1dc4bf82e2c..2ef48316f430 100644 --- a/samples/client/petstore/python/petstore_api/model/object_model_with_ref_props.py +++ b/samples/client/petstore/python/petstore_api/model/object_model_with_ref_props.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.number_with_validations import NumberWithValidations @@ -61,7 +64,14 @@ class ObjectModelWithRefProps(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -93,8 +103,87 @@ def discriminator(): 'my_boolean': 'my_boolean', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ObjectModelWithRefProps - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + my_number (NumberWithValidations): [optional] # noqa: E501 + my_string (str): [optional] # noqa: E501 + my_boolean (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -175,3 +264,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/order.py b/samples/client/petstore/python/petstore_api/model/order.py index b42f066848ab..eeefff1513f6 100644 --- a/samples/client/petstore/python/petstore_api/model/order.py +++ b/samples/client/petstore/python/petstore_api/model/order.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Order(ModelNormal): @@ -62,7 +65,13 @@ class Order(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -99,8 +108,90 @@ def discriminator(): 'complete': 'complete', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Order - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + pet_id (int): [optional] # noqa: E501 + quantity (int): [optional] # noqa: E501 + ship_date (datetime): [optional] # noqa: E501 + status (str): Order Status. [optional] # noqa: E501 + complete (bool): [optional] if omitted the server will use the default value of False # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -184,3 +275,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/parent.py b/samples/client/petstore/python/petstore_api/model/parent.py index a5e5d878d844..e43f678253de 100644 --- a/samples/client/petstore/python/petstore_api/model/parent.py +++ b/samples/client/petstore/python/petstore_api/model/parent.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.grandparent import Grandparent @@ -63,7 +66,14 @@ class Parent(ModelComposed): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -93,6 +103,99 @@ def discriminator(): 'tele_vision': 'teleVision', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Parent - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + radio_waves (bool): [optional] # noqa: E501 + tele_vision (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -174,28 +277,24 @@ def __init__(self, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python/petstore_api/model/parent_all_of.py b/samples/client/petstore/python/petstore_api/model/parent_all_of.py index 0d109f25a4c2..602e3f610a0a 100644 --- a/samples/client/petstore/python/petstore_api/model/parent_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/parent_all_of.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ParentAllOf(ModelNormal): @@ -57,7 +60,13 @@ class ParentAllOf(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'tele_vision': 'teleVision', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ParentAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + tele_vision (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/parent_pet.py b/samples/client/petstore/python/petstore_api/model/parent_pet.py index aac0ff12e86b..fd774033ee35 100644 --- a/samples/client/petstore/python/petstore_api/model/parent_pet.py +++ b/samples/client/petstore/python/petstore_api/model/parent_pet.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_cat import ChildCat @@ -67,7 +70,14 @@ class ParentPet(ModelComposed): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -102,6 +112,98 @@ def discriminator(): 'pet_type': 'pet_type', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ParentPet - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -115,13 +217,11 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, pet_type, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """ParentPet - a model defined in OpenAPI - Args: - pet_type (str): - Keyword Args: + pet_type (str): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -184,29 +284,24 @@ def __init__(self, pet_type, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'pet_type': pet_type, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/client/petstore/python/petstore_api/model/pet.py b/samples/client/petstore/python/petstore_api/model/pet.py index e9f1e30a3196..8946f6d4bea3 100644 --- a/samples/client/petstore/python/petstore_api/model/pet.py +++ b/samples/client/petstore/python/petstore_api/model/pet.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.category import Category @@ -68,7 +71,14 @@ class Pet(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -106,8 +116,94 @@ def discriminator(): 'status': 'status', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, photo_urls, *args, **kwargs): # noqa: E501 + """Pet - a model defined in OpenAPI + + Args: + name (str): + photo_urls ([str]): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + category (Category): [optional] # noqa: E501 + tags ([Tag]): [optional] # noqa: E501 + status (str): pet status in the store. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + self.photo_urls = photo_urls + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -195,3 +291,6 @@ def __init__(self, name, photo_urls, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/player.py b/samples/client/petstore/python/petstore_api/model/player.py index 6e4485fb6500..50ab531029b8 100644 --- a/samples/client/petstore/python/petstore_api/model/player.py +++ b/samples/client/petstore/python/petstore_api/model/player.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Player(ModelNormal): @@ -57,7 +60,13 @@ class Player(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -86,8 +95,89 @@ def discriminator(): 'enemy_player': 'enemyPlayer', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, *args, **kwargs): # noqa: E501 + """Player - a model defined in OpenAPI + + Args: + name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + enemy_player (Player): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +260,6 @@ def __init__(self, name, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/read_only_first.py b/samples/client/petstore/python/petstore_api/model/read_only_first.py index 5c68eab91ea3..38cb5e2634f6 100644 --- a/samples/client/petstore/python/petstore_api/model/read_only_first.py +++ b/samples/client/petstore/python/petstore_api/model/read_only_first.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ReadOnlyFirst(ModelNormal): @@ -57,7 +60,13 @@ class ReadOnlyFirst(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -86,8 +95,87 @@ def discriminator(): 'baz': 'baz', # noqa: E501 } + read_only_vars = { + 'bar', # noqa: E501 + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ReadOnlyFirst - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + baz (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +255,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/special_model_name.py b/samples/client/petstore/python/petstore_api/model/special_model_name.py index 823e77596636..cc2e49f6bcb0 100644 --- a/samples/client/petstore/python/petstore_api/model/special_model_name.py +++ b/samples/client/petstore/python/petstore_api/model/special_model_name.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class SpecialModelName(ModelNormal): @@ -57,7 +60,13 @@ class SpecialModelName(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'special_property_name': '$special[property.name]', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """SpecialModelName - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + special_property_name (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/string_boolean_map.py b/samples/client/petstore/python/petstore_api/model/string_boolean_map.py index 4ac526991839..05f8527fec1e 100644 --- a/samples/client/petstore/python/petstore_api/model/string_boolean_map.py +++ b/samples/client/petstore/python/petstore_api/model/string_boolean_map.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class StringBooleanMap(ModelNormal): @@ -88,8 +91,84 @@ def discriminator(): attribute_map = { } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """StringBooleanMap - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +246,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/string_enum.py b/samples/client/petstore/python/petstore_api/model/string_enum.py index 37dc04332cac..5bd1e28942e5 100644 --- a/samples/client/petstore/python/petstore_api/model/string_enum.py +++ b/samples/client/petstore/python/petstore_api/model/string_enum.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class StringEnum(ModelSimple): @@ -58,7 +61,13 @@ class StringEnum(ModelSimple): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -83,6 +92,8 @@ def discriminator(): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -182,3 +193,97 @@ def __init__(self, *args, **kwargs): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """StringEnum - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str):, must be one of ["placed", "approved", "delivered", ] # noqa: E501 + + Keyword Args: + value (str):, must be one of ["placed", "approved", "delivered", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/client/petstore/python/petstore_api/model/tag.py b/samples/client/petstore/python/petstore_api/model/tag.py index d3dcb78b7ea0..7db3cee0baaf 100644 --- a/samples/client/petstore/python/petstore_api/model/tag.py +++ b/samples/client/petstore/python/petstore_api/model/tag.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Tag(ModelNormal): @@ -57,7 +60,13 @@ class Tag(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -88,8 +97,87 @@ def discriminator(): 'full_name': 'fullName', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Tag - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + name (str): [optional] # noqa: E501 + full_name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +258,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/type_holder_default.py b/samples/client/petstore/python/petstore_api/model/type_holder_default.py index 324b131f3a2d..be884db9d136 100644 --- a/samples/client/petstore/python/petstore_api/model/type_holder_default.py +++ b/samples/client/petstore/python/petstore_api/model/type_holder_default.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class TypeHolderDefault(ModelNormal): @@ -57,7 +60,13 @@ class TypeHolderDefault(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -96,8 +105,102 @@ def discriminator(): 'datetime_item': 'datetime_item', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, array_item, *args, **kwargs): # noqa: E501 + """TypeHolderDefault - a model defined in OpenAPI + + Args: + array_item ([int]): + + Keyword Args: + string_item (str): defaults to "what" # noqa: E501 + number_item (float): defaults to 1.234 # noqa: E501 + integer_item (int): defaults to -2 # noqa: E501 + bool_item (bool): defaults to True # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + date_item (date): [optional] # noqa: E501 + datetime_item (datetime): [optional] # noqa: E501 + """ + + string_item = kwargs.get('string_item', "what") + number_item = kwargs.get('number_item', 1.234) + integer_item = kwargs.get('integer_item', -2) + bool_item = kwargs.get('bool_item', True) + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.string_item = string_item + self.number_item = number_item + self.integer_item = integer_item + self.bool_item = bool_item + self.array_item = array_item + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -193,3 +296,6 @@ def __init__(self, array_item, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/type_holder_example.py b/samples/client/petstore/python/petstore_api/model/type_holder_example.py index 30bbba178f4f..a0836e32d3f3 100644 --- a/samples/client/petstore/python/petstore_api/model/type_holder_example.py +++ b/samples/client/petstore/python/petstore_api/model/type_holder_example.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class TypeHolderExample(ModelNormal): @@ -66,7 +69,13 @@ class TypeHolderExample(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -101,8 +110,99 @@ def discriminator(): 'array_item': 'array_item', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, bool_item, array_item, *args, **kwargs): # noqa: E501 + """TypeHolderExample - a model defined in OpenAPI + + Args: + bool_item (bool): + array_item ([int]): + + Keyword Args: + string_item (str): defaults to "what", must be one of ["what", ] # noqa: E501 + number_item (float): defaults to 1.234, must be one of [1.234, ] # noqa: E501 + integer_item (int): defaults to -2, must be one of [-2, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + string_item = kwargs.get('string_item', "what") + number_item = kwargs.get('number_item', 1.234) + integer_item = kwargs.get('integer_item', -2) + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.string_item = string_item + self.number_item = number_item + self.integer_item = integer_item + self.bool_item = bool_item + self.array_item = array_item + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -195,3 +295,6 @@ def __init__(self, bool_item, array_item, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/user.py b/samples/client/petstore/python/petstore_api/model/user.py index 9a3cd0814114..9c5bc4dfd412 100644 --- a/samples/client/petstore/python/petstore_api/model/user.py +++ b/samples/client/petstore/python/petstore_api/model/user.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class User(ModelNormal): @@ -57,7 +60,13 @@ class User(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -98,8 +107,92 @@ def discriminator(): 'user_status': 'userStatus', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """User - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + username (str): [optional] # noqa: E501 + first_name (str): [optional] # noqa: E501 + last_name (str): [optional] # noqa: E501 + email (str): [optional] # noqa: E501 + password (str): [optional] # noqa: E501 + phone (str): [optional] # noqa: E501 + user_status (int): User Status. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -185,3 +278,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model/xml_item.py b/samples/client/petstore/python/petstore_api/model/xml_item.py index 8401b3f40076..060ed03809c6 100644 --- a/samples/client/petstore/python/petstore_api/model/xml_item.py +++ b/samples/client/petstore/python/petstore_api/model/xml_item.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class XmlItem(ModelNormal): @@ -57,7 +60,13 @@ class XmlItem(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -140,8 +149,113 @@ def discriminator(): 'prefix_ns_wrapped_array': 'prefix_ns_wrapped_array', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """XmlItem - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + attribute_string (str): [optional] # noqa: E501 + attribute_number (float): [optional] # noqa: E501 + attribute_integer (int): [optional] # noqa: E501 + attribute_boolean (bool): [optional] # noqa: E501 + wrapped_array ([int]): [optional] # noqa: E501 + name_string (str): [optional] # noqa: E501 + name_number (float): [optional] # noqa: E501 + name_integer (int): [optional] # noqa: E501 + name_boolean (bool): [optional] # noqa: E501 + name_array ([int]): [optional] # noqa: E501 + name_wrapped_array ([int]): [optional] # noqa: E501 + prefix_string (str): [optional] # noqa: E501 + prefix_number (float): [optional] # noqa: E501 + prefix_integer (int): [optional] # noqa: E501 + prefix_boolean (bool): [optional] # noqa: E501 + prefix_array ([int]): [optional] # noqa: E501 + prefix_wrapped_array ([int]): [optional] # noqa: E501 + namespace_string (str): [optional] # noqa: E501 + namespace_number (float): [optional] # noqa: E501 + namespace_integer (int): [optional] # noqa: E501 + namespace_boolean (bool): [optional] # noqa: E501 + namespace_array ([int]): [optional] # noqa: E501 + namespace_wrapped_array ([int]): [optional] # noqa: E501 + prefix_ns_string (str): [optional] # noqa: E501 + prefix_ns_number (float): [optional] # noqa: E501 + prefix_ns_integer (int): [optional] # noqa: E501 + prefix_ns_boolean (bool): [optional] # noqa: E501 + prefix_ns_array ([int]): [optional] # noqa: E501 + prefix_ns_wrapped_array ([int]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -248,3 +362,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python/petstore_api/model_utils.py b/samples/client/petstore/python/petstore_api/model_utils.py index f73278f35cc7..97f9b2881cc5 100644 --- a/samples/client/petstore/python/petstore_api/model_utils.py +++ b/samples/client/petstore/python/petstore_api/model_utils.py @@ -29,6 +29,22 @@ file_type = io.IOBase +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(_self, *args, **kwargs): + """ + An attribute named `self` received from the api will conflicts with the reserved `self` + parameter of a class method. During generation, `self` attributes are mapped + to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. + """ + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python(kwargs, _self if isinstance(_self, type) else _self.__class__) + return fn(_self, *args, **kwargs) + return wrapped_init + + class cached_property(object): # this caches the result of the function call for fn with no inputs # use this as a decorator on fuction methods that you want converted @@ -284,6 +300,121 @@ def __new__(cls, *args, **kwargs): return new_inst + @classmethod + @convert_js_args_to_python_args + def _new_from_openapi_data(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return cls._from_openapi_data(*args, **kwargs) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return cls._from_openapi_data(*args, **kwargs) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = cls._from_openapi_data(*args, **kwargs) + + + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + return new_inst + + class ModelSimple(OpenApiModel): """the parent class of models whose type != object in their swagger/openapi""" @@ -434,27 +565,43 @@ def __setitem__(self, name, value): self.__dict__[name] = value return - # set the attribute on the correct instance - model_instances = self._var_name_to_model_instances.get( - name, self._additional_properties_model_instances) - if model_instances: - for model_instance in model_instances: - if model_instance == self: - self.set_attribute(name, value) - else: - setattr(model_instance, name, value) - if name not in self._var_name_to_model_instances: - # we assigned an additional property - self.__dict__['_var_name_to_model_instances'][name] = ( - model_instance - ) - return None - - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) + """ + Use cases: + 1. additional_properties_type is None (additionalProperties == False in spec) + Check for property presence in self.openapi_types + if not present then throw an error + if present set in self, set attribute + always set on composed schemas + 2. additional_properties_type exists + set attribute on self + always set on composed schemas + """ + if self.additional_properties_type is None: + """ + For an attribute to exist on a composed schema it must: + - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND + - fulfill schema_requirements in each oneOf/anyOf/allOf schemas + + schema_requirements: + For an attribute to exist on a schema it must: + - be present in properties at the schema OR + - have additionalProperties unset (defaults additionalProperties = any type) OR + - have additionalProperties set + """ + if name not in self.openapi_types: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + # attribute must be set on self and composed instances + self.set_attribute(name, value) + for model_instance in self._composed_instances: + setattr(model_instance, name, value) + if name not in self._var_name_to_model_instances: + # we assigned an additional property + self.__dict__['_var_name_to_model_instances'][name] = self._composed_instances + [self] + return None __unset_attribute_value__ = object() @@ -464,13 +611,12 @@ def get(self, name, default=None): return self.__dict__[name] # get the attribute from the correct instance - model_instances = self._var_name_to_model_instances.get( - name, self._additional_properties_model_instances) + model_instances = self._var_name_to_model_instances.get(name) values = [] - # A composed model stores child (oneof/anyOf/allOf) models under - # self._var_name_to_model_instances. A named property can exist in - # multiple child models. If the property is present in more than one - # child model, the value must be the same across all the child models. + # A composed model stores self and child (oneof/anyOf/allOf) models under + # self._var_name_to_model_instances. + # Any property must exist in self and all model instances + # The value stored in all model instances must be the same if model_instances: for model_instance in model_instances: if name in model_instance._data_store: @@ -1193,14 +1339,14 @@ def deserialize_model(model_data, model_class, path_to_item, check_type, _spec_property_naming=spec_property_naming) if issubclass(model_class, ModelSimple): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) elif isinstance(model_data, list): - return model_class(*model_data, **kw_args) + return model_class._new_from_openapi_data(*model_data, **kw_args) if isinstance(model_data, dict): kw_args.update(model_data) - return model_class(**kw_args) + return model_class._new_from_openapi_data(**kw_args) elif isinstance(model_data, PRIMITIVE_TYPES): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) def deserialize_file(response_data, configuration, content_disposition=None): @@ -1486,12 +1632,20 @@ def model_to_dict(model_instance, serialize=True): model_instances = [model_instance] if model_instance._composed_schemas: model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} for model_instance in model_instances: for attr, value in model_instance._data_store.items(): if serialize: # we use get here because additional property key names do not # exist in attribute_map - attr = model_instance.attribute_map.get(attr, attr) + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) if isinstance(value, list): if not value: # empty list or None @@ -1519,6 +1673,16 @@ def model_to_dict(model_instance, serialize=True): result[attr] = model_to_dict(value, serialize=serialize) else: result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] return result @@ -1562,30 +1726,19 @@ def get_valid_classes_phrase(input_classes): return "is one of [{0}]".format(", ".join(all_class_names)) -def convert_js_args_to_python_args(fn): - from functools import wraps - @wraps(fn) - def wrapped_init(_self, *args, **kwargs): - """ - An attribute named `self` received from the api will conflicts with the reserved `self` - parameter of a class method. During generation, `self` attributes are mapped - to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. - """ - spec_property_naming = kwargs.get('_spec_property_naming', False) - if spec_property_naming: - kwargs = change_keys_js_to_python(kwargs, _self.__class__) - return fn(_self, *args, **kwargs) - return wrapped_init - - def get_allof_instances(self, model_args, constant_args): """ Args: self: the class we are handling model_args (dict): var_name to var_value used to make instances - constant_args (dict): var_name to var_value - used to make instances + constant_args (dict): + metadata arguments: + _check_type + _path_to_item + _spec_property_naming + _configuration + _visited_composed_classes Returns composed_instances (list) @@ -1593,20 +1746,8 @@ def get_allof_instances(self, model_args, constant_args): composed_instances = [] for allof_class in self._composed_schemas['allOf']: - # no need to handle changing js keys to python because - # for composed schemas, allof parameters are included in the - # composed schema and were changed to python keys in __new__ - # extract a dict of only required keys from fixed_model_args - kwargs = {} - var_names = set(allof_class.openapi_types.keys()) - for var_name in var_names: - if var_name in model_args: - kwargs[var_name] = model_args[var_name] - - # and use it to make the instance - kwargs.update(constant_args) try: - allof_instance = allof_class(**kwargs) + allof_instance = allof_class(**model_args, **constant_args) composed_instances.append(allof_instance) except Exception as ex: raise ApiValueError( @@ -1666,31 +1807,9 @@ def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): single_value_input = allows_single_value_input(oneof_class) - if not single_value_input: - # transform js keys from input data to python keys in fixed_model_args - fixed_model_args = change_keys_js_to_python( - model_kwargs, oneof_class) - - # Extract a dict with the properties that are declared in the oneOf schema. - # Undeclared properties (e.g. properties that are allowed because of the - # additionalProperties attribute in the OAS document) are not added to - # the dict. - kwargs = {} - var_names = set(oneof_class.openapi_types.keys()) - for var_name in var_names: - if var_name in fixed_model_args: - kwargs[var_name] = fixed_model_args[var_name] - - # do not try to make a model with no input args - if len(kwargs) == 0: - continue - - # and use it to make the instance - kwargs.update(constant_kwargs) - try: if not single_value_input: - oneof_instance = oneof_class(**kwargs) + oneof_instance = oneof_class(**model_kwargs, **constant_kwargs) else: if issubclass(oneof_class, ModelSimple): oneof_instance = oneof_class(model_arg, **constant_kwargs) @@ -1747,24 +1866,8 @@ def get_anyof_instances(self, model_args, constant_args): # none_type deserialization is handled in the __new__ method continue - # transform js keys to python keys in fixed_model_args - fixed_model_args = change_keys_js_to_python(model_args, anyof_class) - - # extract a dict of only required keys from these_model_vars - kwargs = {} - var_names = set(anyof_class.openapi_types.keys()) - for var_name in var_names: - if var_name in fixed_model_args: - kwargs[var_name] = fixed_model_args[var_name] - - # do not try to make a model with no input args - if len(kwargs) == 0: - continue - - # and use it to make the instance - kwargs.update(constant_args) try: - anyof_instance = anyof_class(**kwargs) + anyof_instance = anyof_class(**model_args, **constant_args) anyof_instances.append(anyof_instance) except Exception: pass @@ -1777,47 +1880,34 @@ def get_anyof_instances(self, model_args, constant_args): return anyof_instances -def get_additional_properties_model_instances( - composed_instances, self): - additional_properties_model_instances = [] - all_instances = [self] - all_instances.extend(composed_instances) - for instance in all_instances: - if instance.additional_properties_type is not None: - additional_properties_model_instances.append(instance) - return additional_properties_model_instances - - -def get_var_name_to_model_instances(self, composed_instances): - var_name_to_model_instances = {} - all_instances = [self] - all_instances.extend(composed_instances) - for instance in all_instances: - for var_name in instance.openapi_types: - if var_name not in var_name_to_model_instances: - var_name_to_model_instances[var_name] = [instance] - else: - var_name_to_model_instances[var_name].append(instance) - return var_name_to_model_instances - - -def get_unused_args(self, composed_instances, model_args): - unused_args = dict(model_args) - # arguments apssed to self were already converted to python names +def get_discarded_args(self, composed_instances, model_args): + """ + Gathers the args that were discarded by configuration.discard_unknown_keys + """ + model_arg_keys = model_args.keys() + discarded_args = set() + # arguments passed to self were already converted to python names # before __init__ was called - for var_name_py in self.attribute_map: - if var_name_py in unused_args: - del unused_args[var_name_py] for instance in composed_instances: if instance.__class__ in self._composed_schemas['allOf']: - for var_name_py in instance.attribute_map: - if var_name_py in unused_args: - del unused_args[var_name_py] + try: + keys = instance.to_dict().keys() + discarded_keys = model_args - keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass else: - for var_name_js in instance.attribute_map.values(): - if var_name_js in unused_args: - del unused_args[var_name_js] - return unused_args + try: + all_keys = set(model_to_dict(instance, serialize=False).keys()) + js_keys = model_to_dict(instance, serialize=True).keys() + all_keys.update(js_keys) + discarded_keys = model_arg_keys - all_keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass + return discarded_args def validate_get_composed_info(constant_args, model_args, self): @@ -1861,36 +1951,42 @@ def validate_get_composed_info(constant_args, model_args, self): composed_instances.append(oneof_instance) anyof_instances = get_anyof_instances(self, model_args, constant_args) composed_instances.extend(anyof_instances) + """ + set additional_properties_model_instances + additional properties must be evaluated at the schema level + so self's additional properties are most important + If self is a composed schema with: + - no properties defined in self + - additionalProperties: False + Then for object payloads every property is an additional property + and they are not allowed, so only empty dict is allowed + + Properties must be set on all matching schemas + so when a property is assigned toa composed instance, it must be set on all + composed instances regardless of additionalProperties presence + keeping it to prevent breaking changes in v5.0.1 + TODO remove cls._additional_properties_model_instances in 6.0.0 + """ + additional_properties_model_instances = [] + if self.additional_properties_type is not None: + additional_properties_model_instances = [self] - # map variable names to composed_instances - var_name_to_model_instances = get_var_name_to_model_instances( - self, composed_instances) - - # set additional_properties_model_instances - additional_properties_model_instances = ( - get_additional_properties_model_instances(composed_instances, self) - ) - - # set any remaining values - unused_args = get_unused_args(self, composed_instances, model_args) - if len(unused_args) > 0 and \ - len(additional_properties_model_instances) == 0 and \ - (self._configuration is None or - not self._configuration.discard_unknown_keys): - raise ApiValueError( - "Invalid input arguments input when making an instance of " - "class %s. Not all inputs were used. The unused input data " - "is %s" % (self.__class__.__name__, unused_args) - ) + """ + no need to set properties on self in here, they will be set in __init__ + By here all composed schema oneOf/anyOf/allOf instances have their properties set using + model_args + """ + discarded_args = get_discarded_args(self, composed_instances, model_args) - # no need to add additional_properties to var_name_to_model_instances here - # because additional_properties_model_instances will direct us to that - # instance when we use getattr or setattr - # and we update var_name_to_model_instances in setattr + # map variable names to composed_instances + var_name_to_model_instances = {} + for prop_name in model_args: + if prop_name not in discarded_args: + var_name_to_model_instances[prop_name] = [self] + composed_instances return [ composed_instances, var_name_to_model_instances, additional_properties_model_instances, - unused_args + discarded_args ] diff --git a/samples/client/petstore/python/pom.xml b/samples/client/petstore/python/pom.xml index 9dc399cc8089..f6178c5c09c8 100644 --- a/samples/client/petstore/python/pom.xml +++ b/samples/client/petstore/python/pom.xml @@ -1,10 +1,10 @@ 4.0.0 org.openapitools - PythonExperimentalPetstoreClientTests + PythonV2PetstoreClientTestsWithComposition pom 1.0-SNAPSHOT - Python Experimental OpenAPI Petstore Client + Python OpenAPI Petstore Client diff --git a/samples/client/petstore/python/test/test_child.py b/samples/client/petstore/python/test/test_child.py index 3b49febd9532..88e6b9ed4a8e 100644 --- a/samples/client/petstore/python/test/test_child.py +++ b/samples/client/petstore/python/test/test_child.py @@ -73,14 +73,6 @@ def testChild(self): } ) - # setting a value that doesn't exist raises an exception - # with a key - with self.assertRaises(petstore_api.ApiAttributeError): - child['invalid_variable'] = 'some value' - # with setattr - with self.assertRaises(petstore_api.ApiAttributeError): - setattr(child, 'invalid_variable', 'some value') - # with hasattr self.assertFalse(hasattr(child, 'invalid_variable')) @@ -123,17 +115,26 @@ def testChild(self): self.assertEqual( child._var_name_to_model_instances, { - 'radio_waves': [child, parent_instance], - 'tele_vision': [child, parent_instance], - 'inter_net': [child, child_allof_instance] + 'radio_waves': [child, child_allof_instance, parent_instance], + 'tele_vision': [child, child_allof_instance, parent_instance], + 'inter_net': [child, child_allof_instance, parent_instance] } ) # model._additional_properties_model_instances stores a list of # models which have the property additional_properties_type != None self.assertEqual( - child._additional_properties_model_instances, [] + child._additional_properties_model_instances, [child] ) + # setting a value that doesn't exist works + # with a key + child['invalid_variable'] = 'a' + assert child.invalid_variable == 'a' + # with setattr + setattr(child, 'invalid_variable', 'b') + assert child.invalid_variable == 'b' + + # if we modify one of the properties owned by multiple # model_instances we get an exception when we try to access that # property because the retrieved values are not all the same @@ -141,13 +142,13 @@ def testChild(self): with self.assertRaises(petstore_api.ApiValueError): inter_net = child.inter_net - # including extra parameters raises an exception - with self.assertRaises(petstore_api.ApiValueError): - child = Child( - radio_waves=radio_waves, - tele_vision=tele_vision, - inter_net=inter_net, - unknown_property='some value') + # including extra parameters works + child = Child( + radio_waves=radio_waves, + tele_vision=tele_vision, + inter_net=inter_net, + unknown_property='some value') + assert child.unknown_property == 'some value' if __name__ == '__main__': unittest.main() diff --git a/samples/client/petstore/python/test/test_dog.py b/samples/client/petstore/python/test/test_dog.py index 0b95c0a4c83a..0352d794c928 100644 --- a/samples/client/petstore/python/test/test_dog.py +++ b/samples/client/petstore/python/test/test_dog.py @@ -73,23 +73,15 @@ def testDog(self): } ) - # setting a value that doesn't exist raises an exception - # with a key - with self.assertRaises(AttributeError): - dog['invalid_variable'] = 'some value' - # with setattr - with self.assertRaises(AttributeError): - setattr(dog, 'invalid_variable', 'some value') - # getting a value that doesn't exist raises an exception # with a key with self.assertRaises(AttributeError): - invalid_variable = dog['invalid_variable'] + invalid_variable = dog['not_here_a'] # with getattr - self.assertEqual(getattr(dog, 'invalid_variable', 'some value'), 'some value') + self.assertEqual(getattr(dog, 'not_here_a', 'some value'), 'some value') with self.assertRaises(AttributeError): - invalid_variable = getattr(dog, 'invalid_variable') + invalid_variable = getattr(dog, 'not_here_a') # make sure that the ModelComposed class properties are correct # model.composed_schemas() stores the anyOf/allOf/oneOf info @@ -120,17 +112,25 @@ def testDog(self): self.assertEqual( dog._var_name_to_model_instances, { - 'breed': [dog, dog_allof_instance], - 'class_name': [dog, animal_instance], - 'color': [dog, animal_instance] + 'breed': [dog, animal_instance, dog_allof_instance], + 'class_name': [dog, animal_instance, dog_allof_instance], + 'color': [dog, animal_instance, dog_allof_instance] } ) # model._additional_properties_model_instances stores a list of # models which have the property additional_properties_type != None self.assertEqual( - dog._additional_properties_model_instances, [] + dog._additional_properties_model_instances, [dog] ) + # setting a value that doesn't exist works + dog['invalid_variable'] = 'a' + assert dog.invalid_variable == 'a' + + # with setattr + setattr(dog, 'invalid_variable', 'b') + assert dog.invalid_variable == 'b' + # if we modify one of the properties owned by multiple # model_instances we get an exception when we try to access that # property because the retrieved values are not all the same @@ -138,14 +138,14 @@ def testDog(self): with self.assertRaises(petstore_api.ApiValueError): breed = dog.breed - # including extra parameters raises an exception - with self.assertRaises(petstore_api.ApiValueError): - dog = Dog( - class_name=class_name, - color=color, - breed=breed, - unknown_property='some value' - ) + # including extra parameters works + dog = Dog( + class_name=class_name, + color=color, + breed=breed, + unknown_property='some value' + ) + assert dog.unknown_property == 'some value' if __name__ == '__main__': unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.gitignore b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.gitignore new file mode 100644 index 000000000000..43995bd42fa2 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.gitignore @@ -0,0 +1,66 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ +venv/ +.venv/ +.python-version +.pytest_cache + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Ipython Notebook +.ipynb_checkpoints diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.gitlab-ci.yml b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.gitlab-ci.yml new file mode 100644 index 000000000000..9e84f5176163 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.gitlab-ci.yml @@ -0,0 +1,24 @@ +# ref: https://docs.gitlab.com/ee/ci/README.html + +stages: + - test + +.tests: + stage: test + script: + - pip install -r requirements.txt + - pip install -r test-requirements.txt + - pytest --cov=petstore_api + +test-3.6: + extends: .tests + image: python:3.6-alpine +test-3.7: + extends: .tests + image: python:3.7-alpine +test-3.8: + extends: .tests + image: python:3.8-alpine +test-3.9: + extends: .tests + image: python:3.9-alpine diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/.openapi-generator-ignore b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.openapi-generator-ignore similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/.openapi-generator-ignore rename to samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.openapi-generator-ignore diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.openapi-generator/FILES b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.openapi-generator/FILES new file mode 100644 index 000000000000..a5adeaaddc68 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.openapi-generator/FILES @@ -0,0 +1,159 @@ +.gitignore +.gitlab-ci.yml +.travis.yml +README.md +docs/AdditionalPropertiesAnyType.md +docs/AdditionalPropertiesArray.md +docs/AdditionalPropertiesBoolean.md +docs/AdditionalPropertiesClass.md +docs/AdditionalPropertiesInteger.md +docs/AdditionalPropertiesNumber.md +docs/AdditionalPropertiesObject.md +docs/AdditionalPropertiesString.md +docs/Animal.md +docs/AnimalFarm.md +docs/AnotherFakeApi.md +docs/ApiResponse.md +docs/ArrayOfArrayOfNumberOnly.md +docs/ArrayOfNumberOnly.md +docs/ArrayTest.md +docs/Capitalization.md +docs/Cat.md +docs/CatAllOf.md +docs/Category.md +docs/Child.md +docs/ChildAllOf.md +docs/ChildCat.md +docs/ChildCatAllOf.md +docs/ChildDog.md +docs/ChildDogAllOf.md +docs/ChildLizard.md +docs/ChildLizardAllOf.md +docs/ClassModel.md +docs/Client.md +docs/Dog.md +docs/DogAllOf.md +docs/EnumArrays.md +docs/EnumClass.md +docs/EnumTest.md +docs/FakeApi.md +docs/FakeClassnameTags123Api.md +docs/File.md +docs/FileSchemaTestClass.md +docs/FormatTest.md +docs/Grandparent.md +docs/GrandparentAnimal.md +docs/HasOnlyReadOnly.md +docs/List.md +docs/MapTest.md +docs/MixedPropertiesAndAdditionalPropertiesClass.md +docs/Model200Response.md +docs/ModelReturn.md +docs/Name.md +docs/NumberOnly.md +docs/NumberWithValidations.md +docs/ObjectModelWithRefProps.md +docs/Order.md +docs/Parent.md +docs/ParentAllOf.md +docs/ParentPet.md +docs/Pet.md +docs/PetApi.md +docs/Player.md +docs/ReadOnlyFirst.md +docs/SpecialModelName.md +docs/StoreApi.md +docs/StringBooleanMap.md +docs/StringEnum.md +docs/Tag.md +docs/TypeHolderDefault.md +docs/TypeHolderExample.md +docs/User.md +docs/UserApi.md +docs/XmlItem.md +git_push.sh +petstore_api/__init__.py +petstore_api/api/__init__.py +petstore_api/api/another_fake_api.py +petstore_api/api/fake_api.py +petstore_api/api/fake_classname_tags_123_api.py +petstore_api/api/pet_api.py +petstore_api/api/store_api.py +petstore_api/api/user_api.py +petstore_api/api_client.py +petstore_api/apis/__init__.py +petstore_api/configuration.py +petstore_api/exceptions.py +petstore_api/model/__init__.py +petstore_api/model/additional_properties_any_type.py +petstore_api/model/additional_properties_array.py +petstore_api/model/additional_properties_boolean.py +petstore_api/model/additional_properties_class.py +petstore_api/model/additional_properties_integer.py +petstore_api/model/additional_properties_number.py +petstore_api/model/additional_properties_object.py +petstore_api/model/additional_properties_string.py +petstore_api/model/animal.py +petstore_api/model/animal_farm.py +petstore_api/model/api_response.py +petstore_api/model/array_of_array_of_number_only.py +petstore_api/model/array_of_number_only.py +petstore_api/model/array_test.py +petstore_api/model/capitalization.py +petstore_api/model/cat.py +petstore_api/model/cat_all_of.py +petstore_api/model/category.py +petstore_api/model/child.py +petstore_api/model/child_all_of.py +petstore_api/model/child_cat.py +petstore_api/model/child_cat_all_of.py +petstore_api/model/child_dog.py +petstore_api/model/child_dog_all_of.py +petstore_api/model/child_lizard.py +petstore_api/model/child_lizard_all_of.py +petstore_api/model/class_model.py +petstore_api/model/client.py +petstore_api/model/dog.py +petstore_api/model/dog_all_of.py +petstore_api/model/enum_arrays.py +petstore_api/model/enum_class.py +petstore_api/model/enum_test.py +petstore_api/model/file.py +petstore_api/model/file_schema_test_class.py +petstore_api/model/format_test.py +petstore_api/model/grandparent.py +petstore_api/model/grandparent_animal.py +petstore_api/model/has_only_read_only.py +petstore_api/model/list.py +petstore_api/model/map_test.py +petstore_api/model/mixed_properties_and_additional_properties_class.py +petstore_api/model/model200_response.py +petstore_api/model/model_return.py +petstore_api/model/name.py +petstore_api/model/number_only.py +petstore_api/model/number_with_validations.py +petstore_api/model/object_model_with_ref_props.py +petstore_api/model/order.py +petstore_api/model/parent.py +petstore_api/model/parent_all_of.py +petstore_api/model/parent_pet.py +petstore_api/model/pet.py +petstore_api/model/player.py +petstore_api/model/read_only_first.py +petstore_api/model/special_model_name.py +petstore_api/model/string_boolean_map.py +petstore_api/model/string_enum.py +petstore_api/model/tag.py +petstore_api/model/type_holder_default.py +petstore_api/model/type_holder_example.py +petstore_api/model/user.py +petstore_api/model/xml_item.py +petstore_api/model_utils.py +petstore_api/models/__init__.py +petstore_api/rest.py +requirements.txt +setup.cfg +setup.py +test-requirements.txt +test/__init__.py +tox.ini diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.openapi-generator/VERSION b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.openapi-generator/VERSION new file mode 100644 index 000000000000..6555596f9311 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.travis.yml b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.travis.yml new file mode 100644 index 000000000000..1fcc4b155964 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.travis.yml @@ -0,0 +1,13 @@ +# ref: https://docs.travis-ci.com/user/languages/python +language: python +python: + - "3.6" + - "3.7" + - "3.8" + - "3.9" +# command to install dependencies +install: + - "pip install -r requirements.txt" + - "pip install -r test-requirements.txt" +# command to run tests +script: pytest --cov=petstore_api diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/Makefile b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/Makefile new file mode 100644 index 000000000000..a6bbba4a434f --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/Makefile @@ -0,0 +1,18 @@ + #!/bin/bash + +REQUIREMENTS_FILE=dev-requirements.txt +REQUIREMENTS_OUT=dev-requirements.txt.log +SETUP_OUT=*.egg-info +VENV=venv + +clean: + rm -rf $(REQUIREMENTS_OUT) + rm -rf $(SETUP_OUT) + rm -rf $(VENV) + rm -rf .tox + rm -rf .coverage + find . -name "*.py[oc]" -delete + find . -name "__pycache__" -delete + +test: clean + bash ./test_python.sh diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/README.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/README.md new file mode 100644 index 000000000000..5f53c0f64235 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/README.md @@ -0,0 +1,247 @@ +# petstore-api +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.PythonClientCodegen + +## Requirements. + +Python >= 3.6 + +## Installation & Usage +### pip install + +If the python package is hosted on a repository, you can install directly using: + +```sh +pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git +``` +(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) + +Then import the package: +```python +import petstore_api +``` + +### Setuptools + +Install via [Setuptools](http://pypi.python.org/pypi/setuptools). + +```sh +python setup.py install --user +``` +(or `sudo python setup.py install` to install the package for all users) + +Then import the package: +```python +import petstore_api +``` + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```python + +import time +import petstore_api +from pprint import pprint +from petstore_api.api import another_fake_api +from petstore_api.model.client import Client +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = another_fake_api.AnotherFakeApi(api_client) + body = Client( + client="client_example", + ) # Client | client model + + try: + # To test special tags + api_response = api_instance.call_123_test_special_tags(body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AnotherFakeApi* | [**call_123_test_special_tags**](docs/AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags +*FakeApi* | [**array_model**](docs/FakeApi.md#array_model) | **POST** /fake/refs/arraymodel | +*FakeApi* | [**boolean**](docs/FakeApi.md#boolean) | **POST** /fake/refs/boolean | +*FakeApi* | [**create_xml_item**](docs/FakeApi.md#create_xml_item) | **POST** /fake/create_xml_item | creates an XmlItem +*FakeApi* | [**number_with_validations**](docs/FakeApi.md#number_with_validations) | **POST** /fake/refs/number | +*FakeApi* | [**object_model_with_ref_props**](docs/FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | +*FakeApi* | [**string**](docs/FakeApi.md#string) | **POST** /fake/refs/string | +*FakeApi* | [**string_enum**](docs/FakeApi.md#string_enum) | **POST** /fake/refs/enum | +*FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | +*FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | +*FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model +*FakeApi* | [**test_endpoint_enums_length_one**](docs/FakeApi.md#test_endpoint_enums_length_one) | **PUT** /fake/enums-of-length-one/{path_string}/{path_integer} | +*FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**test_enum_parameters**](docs/FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**test_group_parameters**](docs/FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +*FakeApi* | [**test_inline_additional_properties**](docs/FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeApi* | [**test_json_form_data**](docs/FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case +*PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +*PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**upload_file**](docs/PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image +*PetApi* | [**upload_file_with_required_file**](docs/PetApi.md#upload_file_with_required_file) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +*StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +*StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{order_id} | Find purchase order by ID +*StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet +*UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user +*UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +*UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +*UserApi* | [**login_user**](docs/UserApi.md#login_user) | **GET** /user/login | Logs user into the system +*UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**update_user**](docs/UserApi.md#update_user) | **PUT** /user/{username} | Updated user + + +## Documentation For Models + + - [AdditionalPropertiesAnyType](docs/AdditionalPropertiesAnyType.md) + - [AdditionalPropertiesArray](docs/AdditionalPropertiesArray.md) + - [AdditionalPropertiesBoolean](docs/AdditionalPropertiesBoolean.md) + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [AdditionalPropertiesInteger](docs/AdditionalPropertiesInteger.md) + - [AdditionalPropertiesNumber](docs/AdditionalPropertiesNumber.md) + - [AdditionalPropertiesObject](docs/AdditionalPropertiesObject.md) + - [AdditionalPropertiesString](docs/AdditionalPropertiesString.md) + - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ApiResponse](docs/ApiResponse.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayTest](docs/ArrayTest.md) + - [Capitalization](docs/Capitalization.md) + - [Cat](docs/Cat.md) + - [CatAllOf](docs/CatAllOf.md) + - [Category](docs/Category.md) + - [Child](docs/Child.md) + - [ChildAllOf](docs/ChildAllOf.md) + - [ChildCat](docs/ChildCat.md) + - [ChildCatAllOf](docs/ChildCatAllOf.md) + - [ChildDog](docs/ChildDog.md) + - [ChildDogAllOf](docs/ChildDogAllOf.md) + - [ChildLizard](docs/ChildLizard.md) + - [ChildLizardAllOf](docs/ChildLizardAllOf.md) + - [ClassModel](docs/ClassModel.md) + - [Client](docs/Client.md) + - [Dog](docs/Dog.md) + - [DogAllOf](docs/DogAllOf.md) + - [EnumArrays](docs/EnumArrays.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [File](docs/File.md) + - [FileSchemaTestClass](docs/FileSchemaTestClass.md) + - [FormatTest](docs/FormatTest.md) + - [Grandparent](docs/Grandparent.md) + - [GrandparentAnimal](docs/GrandparentAnimal.md) + - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [List](docs/List.md) + - [MapTest](docs/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model200Response.md) + - [ModelReturn](docs/ModelReturn.md) + - [Name](docs/Name.md) + - [NumberOnly](docs/NumberOnly.md) + - [NumberWithValidations](docs/NumberWithValidations.md) + - [ObjectModelWithRefProps](docs/ObjectModelWithRefProps.md) + - [Order](docs/Order.md) + - [Parent](docs/Parent.md) + - [ParentAllOf](docs/ParentAllOf.md) + - [ParentPet](docs/ParentPet.md) + - [Pet](docs/Pet.md) + - [Player](docs/Player.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [SpecialModelName](docs/SpecialModelName.md) + - [StringBooleanMap](docs/StringBooleanMap.md) + - [StringEnum](docs/StringEnum.md) + - [Tag](docs/Tag.md) + - [TypeHolderDefault](docs/TypeHolderDefault.md) + - [TypeHolderExample](docs/TypeHolderExample.md) + - [User](docs/User.md) + - [XmlItem](docs/XmlItem.md) + + +## Documentation For Authorization + + +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +## api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + + +## http_basic_test + +- **Type**: HTTP basic authentication + + +## petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - **write:pets**: modify pets in your account + - **read:pets**: read your pets + + +## Author + + + + +## Notes for Large OpenAPI documents +If the OpenAPI document is large, imports in petstore_api.apis and petstore_api.models may fail with a +RecursionError indicating the maximum recursion limit has been exceeded. In that case, there are a couple of solutions: + +Solution 1: +Use specific imports for apis and models like: +- `from petstore_api.api.default_api import DefaultApi` +- `from petstore_api.model.pet import Pet` + +Solution 2: +Before importing the package, adjust the maximum recursion limit as shown below: +``` +import sys +sys.setrecursionlimit(1500) +import petstore_api +from petstore_api.apis import * +from petstore_api.models import * +``` + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/dev-requirements.txt b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/dev-requirements.txt new file mode 100644 index 000000000000..ccdfca629494 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/dev-requirements.txt @@ -0,0 +1,2 @@ +tox +flake8 diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesAnyType.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesAnyType.md new file mode 100644 index 000000000000..d31d12de0822 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesAnyType.md @@ -0,0 +1,12 @@ +# AdditionalPropertiesAnyType + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesArray.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesArray.md new file mode 100644 index 000000000000..40537cbf8384 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesArray.md @@ -0,0 +1,12 @@ +# AdditionalPropertiesArray + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] +**any string name** | **[bool, date, datetime, dict, float, int, list, str, none_type]** | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesBoolean.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesBoolean.md new file mode 100644 index 000000000000..bf7b5be4c13d --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesBoolean.md @@ -0,0 +1,12 @@ +# AdditionalPropertiesBoolean + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] +**any string name** | **bool** | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesClass.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesClass.md new file mode 100644 index 000000000000..fe54cef0539f --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesClass.md @@ -0,0 +1,21 @@ +# AdditionalPropertiesClass + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**map_string** | **{str: (str,)}** | | [optional] +**map_number** | **{str: (float,)}** | | [optional] +**map_integer** | **{str: (int,)}** | | [optional] +**map_boolean** | **{str: (bool,)}** | | [optional] +**map_array_integer** | **{str: ([int],)}** | | [optional] +**map_array_anytype** | **{str: ([bool, date, datetime, dict, float, int, list, str, none_type],)}** | | [optional] +**map_map_string** | **{str: ({str: (str,)},)}** | | [optional] +**map_map_anytype** | **{str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type,)},)}** | | [optional] +**anytype_1** | **bool, date, datetime, dict, float, int, list, str, none_type** | | [optional] +**anytype_2** | **bool, date, datetime, dict, float, int, list, str, none_type** | no type is set for this | [optional] +**anytype_3** | **bool, date, datetime, dict, float, int, list, str, none_type** | because of a bug in swagger-parser, this should have values {str: (str, int, float...)} but instead we get any type. See https://github.com/swagger-api/swagger-parser/issues/1378 | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesInteger.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesInteger.md new file mode 100644 index 000000000000..96345efd4cc8 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesInteger.md @@ -0,0 +1,12 @@ +# AdditionalPropertiesInteger + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] +**any string name** | **int** | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesNumber.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesNumber.md new file mode 100644 index 000000000000..9af52dc6dcfd --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesNumber.md @@ -0,0 +1,12 @@ +# AdditionalPropertiesNumber + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] +**any string name** | **float** | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesObject.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesObject.md new file mode 100644 index 000000000000..dc64a0d91c24 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesObject.md @@ -0,0 +1,12 @@ +# AdditionalPropertiesObject + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] +**any string name** | **{str: (bool, date, datetime, dict, float, int, list, str, none_type,)}** | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesString.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesString.md new file mode 100644 index 000000000000..fe3993d02265 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AdditionalPropertiesString.md @@ -0,0 +1,12 @@ +# AdditionalPropertiesString + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] +**any string name** | **str** | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Animal.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Animal.md new file mode 100644 index 000000000000..1d1c77c01abc --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Animal.md @@ -0,0 +1,12 @@ +# Animal + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **str** | | +**color** | **str** | | [optional] if omitted the server will use the default value of "red" + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/docs/FakeGetInlineAdditionalPropertiesPayloadArrayData.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AnimalFarm.md similarity index 72% rename from samples/openapi3/client/petstore/python/docs/FakeGetInlineAdditionalPropertiesPayloadArrayData.md rename to samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AnimalFarm.md index 0ba4e3b8e5a4..fc299cf27d34 100644 --- a/samples/openapi3/client/petstore/python/docs/FakeGetInlineAdditionalPropertiesPayloadArrayData.md +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AnimalFarm.md @@ -1,10 +1,10 @@ -# FakeGetInlineAdditionalPropertiesPayloadArrayData +# AnimalFarm ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**labels** | **[str, none_type]** | | [optional] +**value** | [**[Animal]**](Animal.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AnotherFakeApi.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AnotherFakeApi.md new file mode 100644 index 000000000000..470caed72cc5 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/AnotherFakeApi.md @@ -0,0 +1,76 @@ +# petstore_api.AnotherFakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**call_123_test_special_tags**](AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags + + +# **call_123_test_special_tags** +> Client call_123_test_special_tags(body) + +To test special tags + +To test special tags and operation ID starting with number + +### Example + +```python +import time +import petstore_api +from petstore_api.api import another_fake_api +from petstore_api.model.client import Client +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = another_fake_api.AnotherFakeApi(api_client) + body = Client( + client="client_example", + ) # Client | client model + + # example passing only required values which don't have defaults set + try: + # To test special tags + api_response = api_instance.call_123_test_special_tags(body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ApiResponse.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ApiResponse.md new file mode 100644 index 000000000000..81a7d0d85227 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ApiResponse.md @@ -0,0 +1,13 @@ +# ApiResponse + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **int** | | [optional] +**type** | **str** | | [optional] +**message** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 000000000000..6ab77963788b --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,11 @@ +# ArrayOfArrayOfNumberOnly + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**array_array_number** | **[[float]]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ArrayOfNumberOnly.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ArrayOfNumberOnly.md new file mode 100644 index 000000000000..ebc65a54ba7e --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ArrayOfNumberOnly.md @@ -0,0 +1,11 @@ +# ArrayOfNumberOnly + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**array_number** | **[float]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ArrayTest.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ArrayTest.md new file mode 100644 index 000000000000..4e1bda8fc3af --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ArrayTest.md @@ -0,0 +1,13 @@ +# ArrayTest + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**array_of_string** | **[str]** | | [optional] +**array_array_of_integer** | **[[int]]** | | [optional] +**array_array_of_model** | [**[[ReadOnlyFirst]]**](ReadOnlyFirst.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Capitalization.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Capitalization.md new file mode 100644 index 000000000000..1ddeadeb3f46 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Capitalization.md @@ -0,0 +1,16 @@ +# Capitalization + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**small_camel** | **str** | | [optional] +**capital_camel** | **str** | | [optional] +**small_snake** | **str** | | [optional] +**capital_snake** | **str** | | [optional] +**sca_eth_flow_points** | **str** | | [optional] +**att_name** | **str** | Name of the pet | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Cat.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Cat.md new file mode 100644 index 000000000000..e9ce235cd632 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Cat.md @@ -0,0 +1,13 @@ +# Cat + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **str** | | +**declawed** | **bool** | | [optional] +**color** | **str** | | [optional] if omitted the server will use the default value of "red" + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/CatAllOf.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/CatAllOf.md new file mode 100644 index 000000000000..0ff7809a99ac --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/CatAllOf.md @@ -0,0 +1,11 @@ +# CatAllOf + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Category.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Category.md new file mode 100644 index 000000000000..940f6a45e641 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Category.md @@ -0,0 +1,12 @@ +# Category + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | defaults to "default-name" +**id** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Child.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Child.md new file mode 100644 index 000000000000..eb4392445710 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Child.md @@ -0,0 +1,13 @@ +# Child + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**radio_waves** | **bool** | | [optional] +**tele_vision** | **bool** | | [optional] +**inter_net** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildAllOf.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildAllOf.md new file mode 100644 index 000000000000..f9ae99c7c157 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildAllOf.md @@ -0,0 +1,11 @@ +# ChildAllOf + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**inter_net** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildCat.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildCat.md new file mode 100644 index 000000000000..9e3a0fb4b51a --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildCat.md @@ -0,0 +1,12 @@ +# ChildCat + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**pet_type** | **str** | | +**name** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildCatAllOf.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildCatAllOf.md new file mode 100644 index 000000000000..c5883b9a87c8 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildCatAllOf.md @@ -0,0 +1,11 @@ +# ChildCatAllOf + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildDog.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildDog.md new file mode 100644 index 000000000000..9a6e5b372664 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildDog.md @@ -0,0 +1,12 @@ +# ChildDog + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**pet_type** | **str** | | +**bark** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildDogAllOf.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildDogAllOf.md new file mode 100644 index 000000000000..673050667cb3 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildDogAllOf.md @@ -0,0 +1,11 @@ +# ChildDogAllOf + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bark** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildLizard.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildLizard.md new file mode 100644 index 000000000000..e881ee0a1d1b --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildLizard.md @@ -0,0 +1,12 @@ +# ChildLizard + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**pet_type** | **str** | | +**loves_rocks** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildLizardAllOf.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildLizardAllOf.md new file mode 100644 index 000000000000..6e2b70c01505 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ChildLizardAllOf.md @@ -0,0 +1,11 @@ +# ChildLizardAllOf + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**loves_rocks** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ClassModel.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ClassModel.md new file mode 100644 index 000000000000..48ed7cbf2ff0 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ClassModel.md @@ -0,0 +1,12 @@ +# ClassModel + +Model for testing model with \"_class\" property + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_class** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Client.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Client.md new file mode 100644 index 000000000000..c3986008d6c3 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Client.md @@ -0,0 +1,11 @@ +# Client + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Dog.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Dog.md new file mode 100644 index 000000000000..7065c4c983d9 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Dog.md @@ -0,0 +1,13 @@ +# Dog + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **str** | | +**breed** | **str** | | [optional] +**color** | **str** | | [optional] if omitted the server will use the default value of "red" + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/DogAllOf.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/DogAllOf.md new file mode 100644 index 000000000000..6382bbd80671 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/DogAllOf.md @@ -0,0 +1,11 @@ +# DogAllOf + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/EnumArrays.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/EnumArrays.md new file mode 100644 index 000000000000..9be5c645a809 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/EnumArrays.md @@ -0,0 +1,12 @@ +# EnumArrays + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**just_symbol** | **str** | | [optional] +**array_enum** | **[str]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/EnumClass.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/EnumClass.md new file mode 100644 index 000000000000..a1f9aae58190 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/EnumClass.md @@ -0,0 +1,11 @@ +# EnumClass + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**value** | **str** | | defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/EnumTest.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/EnumTest.md new file mode 100644 index 000000000000..eb8842241390 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/EnumTest.md @@ -0,0 +1,15 @@ +# EnumTest + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enum_string_required** | **str** | | +**enum_string** | **str** | | [optional] +**enum_integer** | **int** | | [optional] +**enum_number** | **float** | | [optional] +**string_enum** | [**StringEnum**](StringEnum.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FakeApi.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FakeApi.md new file mode 100644 index 000000000000..bfd6467215ba --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FakeApi.md @@ -0,0 +1,1205 @@ +# petstore_api.FakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**array_model**](FakeApi.md#array_model) | **POST** /fake/refs/arraymodel | +[**boolean**](FakeApi.md#boolean) | **POST** /fake/refs/boolean | +[**create_xml_item**](FakeApi.md#create_xml_item) | **POST** /fake/create_xml_item | creates an XmlItem +[**number_with_validations**](FakeApi.md#number_with_validations) | **POST** /fake/refs/number | +[**object_model_with_ref_props**](FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | +[**string**](FakeApi.md#string) | **POST** /fake/refs/string | +[**string_enum**](FakeApi.md#string_enum) | **POST** /fake/refs/enum | +[**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | +[**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | +[**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model +[**test_endpoint_enums_length_one**](FakeApi.md#test_endpoint_enums_length_one) | **PUT** /fake/enums-of-length-one/{path_string}/{path_integer} | +[**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**test_enum_parameters**](FakeApi.md#test_enum_parameters) | **GET** /fake | To test enum parameters +[**test_group_parameters**](FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[**test_inline_additional_properties**](FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**test_json_form_data**](FakeApi.md#test_json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data + + +# **array_model** +> AnimalFarm array_model() + + + +Test serialization of ArrayModel + +### Example + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.animal_farm import AnimalFarm +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = AnimalFarm([ + Animal(), + ]) # AnimalFarm | Input model (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.array_model(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->array_model: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**AnimalFarm**](AnimalFarm.md)| Input model | [optional] + +### Return type + +[**AnimalFarm**](AnimalFarm.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output model | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **boolean** +> bool boolean() + + + +Test serialization of outer boolean types + +### Example + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = True # bool | Input boolean as post body (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.boolean(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->boolean: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **bool**| Input boolean as post body | [optional] + +### Return type + +**bool** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output boolean | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **create_xml_item** +> create_xml_item(xml_item) + +creates an XmlItem + +this route creates an XmlItem + +### Example + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.xml_item import XmlItem +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + xml_item = XmlItem( + attribute_string="string", + attribute_number=1.234, + attribute_integer=-2, + attribute_boolean=True, + wrapped_array=[ + 1, + ], + name_string="string", + name_number=1.234, + name_integer=-2, + name_boolean=True, + name_array=[ + 1, + ], + name_wrapped_array=[ + 1, + ], + prefix_string="string", + prefix_number=1.234, + prefix_integer=-2, + prefix_boolean=True, + prefix_array=[ + 1, + ], + prefix_wrapped_array=[ + 1, + ], + namespace_string="string", + namespace_number=1.234, + namespace_integer=-2, + namespace_boolean=True, + namespace_array=[ + 1, + ], + namespace_wrapped_array=[ + 1, + ], + prefix_ns_string="string", + prefix_ns_number=1.234, + prefix_ns_integer=-2, + prefix_ns_boolean=True, + prefix_ns_array=[ + 1, + ], + prefix_ns_wrapped_array=[ + 1, + ], + ) # XmlItem | XmlItem Body + + # example passing only required values which don't have defaults set + try: + # creates an XmlItem + api_instance.create_xml_item(xml_item) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->create_xml_item: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **xml_item** | [**XmlItem**](XmlItem.md)| XmlItem Body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml, application/xml; charset=utf-8, application/xml; charset=utf-16, text/xml, text/xml; charset=utf-8, text/xml; charset=utf-16 + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **number_with_validations** +> NumberWithValidations number_with_validations() + + + +Test serialization of outer number types + +### Example + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.number_with_validations import NumberWithValidations +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = NumberWithValidations(1E+1) # NumberWithValidations | Input number as post body (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.number_with_validations(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->number_with_validations: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**NumberWithValidations**](NumberWithValidations.md)| Input number as post body | [optional] + +### Return type + +[**NumberWithValidations**](NumberWithValidations.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output number | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **object_model_with_ref_props** +> ObjectModelWithRefProps object_model_with_ref_props() + + + +Test serialization of object with $refed properties + +### Example + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = ObjectModelWithRefProps( + my_number=NumberWithValidations(1E+1), + my_string="my_string_example", + my_boolean=True, + ) # ObjectModelWithRefProps | Input model (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.object_model_with_ref_props(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->object_model_with_ref_props: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**ObjectModelWithRefProps**](ObjectModelWithRefProps.md)| Input model | [optional] + +### Return type + +[**ObjectModelWithRefProps**](ObjectModelWithRefProps.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output model | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **string** +> str string() + + + +Test serialization of outer string types + +### Example + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = "body_example" # str | Input string as post body (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.string(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->string: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **str**| Input string as post body | [optional] + +### Return type + +**str** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output string | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **string_enum** +> StringEnum string_enum() + + + +Test serialization of outer enum + +### Example + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.string_enum import StringEnum +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = StringEnum("placed") # StringEnum | Input enum (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.string_enum(body=body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->string_enum: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**StringEnum**](StringEnum.md)| Input enum | [optional] + +### Return type + +[**StringEnum**](StringEnum.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output enum | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_body_with_file_schema** +> test_body_with_file_schema(body) + + + +For this test, the body for this request much reference a schema named `File`. + +### Example + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.file_schema_test_class import FileSchemaTestClass +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = FileSchemaTestClass( + file=File( + source_uri="source_uri_example", + ), + files=[ + File( + source_uri="source_uri_example", + ), + ], + ) # FileSchemaTestClass | + + # example passing only required values which don't have defaults set + try: + api_instance.test_body_with_file_schema(body) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_body_with_file_schema: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_body_with_query_params** +> test_body_with_query_params(query, body) + + + +### Example + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.user import User +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + query = "query_example" # str | + body = User( + id=1, + username="username_example", + first_name="first_name_example", + last_name="last_name_example", + email="email_example", + password="password_example", + phone="phone_example", + user_status=1, + ) # User | + + # example passing only required values which don't have defaults set + try: + api_instance.test_body_with_query_params(query, body) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_body_with_query_params: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **query** | **str**| | + **body** | [**User**](User.md)| | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_client_model** +> Client test_client_model(body) + +To test \"client\" model + +To test \"client\" model + +### Example + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.client import Client +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + body = Client( + client="client_example", + ) # Client | client model + + # example passing only required values which don't have defaults set + try: + # To test \"client\" model + api_response = api_instance.test_client_model(body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_client_model: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_endpoint_enums_length_one** +> test_endpoint_enums_length_one() + + + +This route has required values with enums of 1 + +### Example + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + + # example passing only required values which don't have defaults set + try: + api_instance.test_endpoint_enums_length_one() + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_endpoint_enums_length_one: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **query_integer** | **int**| | defaults to 3 + **query_string** | **str**| | defaults to "brillig" + **path_string** | **str**| | defaults to "hello" + **path_integer** | **int**| | defaults to 34 + **header_number** | **float**| | defaults to 1.234 + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_endpoint_parameters** +> test_endpoint_parameters(number, double, pattern_without_delimiter, byte) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example + +* Basic Authentication (http_basic_test): +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure HTTP basic authorization: http_basic_test +configuration = petstore_api.Configuration( + username = 'YOUR_USERNAME', + password = 'YOUR_PASSWORD' +) + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + number = 32.1 # float | None + double = 67.8 # float | None + pattern_without_delimiter = "Aj" # str | None + byte = 'YQ==' # str | None + integer = 10 # int | None (optional) + int32 = 20 # int | None (optional) + int64 = 1 # int | None (optional) + float = 3.14 # float | None (optional) + string = "A" # str | None (optional) + binary = open('/path/to/file', 'rb') # file_type | None (optional) + date = dateutil_parser('1970-01-01').date() # date | None (optional) + date_time = dateutil_parser('1970-01-01T00:00:00.00Z') # datetime | None (optional) + password = "password_example" # str | None (optional) + param_callback = "param_callback_example" # str | None (optional) + + # example passing only required values which don't have defaults set + try: + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) + + # example passing only required values which don't have defaults set + # and optional values + try: + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password, param_callback=param_callback) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **float**| None | + **double** | **float**| None | + **pattern_without_delimiter** | **str**| None | + **byte** | **str**| None | + **integer** | **int**| None | [optional] + **int32** | **int**| None | [optional] + **int64** | **int**| None | [optional] + **float** | **float**| None | [optional] + **string** | **str**| None | [optional] + **binary** | **file_type**| None | [optional] + **date** | **date**| None | [optional] + **date_time** | **datetime**| None | [optional] + **password** | **str**| None | [optional] + **param_callback** | **str**| None | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid username supplied | - | +**404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_enum_parameters** +> test_enum_parameters() + +To test enum parameters + +To test enum parameters + +### Example + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + enum_header_string_array = [ + "$", + ] # [str] | Header parameter enum test (string array) (optional) + enum_header_string = "-efg" # str | Header parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" + enum_query_string_array = [ + "$", + ] # [str] | Query parameter enum test (string array) (optional) + enum_query_string = "-efg" # str | Query parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" + enum_query_integer = 1 # int | Query parameter enum test (double) (optional) + enum_query_double = 1.1 # float | Query parameter enum test (double) (optional) + enum_form_string_array = "$" # [str] | Form parameter enum test (string array) (optional) if omitted the server will use the default value of "$" + enum_form_string = "-efg" # str | Form parameter enum test (string) (optional) if omitted the server will use the default value of "-efg" + + # example passing only required values which don't have defaults set + # and optional values + try: + # To test enum parameters + api_instance.test_enum_parameters(enum_header_string_array=enum_header_string_array, enum_header_string=enum_header_string, enum_query_string_array=enum_query_string_array, enum_query_string=enum_query_string, enum_query_integer=enum_query_integer, enum_query_double=enum_query_double, enum_form_string_array=enum_form_string_array, enum_form_string=enum_form_string) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_enum_parameters: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enum_header_string_array** | **[str]**| Header parameter enum test (string array) | [optional] + **enum_header_string** | **str**| Header parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" + **enum_query_string_array** | **[str]**| Query parameter enum test (string array) | [optional] + **enum_query_string** | **str**| Query parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" + **enum_query_integer** | **int**| Query parameter enum test (double) | [optional] + **enum_query_double** | **float**| Query parameter enum test (double) | [optional] + **enum_form_string_array** | **[str]**| Form parameter enum test (string array) | [optional] if omitted the server will use the default value of "$" + **enum_form_string** | **str**| Form parameter enum test (string) | [optional] if omitted the server will use the default value of "-efg" + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid request | - | +**404** | Not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_group_parameters** +> test_group_parameters(required_string_group, required_boolean_group, required_int64_group) + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### Example + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + required_string_group = 1 # int | Required String in group parameters + required_boolean_group = True # bool | Required Boolean in group parameters + required_int64_group = 1 # int | Required Integer in group parameters + string_group = 1 # int | String in group parameters (optional) + boolean_group = True # bool | Boolean in group parameters (optional) + int64_group = 1 # int | Integer in group parameters (optional) + + # example passing only required values which don't have defaults set + try: + # Fake endpoint to test group parameters (optional) + api_instance.test_group_parameters(required_string_group, required_boolean_group, required_int64_group) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_group_parameters: %s\n" % e) + + # example passing only required values which don't have defaults set + # and optional values + try: + # Fake endpoint to test group parameters (optional) + api_instance.test_group_parameters(required_string_group, required_boolean_group, required_int64_group, string_group=string_group, boolean_group=boolean_group, int64_group=int64_group) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_group_parameters: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **required_string_group** | **int**| Required String in group parameters | + **required_boolean_group** | **bool**| Required Boolean in group parameters | + **required_int64_group** | **int**| Required Integer in group parameters | + **string_group** | **int**| String in group parameters | [optional] + **boolean_group** | **bool**| Boolean in group parameters | [optional] + **int64_group** | **int**| Integer in group parameters | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Someting wrong | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_inline_additional_properties** +> test_inline_additional_properties(param) + +test inline additionalProperties + +### Example + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + param = { + "key": "key_example", + } # {str: (str,)} | request body + + # example passing only required values which don't have defaults set + try: + # test inline additionalProperties + api_instance.test_inline_additional_properties(param) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_inline_additional_properties: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **{str: (str,)}**| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_json_form_data** +> test_json_form_data(param, param2) + +test json serialization of form data + +### Example + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + param = "param_example" # str | field1 + param2 = "param2_example" # str | field2 + + # example passing only required values which don't have defaults set + try: + # test json serialization of form data + api_instance.test_json_form_data(param, param2) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->test_json_form_data: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **str**| field1 | + **param2** | **str**| field2 | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FakeClassnameTags123Api.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FakeClassnameTags123Api.md new file mode 100644 index 000000000000..3452fd6ddff4 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FakeClassnameTags123Api.md @@ -0,0 +1,87 @@ +# petstore_api.FakeClassnameTags123Api + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**test_classname**](FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case + + +# **test_classname** +> Client test_classname(body) + +To test class name in snake case + +To test class name in snake case + +### Example + +* Api Key Authentication (api_key_query): +```python +import time +import petstore_api +from petstore_api.api import fake_classname_tags_123_api +from petstore_api.model.client import Client +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure API key authorization: api_key_query +configuration.api_key['api_key_query'] = 'YOUR_API_KEY' + +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +# configuration.api_key_prefix['api_key_query'] = 'Bearer' + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = fake_classname_tags_123_api.FakeClassnameTags123Api(api_client) + body = Client( + client="client_example", + ) # Client | client model + + # example passing only required values which don't have defaults set + try: + # To test class name in snake case + api_response = api_instance.test_classname(body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeClassnameTags123Api->test_classname: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/File.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/File.md new file mode 100644 index 000000000000..63b1d1a65186 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/File.md @@ -0,0 +1,12 @@ +# File + +Must be named `File` for test. + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**source_uri** | **str** | Test capitalization | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FileSchemaTestClass.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FileSchemaTestClass.md new file mode 100644 index 000000000000..caf2440821da --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FileSchemaTestClass.md @@ -0,0 +1,12 @@ +# FileSchemaTestClass + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**file** | [**File**](File.md) | | [optional] +**files** | [**[File]**](File.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FormatTest.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FormatTest.md new file mode 100644 index 000000000000..aef09bfcc83e --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/FormatTest.md @@ -0,0 +1,23 @@ +# FormatTest + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**number** | **float** | | +**byte** | **str** | | +**date** | **date** | | +**password** | **str** | | +**integer** | **int** | | [optional] +**int32** | **int** | | [optional] +**int64** | **int** | | [optional] +**float** | **float** | | [optional] +**double** | **float** | | [optional] +**string** | **str** | | [optional] +**binary** | **file_type** | | [optional] +**date_time** | **datetime** | | [optional] +**uuid** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Grandparent.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Grandparent.md new file mode 100644 index 000000000000..b6d80a719457 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Grandparent.md @@ -0,0 +1,11 @@ +# Grandparent + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**radio_waves** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/GrandparentAnimal.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/GrandparentAnimal.md new file mode 100644 index 000000000000..15db0708bb1a --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/GrandparentAnimal.md @@ -0,0 +1,11 @@ +# GrandparentAnimal + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**pet_type** | **str** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/HasOnlyReadOnly.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/HasOnlyReadOnly.md new file mode 100644 index 000000000000..0e1334519a8b --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/HasOnlyReadOnly.md @@ -0,0 +1,12 @@ +# HasOnlyReadOnly + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **str** | | [optional] [readonly] +**foo** | **str** | | [optional] [readonly] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/List.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/List.md new file mode 100644 index 000000000000..4b60956971aa --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/List.md @@ -0,0 +1,11 @@ +# List + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123_list** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/MapTest.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/MapTest.md new file mode 100644 index 000000000000..15228ee1f282 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/MapTest.md @@ -0,0 +1,14 @@ +# MapTest + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**map_map_of_string** | **{str: ({str: (str,)},)}** | | [optional] +**map_of_enum_string** | **{str: (str,)}** | | [optional] +**direct_map** | **{str: (bool,)}** | | [optional] +**indirect_map** | [**StringBooleanMap**](StringBooleanMap.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 000000000000..f489944a20af --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,13 @@ +# MixedPropertiesAndAdditionalPropertiesClass + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **str** | | [optional] +**date_time** | **datetime** | | [optional] +**map** | [**{str: (Animal,)}**](Animal.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Model200Response.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Model200Response.md new file mode 100644 index 000000000000..c958bd4b33f8 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Model200Response.md @@ -0,0 +1,13 @@ +# Model200Response + +Model for testing model name starting with number + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **int** | | [optional] +**_class** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ModelReturn.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ModelReturn.md new file mode 100644 index 000000000000..043e9d466fab --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ModelReturn.md @@ -0,0 +1,12 @@ +# ModelReturn + +Model for testing reserved words + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Name.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Name.md new file mode 100644 index 000000000000..3be719cdbfba --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Name.md @@ -0,0 +1,15 @@ +# Name + +Model for testing model name same as property name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **int** | | +**snake_case** | **int** | | [optional] [readonly] +**_property** | **str** | | [optional] +**_123_number** | **int** | | [optional] [readonly] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/NumberOnly.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/NumberOnly.md new file mode 100644 index 000000000000..37195c5d8994 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/NumberOnly.md @@ -0,0 +1,11 @@ +# NumberOnly + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**just_number** | **float** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/NumberWithValidations.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/NumberWithValidations.md new file mode 100644 index 000000000000..119e0f678239 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/NumberWithValidations.md @@ -0,0 +1,11 @@ +# NumberWithValidations + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**value** | **float** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ObjectModelWithRefProps.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ObjectModelWithRefProps.md new file mode 100644 index 000000000000..5ff4e52033d6 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ObjectModelWithRefProps.md @@ -0,0 +1,14 @@ +# ObjectModelWithRefProps + +a model that includes properties which should stay primitive (String + Boolean) and one which is defined as a class, NumberWithValidations + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**my_number** | [**NumberWithValidations**](NumberWithValidations.md) | | [optional] +**my_string** | **str** | | [optional] +**my_boolean** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Order.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Order.md new file mode 100644 index 000000000000..d29e1a381de8 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Order.md @@ -0,0 +1,16 @@ +# Order + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**pet_id** | **int** | | [optional] +**quantity** | **int** | | [optional] +**ship_date** | **datetime** | | [optional] +**status** | **str** | Order Status | [optional] +**complete** | **bool** | | [optional] if omitted the server will use the default value of False + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Parent.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Parent.md new file mode 100644 index 000000000000..9d3f02d68b31 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Parent.md @@ -0,0 +1,12 @@ +# Parent + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**radio_waves** | **bool** | | [optional] +**tele_vision** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ParentAllOf.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ParentAllOf.md new file mode 100644 index 000000000000..569a5e4af14f --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ParentAllOf.md @@ -0,0 +1,11 @@ +# ParentAllOf + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**tele_vision** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ParentPet.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ParentPet.md new file mode 100644 index 000000000000..09e409c8fcf1 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ParentPet.md @@ -0,0 +1,11 @@ +# ParentPet + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**pet_type** | **str** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Pet.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Pet.md new file mode 100644 index 000000000000..6e78495272e4 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Pet.md @@ -0,0 +1,16 @@ +# Pet + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | +**photo_urls** | **[str]** | | +**id** | **int** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**tags** | [**[Tag]**](Tag.md) | | [optional] +**status** | **str** | pet status in the store | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/PetApi.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/PetApi.md new file mode 100644 index 000000000000..dcff2fcd0727 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/PetApi.md @@ -0,0 +1,782 @@ +# petstore_api.PetApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**add_pet**](PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +[**delete_pet**](PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet +[**find_pets_by_status**](PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status +[**find_pets_by_tags**](PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +[**get_pet_by_id**](PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +[**update_pet**](PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +[**update_pet_with_form**](PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**upload_file**](PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image +[**upload_file_with_required_file**](PetApi.md#upload_file_with_required_file) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) + + +# **add_pet** +> add_pet(body) + +Add a new pet to the store + +### Example + +* OAuth Authentication (petstore_auth): +```python +import time +import petstore_api +from petstore_api.api import pet_api +from petstore_api.model.pet import Pet +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure OAuth2 access token for authorization: petstore_auth +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) +configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + body = Pet( + id=1, + category=Category( + id=1, + name="default-name", + ), + name="doggie", + photo_urls=[ + "photo_urls_example", + ], + tags=[ + Tag( + id=1, + name="name_example", + full_name="full_name_example", + ), + ], + status="available", + ) # Pet | Pet object that needs to be added to the store + + # example passing only required values which don't have defaults set + try: + # Add a new pet to the store + api_instance.add_pet(body) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->add_pet: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | +**405** | Invalid input | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **delete_pet** +> delete_pet(pet_id) + +Deletes a pet + +### Example + +* OAuth Authentication (petstore_auth): +```python +import time +import petstore_api +from petstore_api.api import pet_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure OAuth2 access token for authorization: petstore_auth +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) +configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + pet_id = 1 # int | Pet id to delete + api_key = "api_key_example" # str | (optional) + + # example passing only required values which don't have defaults set + try: + # Deletes a pet + api_instance.delete_pet(pet_id) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->delete_pet: %s\n" % e) + + # example passing only required values which don't have defaults set + # and optional values + try: + # Deletes a pet + api_instance.delete_pet(pet_id, api_key=api_key) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->delete_pet: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| Pet id to delete | + **api_key** | **str**| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | +**400** | Invalid pet value | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **find_pets_by_status** +> [Pet] find_pets_by_status(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example + +* OAuth Authentication (petstore_auth): +```python +import time +import petstore_api +from petstore_api.api import pet_api +from petstore_api.model.pet import Pet +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure OAuth2 access token for authorization: petstore_auth +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) +configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + status = [ + "available", + ] # [str] | Status values that need to be considered for filter + + # example passing only required values which don't have defaults set + try: + # Finds Pets by status + api_response = api_instance.find_pets_by_status(status) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->find_pets_by_status: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | **[str]**| Status values that need to be considered for filter | + +### Return type + +[**[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | +**400** | Invalid status value | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **find_pets_by_tags** +> [Pet] find_pets_by_tags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example + +* OAuth Authentication (petstore_auth): +```python +import time +import petstore_api +from petstore_api.api import pet_api +from petstore_api.model.pet import Pet +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure OAuth2 access token for authorization: petstore_auth +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) +configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + tags = [ + "tags_example", + ] # [str] | Tags to filter by + + # example passing only required values which don't have defaults set + try: + # Finds Pets by tags + api_response = api_instance.find_pets_by_tags(tags) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->find_pets_by_tags: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | **[str]**| Tags to filter by | + +### Return type + +[**[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | +**400** | Invalid tag value | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_pet_by_id** +> Pet get_pet_by_id(pet_id) + +Find pet by ID + +Returns a single pet + +### Example + +* Api Key Authentication (api_key): +```python +import time +import petstore_api +from petstore_api.api import pet_api +from petstore_api.model.pet import Pet +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure API key authorization: api_key +configuration.api_key['api_key'] = 'YOUR_API_KEY' + +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +# configuration.api_key_prefix['api_key'] = 'Bearer' + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + pet_id = 1 # int | ID of pet to return + + # example passing only required values which don't have defaults set + try: + # Find pet by ID + api_response = api_instance.get_pet_by_id(pet_id) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->get_pet_by_id: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | +**400** | Invalid ID supplied | - | +**404** | Pet not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **update_pet** +> update_pet(body) + +Update an existing pet + +### Example + +* OAuth Authentication (petstore_auth): +```python +import time +import petstore_api +from petstore_api.api import pet_api +from petstore_api.model.pet import Pet +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure OAuth2 access token for authorization: petstore_auth +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) +configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + body = Pet( + id=1, + category=Category( + id=1, + name="default-name", + ), + name="doggie", + photo_urls=[ + "photo_urls_example", + ], + tags=[ + Tag( + id=1, + name="name_example", + full_name="full_name_example", + ), + ], + status="available", + ) # Pet | Pet object that needs to be added to the store + + # example passing only required values which don't have defaults set + try: + # Update an existing pet + api_instance.update_pet(body) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->update_pet: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | +**400** | Invalid ID supplied | - | +**404** | Pet not found | - | +**405** | Validation exception | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **update_pet_with_form** +> update_pet_with_form(pet_id) + +Updates a pet in the store with form data + +### Example + +* OAuth Authentication (petstore_auth): +```python +import time +import petstore_api +from petstore_api.api import pet_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure OAuth2 access token for authorization: petstore_auth +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) +configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + pet_id = 1 # int | ID of pet that needs to be updated + name = "name_example" # str | Updated name of the pet (optional) + status = "status_example" # str | Updated status of the pet (optional) + + # example passing only required values which don't have defaults set + try: + # Updates a pet in the store with form data + api_instance.update_pet_with_form(pet_id) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->update_pet_with_form: %s\n" % e) + + # example passing only required values which don't have defaults set + # and optional values + try: + # Updates a pet in the store with form data + api_instance.update_pet_with_form(pet_id, name=name, status=status) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->update_pet_with_form: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet that needs to be updated | + **name** | **str**| Updated name of the pet | [optional] + **status** | **str**| Updated status of the pet | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**405** | Invalid input | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **upload_file** +> ApiResponse upload_file(pet_id) + +uploads an image + +### Example + +* OAuth Authentication (petstore_auth): +```python +import time +import petstore_api +from petstore_api.api import pet_api +from petstore_api.model.api_response import ApiResponse +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure OAuth2 access token for authorization: petstore_auth +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) +configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + pet_id = 1 # int | ID of pet to update + additional_metadata = "additional_metadata_example" # str | Additional data to pass to server (optional) + file = open('/path/to/file', 'rb') # file_type | file to upload (optional) + files = # [file_type] | files to upload (optional) + + # example passing only required values which don't have defaults set + try: + # uploads an image + api_response = api_instance.upload_file(pet_id) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->upload_file: %s\n" % e) + + # example passing only required values which don't have defaults set + # and optional values + try: + # uploads an image + api_response = api_instance.upload_file(pet_id, additional_metadata=additional_metadata, file=file, files=files) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->upload_file: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet to update | + **additional_metadata** | **str**| Additional data to pass to server | [optional] + **file** | **file_type**| file to upload | [optional] + **files** | **[file_type]**| files to upload | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **upload_file_with_required_file** +> ApiResponse upload_file_with_required_file(pet_id, required_file) + +uploads an image (required) + +### Example + +* OAuth Authentication (petstore_auth): +```python +import time +import petstore_api +from petstore_api.api import pet_api +from petstore_api.model.api_response import ApiResponse +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure OAuth2 access token for authorization: petstore_auth +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) +configuration.access_token = 'YOUR_ACCESS_TOKEN' + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = pet_api.PetApi(api_client) + pet_id = 1 # int | ID of pet to update + required_file = open('/path/to/file', 'rb') # file_type | file to upload + additional_metadata = "additional_metadata_example" # str | Additional data to pass to server (optional) + + # example passing only required values which don't have defaults set + try: + # uploads an image (required) + api_response = api_instance.upload_file_with_required_file(pet_id, required_file) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->upload_file_with_required_file: %s\n" % e) + + # example passing only required values which don't have defaults set + # and optional values + try: + # uploads an image (required) + api_response = api_instance.upload_file_with_required_file(pet_id, required_file, additional_metadata=additional_metadata) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling PetApi->upload_file_with_required_file: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **int**| ID of pet to update | + **required_file** | **file_type**| file to upload | + **additional_metadata** | **str**| Additional data to pass to server | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Player.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Player.md new file mode 100644 index 000000000000..2014198aa1bd --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Player.md @@ -0,0 +1,12 @@ +# Player + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | +**enemy_player** | [**Player**](Player.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ReadOnlyFirst.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ReadOnlyFirst.md new file mode 100644 index 000000000000..53b4c61d8445 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/ReadOnlyFirst.md @@ -0,0 +1,12 @@ +# ReadOnlyFirst + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **str** | | [optional] [readonly] +**baz** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/SpecialModelName.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/SpecialModelName.md new file mode 100644 index 000000000000..268e1134192d --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/SpecialModelName.md @@ -0,0 +1,11 @@ +# SpecialModelName + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**special_property_name** | **int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/StoreApi.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/StoreApi.md new file mode 100644 index 000000000000..b5df4fc1feea --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/StoreApi.md @@ -0,0 +1,285 @@ +# petstore_api.StoreApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**delete_order**](StoreApi.md#delete_order) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +[**get_inventory**](StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +[**get_order_by_id**](StoreApi.md#get_order_by_id) | **GET** /store/order/{order_id} | Find purchase order by ID +[**place_order**](StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet + + +# **delete_order** +> delete_order(order_id) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example + +```python +import time +import petstore_api +from petstore_api.api import store_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = store_api.StoreApi(api_client) + order_id = "order_id_example" # str | ID of the order that needs to be deleted + + # example passing only required values which don't have defaults set + try: + # Delete purchase order by ID + api_instance.delete_order(order_id) + except petstore_api.ApiException as e: + print("Exception when calling StoreApi->delete_order: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **str**| ID of the order that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid ID supplied | - | +**404** | Order not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_inventory** +> {str: (int,)} get_inventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example + +* Api Key Authentication (api_key): +```python +import time +import petstore_api +from petstore_api.api import store_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure API key authorization: api_key +configuration.api_key['api_key'] = 'YOUR_API_KEY' + +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +# configuration.api_key_prefix['api_key'] = 'Bearer' + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = store_api.StoreApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + # Returns pet inventories by status + api_response = api_instance.get_inventory() + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling StoreApi->get_inventory: %s\n" % e) +``` + + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**{str: (int,)}** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_order_by_id** +> Order get_order_by_id(order_id) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example + +```python +import time +import petstore_api +from petstore_api.api import store_api +from petstore_api.model.order import Order +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = store_api.StoreApi(api_client) + order_id = 1 # int | ID of pet that needs to be fetched + + # example passing only required values which don't have defaults set + try: + # Find purchase order by ID + api_response = api_instance.get_order_by_id(order_id) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling StoreApi->get_order_by_id: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **int**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | +**400** | Invalid ID supplied | - | +**404** | Order not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **place_order** +> Order place_order(body) + +Place an order for a pet + +### Example + +```python +import time +import petstore_api +from petstore_api.api import store_api +from petstore_api.model.order import Order +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = store_api.StoreApi(api_client) + body = Order( + id=1, + pet_id=1, + quantity=1, + ship_date=dateutil_parser('1970-01-01T00:00:00.00Z'), + status="placed", + complete=False, + ) # Order | order placed for purchasing the pet + + # example passing only required values which don't have defaults set + try: + # Place an order for a pet + api_response = api_instance.place_order(body) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling StoreApi->place_order: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | +**400** | Invalid Order | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/StringBooleanMap.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/StringBooleanMap.md new file mode 100644 index 000000000000..217c79704081 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/StringBooleanMap.md @@ -0,0 +1,11 @@ +# StringBooleanMap + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**any string name** | **bool** | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/StringEnum.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/StringEnum.md new file mode 100644 index 000000000000..bb195ec0e453 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/StringEnum.md @@ -0,0 +1,11 @@ +# StringEnum + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**value** | **str** | | must be one of ["placed", "approved", "delivered", ] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Tag.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Tag.md new file mode 100644 index 000000000000..b9fe1e0944c4 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/Tag.md @@ -0,0 +1,13 @@ +# Tag + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**name** | **str** | | [optional] +**full_name** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/TypeHolderDefault.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/TypeHolderDefault.md new file mode 100644 index 000000000000..904915aec010 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/TypeHolderDefault.md @@ -0,0 +1,18 @@ +# TypeHolderDefault + +a model to test optional properties with server defaults + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**array_item** | **[int]** | | +**string_item** | **str** | | defaults to "what" +**number_item** | **float** | | defaults to 1.234 +**integer_item** | **int** | | defaults to -2 +**bool_item** | **bool** | | defaults to True +**date_item** | **date** | | [optional] +**datetime_item** | **datetime** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/TypeHolderExample.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/TypeHolderExample.md new file mode 100644 index 000000000000..d2954c64dcef --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/TypeHolderExample.md @@ -0,0 +1,16 @@ +# TypeHolderExample + +a model to test required properties with an example and length one enum + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bool_item** | **bool** | | +**array_item** | **[int]** | | +**string_item** | **str** | | defaults to "what" +**number_item** | **float** | | defaults to 1.234 +**integer_item** | **int** | | defaults to -2 + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/User.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/User.md new file mode 100644 index 000000000000..b0079f591b6e --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/User.md @@ -0,0 +1,18 @@ +# User + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**username** | **str** | | [optional] +**first_name** | **str** | | [optional] +**last_name** | **str** | | [optional] +**email** | **str** | | [optional] +**password** | **str** | | [optional] +**phone** | **str** | | [optional] +**user_status** | **int** | User Status | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/UserApi.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/UserApi.md new file mode 100644 index 000000000000..3c04b81d1967 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/UserApi.md @@ -0,0 +1,562 @@ +# petstore_api.UserApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**create_user**](UserApi.md#create_user) | **POST** /user | Create user +[**create_users_with_array_input**](UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +[**create_users_with_list_input**](UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +[**delete_user**](UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +[**get_user_by_name**](UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +[**login_user**](UserApi.md#login_user) | **GET** /user/login | Logs user into the system +[**logout_user**](UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +[**update_user**](UserApi.md#update_user) | **PUT** /user/{username} | Updated user + + +# **create_user** +> create_user(body) + +Create user + +This can only be done by the logged in user. + +### Example + +```python +import time +import petstore_api +from petstore_api.api import user_api +from petstore_api.model.user import User +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = user_api.UserApi(api_client) + body = User( + id=1, + username="username_example", + first_name="first_name_example", + last_name="last_name_example", + email="email_example", + password="password_example", + phone="phone_example", + user_status=1, + ) # User | Created user object + + # example passing only required values which don't have defaults set + try: + # Create user + api_instance.create_user(body) + except petstore_api.ApiException as e: + print("Exception when calling UserApi->create_user: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**0** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **create_users_with_array_input** +> create_users_with_array_input(body) + +Creates list of users with given input array + +### Example + +```python +import time +import petstore_api +from petstore_api.api import user_api +from petstore_api.model.user import User +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = user_api.UserApi(api_client) + body = [ + User( + id=1, + username="username_example", + first_name="first_name_example", + last_name="last_name_example", + email="email_example", + password="password_example", + phone="phone_example", + user_status=1, + ), + ] # [User] | List of user object + + # example passing only required values which don't have defaults set + try: + # Creates list of users with given input array + api_instance.create_users_with_array_input(body) + except petstore_api.ApiException as e: + print("Exception when calling UserApi->create_users_with_array_input: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[User]**](User.md)| List of user object | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**0** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **create_users_with_list_input** +> create_users_with_list_input(body) + +Creates list of users with given input array + +### Example + +```python +import time +import petstore_api +from petstore_api.api import user_api +from petstore_api.model.user import User +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = user_api.UserApi(api_client) + body = [ + User( + id=1, + username="username_example", + first_name="first_name_example", + last_name="last_name_example", + email="email_example", + password="password_example", + phone="phone_example", + user_status=1, + ), + ] # [User] | List of user object + + # example passing only required values which don't have defaults set + try: + # Creates list of users with given input array + api_instance.create_users_with_list_input(body) + except petstore_api.ApiException as e: + print("Exception when calling UserApi->create_users_with_list_input: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[User]**](User.md)| List of user object | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**0** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **delete_user** +> delete_user(username) + +Delete user + +This can only be done by the logged in user. + +### Example + +```python +import time +import petstore_api +from petstore_api.api import user_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = user_api.UserApi(api_client) + username = "username_example" # str | The name that needs to be deleted + + # example passing only required values which don't have defaults set + try: + # Delete user + api_instance.delete_user(username) + except petstore_api.ApiException as e: + print("Exception when calling UserApi->delete_user: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **str**| The name that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid username supplied | - | +**404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_user_by_name** +> User get_user_by_name(username) + +Get user by user name + +### Example + +```python +import time +import petstore_api +from petstore_api.api import user_api +from petstore_api.model.user import User +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = user_api.UserApi(api_client) + username = "username_example" # str | The name that needs to be fetched. Use user1 for testing. + + # example passing only required values which don't have defaults set + try: + # Get user by user name + api_response = api_instance.get_user_by_name(username) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling UserApi->get_user_by_name: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **str**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | +**400** | Invalid username supplied | - | +**404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **login_user** +> str login_user(username, password) + +Logs user into the system + +### Example + +```python +import time +import petstore_api +from petstore_api.api import user_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = user_api.UserApi(api_client) + username = "username_example" # str | The user name for login + password = "password_example" # str | The password for login in clear text + + # example passing only required values which don't have defaults set + try: + # Logs user into the system + api_response = api_instance.login_user(username, password) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling UserApi->login_user: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **str**| The user name for login | + **password** | **str**| The password for login in clear text | + +### Return type + +**str** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
* X-Expires-After - date in UTC when token expires
| +**400** | Invalid username/password supplied | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **logout_user** +> logout_user() + +Logs out current logged in user session + +### Example + +```python +import time +import petstore_api +from petstore_api.api import user_api +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = user_api.UserApi(api_client) + + # example, this endpoint has no required or optional parameters + try: + # Logs out current logged in user session + api_instance.logout_user() + except petstore_api.ApiException as e: + print("Exception when calling UserApi->logout_user: %s\n" % e) +``` + + +### Parameters +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**0** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **update_user** +> update_user(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example + +```python +import time +import petstore_api +from petstore_api.api import user_api +from petstore_api.model.user import User +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = user_api.UserApi(api_client) + username = "username_example" # str | name that need to be deleted + body = User( + id=1, + username="username_example", + first_name="first_name_example", + last_name="last_name_example", + email="email_example", + password="password_example", + phone="phone_example", + user_status=1, + ) # User | Updated user object + + # example passing only required values which don't have defaults set + try: + # Updated user + api_instance.update_user(username, body) + except petstore_api.ApiException as e: + print("Exception when calling UserApi->update_user: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **str**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid user supplied | - | +**404** | User not found | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/XmlItem.md b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/XmlItem.md new file mode 100644 index 000000000000..ea3d7f92804b --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/docs/XmlItem.md @@ -0,0 +1,39 @@ +# XmlItem + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**attribute_string** | **str** | | [optional] +**attribute_number** | **float** | | [optional] +**attribute_integer** | **int** | | [optional] +**attribute_boolean** | **bool** | | [optional] +**wrapped_array** | **[int]** | | [optional] +**name_string** | **str** | | [optional] +**name_number** | **float** | | [optional] +**name_integer** | **int** | | [optional] +**name_boolean** | **bool** | | [optional] +**name_array** | **[int]** | | [optional] +**name_wrapped_array** | **[int]** | | [optional] +**prefix_string** | **str** | | [optional] +**prefix_number** | **float** | | [optional] +**prefix_integer** | **int** | | [optional] +**prefix_boolean** | **bool** | | [optional] +**prefix_array** | **[int]** | | [optional] +**prefix_wrapped_array** | **[int]** | | [optional] +**namespace_string** | **str** | | [optional] +**namespace_number** | **float** | | [optional] +**namespace_integer** | **int** | | [optional] +**namespace_boolean** | **bool** | | [optional] +**namespace_array** | **[int]** | | [optional] +**namespace_wrapped_array** | **[int]** | | [optional] +**prefix_ns_string** | **str** | | [optional] +**prefix_ns_number** | **float** | | [optional] +**prefix_ns_integer** | **int** | | [optional] +**prefix_ns_boolean** | **bool** | | [optional] +**prefix_ns_array** | **[int]** | | [optional] +**prefix_ns_wrapped_array** | **[int]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/git_push.sh b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/git_push.sh new file mode 100644 index 000000000000..ced3be2b0c7b --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/git_push.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/__init__.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/__init__.py new file mode 100644 index 000000000000..26dd6f84e215 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/__init__.py @@ -0,0 +1,27 @@ +# flake8: noqa + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +__version__ = "1.0.0" + +# import ApiClient +from petstore_api.api_client import ApiClient + +# import Configuration +from petstore_api.configuration import Configuration + +# import exceptions +from petstore_api.exceptions import OpenApiException +from petstore_api.exceptions import ApiAttributeError +from petstore_api.exceptions import ApiTypeError +from petstore_api.exceptions import ApiValueError +from petstore_api.exceptions import ApiKeyError +from petstore_api.exceptions import ApiException diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/__init__.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/__init__.py new file mode 100644 index 000000000000..840e9f0cd908 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/__init__.py @@ -0,0 +1,3 @@ +# do not import all apis into this module because that uses a lot of memory and stack frames +# if you need the ability to import all apis from one package, import them with +# from petstore_api.apis import AnotherFakeApi diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/another_fake_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/another_fake_api.py new file mode 100644 index 000000000000..9c75f7d5a83e --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/another_fake_api.py @@ -0,0 +1,155 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.api_client import ApiClient, Endpoint as _Endpoint +from petstore_api.model_utils import ( # noqa: F401 + check_allowed_values, + check_validations, + date, + datetime, + file_type, + none_type, + validate_and_convert_types +) +from petstore_api.model.client import Client + + +class AnotherFakeApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def __call_123_test_special_tags( + self, + body, + **kwargs + ): + """To test special tags # noqa: E501 + + To test special tags and operation ID starting with number # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.call_123_test_special_tags(body, async_req=True) + >>> result = thread.get() + + Args: + body (Client): client model + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + Client + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['body'] = \ + body + return self.call_with_http_info(**kwargs) + + self.call_123_test_special_tags = _Endpoint( + settings={ + 'response_type': (Client,), + 'auth': [], + 'endpoint_path': '/another-fake/dummy', + 'operation_id': 'call_123_test_special_tags', + 'http_method': 'PATCH', + 'servers': None, + }, + params_map={ + 'all': [ + 'body', + ], + 'required': [ + 'body', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'body': + (Client,), + }, + 'attribute_map': { + }, + 'location_map': { + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [ + 'application/json' + ] + }, + api_client=api_client, + callable=__call_123_test_special_tags + ) diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_api.py new file mode 100644 index 000000000000..aaf44e6f64c8 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_api.py @@ -0,0 +1,2223 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.api_client import ApiClient, Endpoint as _Endpoint +from petstore_api.model_utils import ( # noqa: F401 + check_allowed_values, + check_validations, + date, + datetime, + file_type, + none_type, + validate_and_convert_types +) +from petstore_api.model.animal_farm import AnimalFarm +from petstore_api.model.client import Client +from petstore_api.model.file_schema_test_class import FileSchemaTestClass +from petstore_api.model.number_with_validations import NumberWithValidations +from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps +from petstore_api.model.string_enum import StringEnum +from petstore_api.model.user import User +from petstore_api.model.xml_item import XmlItem + + +class FakeApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def __array_model( + self, + **kwargs + ): + """array_model # noqa: E501 + + Test serialization of ArrayModel # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.array_model(async_req=True) + >>> result = thread.get() + + + Keyword Args: + body (AnimalFarm): Input model. [optional] + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + AnimalFarm + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + return self.call_with_http_info(**kwargs) + + self.array_model = _Endpoint( + settings={ + 'response_type': (AnimalFarm,), + 'auth': [], + 'endpoint_path': '/fake/refs/arraymodel', + 'operation_id': 'array_model', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'body', + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'body': + (AnimalFarm,), + }, + 'attribute_map': { + }, + 'location_map': { + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + '*/*' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__array_model + ) + + def __boolean( + self, + **kwargs + ): + """boolean # noqa: E501 + + Test serialization of outer boolean types # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.boolean(async_req=True) + >>> result = thread.get() + + + Keyword Args: + body (bool): Input boolean as post body. [optional] + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + bool + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + return self.call_with_http_info(**kwargs) + + self.boolean = _Endpoint( + settings={ + 'response_type': (bool,), + 'auth': [], + 'endpoint_path': '/fake/refs/boolean', + 'operation_id': 'boolean', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'body', + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'body': + (bool,), + }, + 'attribute_map': { + }, + 'location_map': { + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + '*/*' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__boolean + ) + + def __create_xml_item( + self, + xml_item, + **kwargs + ): + """creates an XmlItem # noqa: E501 + + this route creates an XmlItem # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.create_xml_item(xml_item, async_req=True) + >>> result = thread.get() + + Args: + xml_item (XmlItem): XmlItem Body + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['xml_item'] = \ + xml_item + return self.call_with_http_info(**kwargs) + + self.create_xml_item = _Endpoint( + settings={ + 'response_type': None, + 'auth': [], + 'endpoint_path': '/fake/create_xml_item', + 'operation_id': 'create_xml_item', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'xml_item', + ], + 'required': [ + 'xml_item', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'xml_item': + (XmlItem,), + }, + 'attribute_map': { + }, + 'location_map': { + 'xml_item': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [ + 'application/xml', + 'application/xml; charset=utf-8', + 'application/xml; charset=utf-16', + 'text/xml', + 'text/xml; charset=utf-8', + 'text/xml; charset=utf-16' + ] + }, + api_client=api_client, + callable=__create_xml_item + ) + + def __number_with_validations( + self, + **kwargs + ): + """number_with_validations # noqa: E501 + + Test serialization of outer number types # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.number_with_validations(async_req=True) + >>> result = thread.get() + + + Keyword Args: + body (NumberWithValidations): Input number as post body. [optional] + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + NumberWithValidations + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + return self.call_with_http_info(**kwargs) + + self.number_with_validations = _Endpoint( + settings={ + 'response_type': (NumberWithValidations,), + 'auth': [], + 'endpoint_path': '/fake/refs/number', + 'operation_id': 'number_with_validations', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'body', + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'body': + (NumberWithValidations,), + }, + 'attribute_map': { + }, + 'location_map': { + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + '*/*' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__number_with_validations + ) + + def __object_model_with_ref_props( + self, + **kwargs + ): + """object_model_with_ref_props # noqa: E501 + + Test serialization of object with $refed properties # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.object_model_with_ref_props(async_req=True) + >>> result = thread.get() + + + Keyword Args: + body (ObjectModelWithRefProps): Input model. [optional] + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + ObjectModelWithRefProps + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + return self.call_with_http_info(**kwargs) + + self.object_model_with_ref_props = _Endpoint( + settings={ + 'response_type': (ObjectModelWithRefProps,), + 'auth': [], + 'endpoint_path': '/fake/refs/object_model_with_ref_props', + 'operation_id': 'object_model_with_ref_props', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'body', + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'body': + (ObjectModelWithRefProps,), + }, + 'attribute_map': { + }, + 'location_map': { + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + '*/*' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__object_model_with_ref_props + ) + + def __string( + self, + **kwargs + ): + """string # noqa: E501 + + Test serialization of outer string types # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.string(async_req=True) + >>> result = thread.get() + + + Keyword Args: + body (str): Input string as post body. [optional] + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + str + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + return self.call_with_http_info(**kwargs) + + self.string = _Endpoint( + settings={ + 'response_type': (str,), + 'auth': [], + 'endpoint_path': '/fake/refs/string', + 'operation_id': 'string', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'body', + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'body': + (str,), + }, + 'attribute_map': { + }, + 'location_map': { + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + '*/*' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__string + ) + + def __string_enum( + self, + **kwargs + ): + """string_enum # noqa: E501 + + Test serialization of outer enum # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.string_enum(async_req=True) + >>> result = thread.get() + + + Keyword Args: + body (StringEnum): Input enum. [optional] + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + StringEnum + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + return self.call_with_http_info(**kwargs) + + self.string_enum = _Endpoint( + settings={ + 'response_type': (StringEnum,), + 'auth': [], + 'endpoint_path': '/fake/refs/enum', + 'operation_id': 'string_enum', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'body', + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'body': + (StringEnum,), + }, + 'attribute_map': { + }, + 'location_map': { + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + '*/*' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__string_enum + ) + + def __test_body_with_file_schema( + self, + body, + **kwargs + ): + """test_body_with_file_schema # noqa: E501 + + For this test, the body for this request much reference a schema named `File`. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_body_with_file_schema(body, async_req=True) + >>> result = thread.get() + + Args: + body (FileSchemaTestClass): + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['body'] = \ + body + return self.call_with_http_info(**kwargs) + + self.test_body_with_file_schema = _Endpoint( + settings={ + 'response_type': None, + 'auth': [], + 'endpoint_path': '/fake/body-with-file-schema', + 'operation_id': 'test_body_with_file_schema', + 'http_method': 'PUT', + 'servers': None, + }, + params_map={ + 'all': [ + 'body', + ], + 'required': [ + 'body', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'body': + (FileSchemaTestClass,), + }, + 'attribute_map': { + }, + 'location_map': { + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [ + 'application/json' + ] + }, + api_client=api_client, + callable=__test_body_with_file_schema + ) + + def __test_body_with_query_params( + self, + query, + body, + **kwargs + ): + """test_body_with_query_params # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_body_with_query_params(query, body, async_req=True) + >>> result = thread.get() + + Args: + query (str): + body (User): + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['query'] = \ + query + kwargs['body'] = \ + body + return self.call_with_http_info(**kwargs) + + self.test_body_with_query_params = _Endpoint( + settings={ + 'response_type': None, + 'auth': [], + 'endpoint_path': '/fake/body-with-query-params', + 'operation_id': 'test_body_with_query_params', + 'http_method': 'PUT', + 'servers': None, + }, + params_map={ + 'all': [ + 'query', + 'body', + ], + 'required': [ + 'query', + 'body', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'query': + (str,), + 'body': + (User,), + }, + 'attribute_map': { + 'query': 'query', + }, + 'location_map': { + 'query': 'query', + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [ + 'application/json' + ] + }, + api_client=api_client, + callable=__test_body_with_query_params + ) + + def __test_client_model( + self, + body, + **kwargs + ): + """To test \"client\" model # noqa: E501 + + To test \"client\" model # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_client_model(body, async_req=True) + >>> result = thread.get() + + Args: + body (Client): client model + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + Client + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['body'] = \ + body + return self.call_with_http_info(**kwargs) + + self.test_client_model = _Endpoint( + settings={ + 'response_type': (Client,), + 'auth': [], + 'endpoint_path': '/fake', + 'operation_id': 'test_client_model', + 'http_method': 'PATCH', + 'servers': None, + }, + params_map={ + 'all': [ + 'body', + ], + 'required': [ + 'body', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'body': + (Client,), + }, + 'attribute_map': { + }, + 'location_map': { + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [ + 'application/json' + ] + }, + api_client=api_client, + callable=__test_client_model + ) + + def __test_endpoint_enums_length_one( + self, + query_integer=3, + query_string="brillig", + path_string="hello", + path_integer=34, + header_number=1.234, + **kwargs + ): + """test_endpoint_enums_length_one # noqa: E501 + + This route has required values with enums of 1 # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_endpoint_enums_length_one(query_integer=3, query_string="brillig", path_string="hello", path_integer=34, header_number=1.234, async_req=True) + >>> result = thread.get() + + Args: + query_integer (int): defaults to 3, must be one of [3] + query_string (str): defaults to "brillig", must be one of ["brillig"] + path_string (str): defaults to "hello", must be one of ["hello"] + path_integer (int): defaults to 34, must be one of [34] + header_number (float): defaults to 1.234, must be one of [1.234] + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['query_integer'] = \ + query_integer + kwargs['query_string'] = \ + query_string + kwargs['path_string'] = \ + path_string + kwargs['path_integer'] = \ + path_integer + kwargs['header_number'] = \ + header_number + return self.call_with_http_info(**kwargs) + + self.test_endpoint_enums_length_one = _Endpoint( + settings={ + 'response_type': None, + 'auth': [], + 'endpoint_path': '/fake/enums-of-length-one/{path_string}/{path_integer}', + 'operation_id': 'test_endpoint_enums_length_one', + 'http_method': 'PUT', + 'servers': None, + }, + params_map={ + 'all': [ + 'query_integer', + 'query_string', + 'path_string', + 'path_integer', + 'header_number', + ], + 'required': [ + 'query_integer', + 'query_string', + 'path_string', + 'path_integer', + 'header_number', + ], + 'nullable': [ + ], + 'enum': [ + 'query_integer', + 'query_string', + 'path_string', + 'path_integer', + 'header_number', + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + ('query_integer',): { + + "3": 3 + }, + ('query_string',): { + + "BRILLIG": "brillig" + }, + ('path_string',): { + + "HELLO": "hello" + }, + ('path_integer',): { + + "34": 34 + }, + ('header_number',): { + + "1.234": 1.234 + }, + }, + 'openapi_types': { + 'query_integer': + (int,), + 'query_string': + (str,), + 'path_string': + (str,), + 'path_integer': + (int,), + 'header_number': + (float,), + }, + 'attribute_map': { + 'query_integer': 'query_integer', + 'query_string': 'query_string', + 'path_string': 'path_string', + 'path_integer': 'path_integer', + 'header_number': 'header_number', + }, + 'location_map': { + 'query_integer': 'query', + 'query_string': 'query', + 'path_string': 'path', + 'path_integer': 'path', + 'header_number': 'header', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [], + }, + api_client=api_client, + callable=__test_endpoint_enums_length_one + ) + + def __test_endpoint_parameters( + self, + number, + double, + pattern_without_delimiter, + byte, + **kwargs + ): + """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 + + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, async_req=True) + >>> result = thread.get() + + Args: + number (float): None + double (float): None + pattern_without_delimiter (str): None + byte (str): None + + Keyword Args: + integer (int): None. [optional] + int32 (int): None. [optional] + int64 (int): None. [optional] + float (float): None. [optional] + string (str): None. [optional] + binary (file_type): None. [optional] + date (date): None. [optional] + date_time (datetime): None. [optional] + password (str): None. [optional] + param_callback (str): None. [optional] + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['number'] = \ + number + kwargs['double'] = \ + double + kwargs['pattern_without_delimiter'] = \ + pattern_without_delimiter + kwargs['byte'] = \ + byte + return self.call_with_http_info(**kwargs) + + self.test_endpoint_parameters = _Endpoint( + settings={ + 'response_type': None, + 'auth': [ + 'http_basic_test' + ], + 'endpoint_path': '/fake', + 'operation_id': 'test_endpoint_parameters', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'number', + 'double', + 'pattern_without_delimiter', + 'byte', + 'integer', + 'int32', + 'int64', + 'float', + 'string', + 'binary', + 'date', + 'date_time', + 'password', + 'param_callback', + ], + 'required': [ + 'number', + 'double', + 'pattern_without_delimiter', + 'byte', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + 'number', + 'double', + 'pattern_without_delimiter', + 'integer', + 'int32', + 'float', + 'string', + 'password', + ] + }, + root_map={ + 'validations': { + ('number',): { + + 'inclusive_maximum': 543.2, + 'inclusive_minimum': 32.1, + }, + ('double',): { + + 'inclusive_maximum': 123.4, + 'inclusive_minimum': 67.8, + }, + ('pattern_without_delimiter',): { + + 'regex': { + 'pattern': r'^[A-Z].*', # noqa: E501 + }, + }, + ('integer',): { + + 'inclusive_maximum': 100, + 'inclusive_minimum': 10, + }, + ('int32',): { + + 'inclusive_maximum': 200, + 'inclusive_minimum': 20, + }, + ('float',): { + + 'inclusive_maximum': 987.6, + }, + ('string',): { + + 'regex': { + 'pattern': r'[a-z]', # noqa: E501 + 'flags': (re.IGNORECASE) + }, + }, + ('password',): { + 'max_length': 64, + 'min_length': 10, + }, + }, + 'allowed_values': { + }, + 'openapi_types': { + 'number': + (float,), + 'double': + (float,), + 'pattern_without_delimiter': + (str,), + 'byte': + (str,), + 'integer': + (int,), + 'int32': + (int,), + 'int64': + (int,), + 'float': + (float,), + 'string': + (str,), + 'binary': + (file_type,), + 'date': + (date,), + 'date_time': + (datetime,), + 'password': + (str,), + 'param_callback': + (str,), + }, + 'attribute_map': { + 'number': 'number', + 'double': 'double', + 'pattern_without_delimiter': 'pattern_without_delimiter', + 'byte': 'byte', + 'integer': 'integer', + 'int32': 'int32', + 'int64': 'int64', + 'float': 'float', + 'string': 'string', + 'binary': 'binary', + 'date': 'date', + 'date_time': 'dateTime', + 'password': 'password', + 'param_callback': 'callback', + }, + 'location_map': { + 'number': 'form', + 'double': 'form', + 'pattern_without_delimiter': 'form', + 'byte': 'form', + 'integer': 'form', + 'int32': 'form', + 'int64': 'form', + 'float': 'form', + 'string': 'form', + 'binary': 'form', + 'date': 'form', + 'date_time': 'form', + 'password': 'form', + 'param_callback': 'form', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [ + 'application/x-www-form-urlencoded' + ] + }, + api_client=api_client, + callable=__test_endpoint_parameters + ) + + def __test_enum_parameters( + self, + **kwargs + ): + """To test enum parameters # noqa: E501 + + To test enum parameters # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_enum_parameters(async_req=True) + >>> result = thread.get() + + + Keyword Args: + enum_header_string_array ([str]): Header parameter enum test (string array). [optional] + enum_header_string (str): Header parameter enum test (string). [optional] if omitted the server will use the default value of "-efg" + enum_query_string_array ([str]): Query parameter enum test (string array). [optional] + enum_query_string (str): Query parameter enum test (string). [optional] if omitted the server will use the default value of "-efg" + enum_query_integer (int): Query parameter enum test (double). [optional] + enum_query_double (float): Query parameter enum test (double). [optional] + enum_form_string_array ([str]): Form parameter enum test (string array). [optional] if omitted the server will use the default value of "$" + enum_form_string (str): Form parameter enum test (string). [optional] if omitted the server will use the default value of "-efg" + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + return self.call_with_http_info(**kwargs) + + self.test_enum_parameters = _Endpoint( + settings={ + 'response_type': None, + 'auth': [], + 'endpoint_path': '/fake', + 'operation_id': 'test_enum_parameters', + 'http_method': 'GET', + 'servers': None, + }, + params_map={ + 'all': [ + 'enum_header_string_array', + 'enum_header_string', + 'enum_query_string_array', + 'enum_query_string', + 'enum_query_integer', + 'enum_query_double', + 'enum_form_string_array', + 'enum_form_string', + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + 'enum_header_string_array', + 'enum_header_string', + 'enum_query_string_array', + 'enum_query_string', + 'enum_query_integer', + 'enum_query_double', + 'enum_form_string_array', + 'enum_form_string', + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + ('enum_header_string_array',): { + + ">": ">", + "$": "$" + }, + ('enum_header_string',): { + + "_ABC": "_abc", + "-EFG": "-efg", + "(XYZ)": "(xyz)" + }, + ('enum_query_string_array',): { + + ">": ">", + "$": "$" + }, + ('enum_query_string',): { + + "_ABC": "_abc", + "-EFG": "-efg", + "(XYZ)": "(xyz)" + }, + ('enum_query_integer',): { + + "1": 1, + "-2": -2 + }, + ('enum_query_double',): { + + "1.1": 1.1, + "-1.2": -1.2 + }, + ('enum_form_string_array',): { + + ">": ">", + "$": "$" + }, + ('enum_form_string',): { + + "_ABC": "_abc", + "-EFG": "-efg", + "(XYZ)": "(xyz)" + }, + }, + 'openapi_types': { + 'enum_header_string_array': + ([str],), + 'enum_header_string': + (str,), + 'enum_query_string_array': + ([str],), + 'enum_query_string': + (str,), + 'enum_query_integer': + (int,), + 'enum_query_double': + (float,), + 'enum_form_string_array': + ([str],), + 'enum_form_string': + (str,), + }, + 'attribute_map': { + 'enum_header_string_array': 'enum_header_string_array', + 'enum_header_string': 'enum_header_string', + 'enum_query_string_array': 'enum_query_string_array', + 'enum_query_string': 'enum_query_string', + 'enum_query_integer': 'enum_query_integer', + 'enum_query_double': 'enum_query_double', + 'enum_form_string_array': 'enum_form_string_array', + 'enum_form_string': 'enum_form_string', + }, + 'location_map': { + 'enum_header_string_array': 'header', + 'enum_header_string': 'header', + 'enum_query_string_array': 'query', + 'enum_query_string': 'query', + 'enum_query_integer': 'query', + 'enum_query_double': 'query', + 'enum_form_string_array': 'form', + 'enum_form_string': 'form', + }, + 'collection_format_map': { + 'enum_header_string_array': 'csv', + 'enum_query_string_array': 'csv', + 'enum_form_string_array': 'csv', + } + }, + headers_map={ + 'accept': [], + 'content_type': [ + 'application/x-www-form-urlencoded' + ] + }, + api_client=api_client, + callable=__test_enum_parameters + ) + + def __test_group_parameters( + self, + required_string_group, + required_boolean_group, + required_int64_group, + **kwargs + ): + """Fake endpoint to test group parameters (optional) # noqa: E501 + + Fake endpoint to test group parameters (optional) # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_group_parameters(required_string_group, required_boolean_group, required_int64_group, async_req=True) + >>> result = thread.get() + + Args: + required_string_group (int): Required String in group parameters + required_boolean_group (bool): Required Boolean in group parameters + required_int64_group (int): Required Integer in group parameters + + Keyword Args: + string_group (int): String in group parameters. [optional] + boolean_group (bool): Boolean in group parameters. [optional] + int64_group (int): Integer in group parameters. [optional] + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['required_string_group'] = \ + required_string_group + kwargs['required_boolean_group'] = \ + required_boolean_group + kwargs['required_int64_group'] = \ + required_int64_group + return self.call_with_http_info(**kwargs) + + self.test_group_parameters = _Endpoint( + settings={ + 'response_type': None, + 'auth': [], + 'endpoint_path': '/fake', + 'operation_id': 'test_group_parameters', + 'http_method': 'DELETE', + 'servers': None, + }, + params_map={ + 'all': [ + 'required_string_group', + 'required_boolean_group', + 'required_int64_group', + 'string_group', + 'boolean_group', + 'int64_group', + ], + 'required': [ + 'required_string_group', + 'required_boolean_group', + 'required_int64_group', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'required_string_group': + (int,), + 'required_boolean_group': + (bool,), + 'required_int64_group': + (int,), + 'string_group': + (int,), + 'boolean_group': + (bool,), + 'int64_group': + (int,), + }, + 'attribute_map': { + 'required_string_group': 'required_string_group', + 'required_boolean_group': 'required_boolean_group', + 'required_int64_group': 'required_int64_group', + 'string_group': 'string_group', + 'boolean_group': 'boolean_group', + 'int64_group': 'int64_group', + }, + 'location_map': { + 'required_string_group': 'query', + 'required_boolean_group': 'header', + 'required_int64_group': 'query', + 'string_group': 'query', + 'boolean_group': 'header', + 'int64_group': 'query', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [], + }, + api_client=api_client, + callable=__test_group_parameters + ) + + def __test_inline_additional_properties( + self, + param, + **kwargs + ): + """test inline additionalProperties # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_inline_additional_properties(param, async_req=True) + >>> result = thread.get() + + Args: + param ({str: (str,)}): request body + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['param'] = \ + param + return self.call_with_http_info(**kwargs) + + self.test_inline_additional_properties = _Endpoint( + settings={ + 'response_type': None, + 'auth': [], + 'endpoint_path': '/fake/inline-additionalProperties', + 'operation_id': 'test_inline_additional_properties', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'param', + ], + 'required': [ + 'param', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'param': + ({str: (str,)},), + }, + 'attribute_map': { + }, + 'location_map': { + 'param': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [ + 'application/json' + ] + }, + api_client=api_client, + callable=__test_inline_additional_properties + ) + + def __test_json_form_data( + self, + param, + param2, + **kwargs + ): + """test json serialization of form data # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_json_form_data(param, param2, async_req=True) + >>> result = thread.get() + + Args: + param (str): field1 + param2 (str): field2 + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['param'] = \ + param + kwargs['param2'] = \ + param2 + return self.call_with_http_info(**kwargs) + + self.test_json_form_data = _Endpoint( + settings={ + 'response_type': None, + 'auth': [], + 'endpoint_path': '/fake/jsonFormData', + 'operation_id': 'test_json_form_data', + 'http_method': 'GET', + 'servers': None, + }, + params_map={ + 'all': [ + 'param', + 'param2', + ], + 'required': [ + 'param', + 'param2', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'param': + (str,), + 'param2': + (str,), + }, + 'attribute_map': { + 'param': 'param', + 'param2': 'param2', + }, + 'location_map': { + 'param': 'form', + 'param2': 'form', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [ + 'application/x-www-form-urlencoded' + ] + }, + api_client=api_client, + callable=__test_json_form_data + ) diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_classname_tags_123_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_classname_tags_123_api.py new file mode 100644 index 000000000000..1d1afc214c14 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_classname_tags_123_api.py @@ -0,0 +1,157 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.api_client import ApiClient, Endpoint as _Endpoint +from petstore_api.model_utils import ( # noqa: F401 + check_allowed_values, + check_validations, + date, + datetime, + file_type, + none_type, + validate_and_convert_types +) +from petstore_api.model.client import Client + + +class FakeClassnameTags123Api(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def __test_classname( + self, + body, + **kwargs + ): + """To test class name in snake case # noqa: E501 + + To test class name in snake case # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_classname(body, async_req=True) + >>> result = thread.get() + + Args: + body (Client): client model + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + Client + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['body'] = \ + body + return self.call_with_http_info(**kwargs) + + self.test_classname = _Endpoint( + settings={ + 'response_type': (Client,), + 'auth': [ + 'api_key_query' + ], + 'endpoint_path': '/fake_classname_test', + 'operation_id': 'test_classname', + 'http_method': 'PATCH', + 'servers': None, + }, + params_map={ + 'all': [ + 'body', + ], + 'required': [ + 'body', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'body': + (Client,), + }, + 'attribute_map': { + }, + 'location_map': { + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [ + 'application/json' + ] + }, + api_client=api_client, + callable=__test_classname + ) diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/pet_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/pet_api.py new file mode 100644 index 000000000000..2989ca8d4ab7 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/pet_api.py @@ -0,0 +1,1170 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.api_client import ApiClient, Endpoint as _Endpoint +from petstore_api.model_utils import ( # noqa: F401 + check_allowed_values, + check_validations, + date, + datetime, + file_type, + none_type, + validate_and_convert_types +) +from petstore_api.model.api_response import ApiResponse +from petstore_api.model.pet import Pet + + +class PetApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def __add_pet( + self, + body, + **kwargs + ): + """Add a new pet to the store # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.add_pet(body, async_req=True) + >>> result = thread.get() + + Args: + body (Pet): Pet object that needs to be added to the store + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['body'] = \ + body + return self.call_with_http_info(**kwargs) + + self.add_pet = _Endpoint( + settings={ + 'response_type': None, + 'auth': [ + 'petstore_auth' + ], + 'endpoint_path': '/pet', + 'operation_id': 'add_pet', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'body', + ], + 'required': [ + 'body', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'body': + (Pet,), + }, + 'attribute_map': { + }, + 'location_map': { + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [ + 'application/json', + 'application/xml' + ] + }, + api_client=api_client, + callable=__add_pet + ) + + def __delete_pet( + self, + pet_id, + **kwargs + ): + """Deletes a pet # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.delete_pet(pet_id, async_req=True) + >>> result = thread.get() + + Args: + pet_id (int): Pet id to delete + + Keyword Args: + api_key (str): [optional] + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['pet_id'] = \ + pet_id + return self.call_with_http_info(**kwargs) + + self.delete_pet = _Endpoint( + settings={ + 'response_type': None, + 'auth': [ + 'petstore_auth' + ], + 'endpoint_path': '/pet/{petId}', + 'operation_id': 'delete_pet', + 'http_method': 'DELETE', + 'servers': None, + }, + params_map={ + 'all': [ + 'pet_id', + 'api_key', + ], + 'required': [ + 'pet_id', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'pet_id': + (int,), + 'api_key': + (str,), + }, + 'attribute_map': { + 'pet_id': 'petId', + 'api_key': 'api_key', + }, + 'location_map': { + 'pet_id': 'path', + 'api_key': 'header', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [], + }, + api_client=api_client, + callable=__delete_pet + ) + + def __find_pets_by_status( + self, + status, + **kwargs + ): + """Finds Pets by status # noqa: E501 + + Multiple status values can be provided with comma separated strings # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.find_pets_by_status(status, async_req=True) + >>> result = thread.get() + + Args: + status ([str]): Status values that need to be considered for filter + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + [Pet] + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['status'] = \ + status + return self.call_with_http_info(**kwargs) + + self.find_pets_by_status = _Endpoint( + settings={ + 'response_type': ([Pet],), + 'auth': [ + 'petstore_auth' + ], + 'endpoint_path': '/pet/findByStatus', + 'operation_id': 'find_pets_by_status', + 'http_method': 'GET', + 'servers': None, + }, + params_map={ + 'all': [ + 'status', + ], + 'required': [ + 'status', + ], + 'nullable': [ + ], + 'enum': [ + 'status', + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + ('status',): { + + "AVAILABLE": "available", + "PENDING": "pending", + "SOLD": "sold" + }, + }, + 'openapi_types': { + 'status': + ([str],), + }, + 'attribute_map': { + 'status': 'status', + }, + 'location_map': { + 'status': 'query', + }, + 'collection_format_map': { + 'status': 'csv', + } + }, + headers_map={ + 'accept': [ + 'application/xml', + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__find_pets_by_status + ) + + def __find_pets_by_tags( + self, + tags, + **kwargs + ): + """Finds Pets by tags # noqa: E501 + + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.find_pets_by_tags(tags, async_req=True) + >>> result = thread.get() + + Args: + tags ([str]): Tags to filter by + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + [Pet] + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['tags'] = \ + tags + return self.call_with_http_info(**kwargs) + + self.find_pets_by_tags = _Endpoint( + settings={ + 'response_type': ([Pet],), + 'auth': [ + 'petstore_auth' + ], + 'endpoint_path': '/pet/findByTags', + 'operation_id': 'find_pets_by_tags', + 'http_method': 'GET', + 'servers': None, + }, + params_map={ + 'all': [ + 'tags', + ], + 'required': [ + 'tags', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'tags': + ([str],), + }, + 'attribute_map': { + 'tags': 'tags', + }, + 'location_map': { + 'tags': 'query', + }, + 'collection_format_map': { + 'tags': 'csv', + } + }, + headers_map={ + 'accept': [ + 'application/xml', + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__find_pets_by_tags + ) + + def __get_pet_by_id( + self, + pet_id, + **kwargs + ): + """Find pet by ID # noqa: E501 + + Returns a single pet # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.get_pet_by_id(pet_id, async_req=True) + >>> result = thread.get() + + Args: + pet_id (int): ID of pet to return + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + Pet + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['pet_id'] = \ + pet_id + return self.call_with_http_info(**kwargs) + + self.get_pet_by_id = _Endpoint( + settings={ + 'response_type': (Pet,), + 'auth': [ + 'api_key' + ], + 'endpoint_path': '/pet/{petId}', + 'operation_id': 'get_pet_by_id', + 'http_method': 'GET', + 'servers': None, + }, + params_map={ + 'all': [ + 'pet_id', + ], + 'required': [ + 'pet_id', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'pet_id': + (int,), + }, + 'attribute_map': { + 'pet_id': 'petId', + }, + 'location_map': { + 'pet_id': 'path', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/xml', + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__get_pet_by_id + ) + + def __update_pet( + self, + body, + **kwargs + ): + """Update an existing pet # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.update_pet(body, async_req=True) + >>> result = thread.get() + + Args: + body (Pet): Pet object that needs to be added to the store + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['body'] = \ + body + return self.call_with_http_info(**kwargs) + + self.update_pet = _Endpoint( + settings={ + 'response_type': None, + 'auth': [ + 'petstore_auth' + ], + 'endpoint_path': '/pet', + 'operation_id': 'update_pet', + 'http_method': 'PUT', + 'servers': None, + }, + params_map={ + 'all': [ + 'body', + ], + 'required': [ + 'body', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'body': + (Pet,), + }, + 'attribute_map': { + }, + 'location_map': { + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [ + 'application/json', + 'application/xml' + ] + }, + api_client=api_client, + callable=__update_pet + ) + + def __update_pet_with_form( + self, + pet_id, + **kwargs + ): + """Updates a pet in the store with form data # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.update_pet_with_form(pet_id, async_req=True) + >>> result = thread.get() + + Args: + pet_id (int): ID of pet that needs to be updated + + Keyword Args: + name (str): Updated name of the pet. [optional] + status (str): Updated status of the pet. [optional] + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['pet_id'] = \ + pet_id + return self.call_with_http_info(**kwargs) + + self.update_pet_with_form = _Endpoint( + settings={ + 'response_type': None, + 'auth': [ + 'petstore_auth' + ], + 'endpoint_path': '/pet/{petId}', + 'operation_id': 'update_pet_with_form', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'pet_id', + 'name', + 'status', + ], + 'required': [ + 'pet_id', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'pet_id': + (int,), + 'name': + (str,), + 'status': + (str,), + }, + 'attribute_map': { + 'pet_id': 'petId', + 'name': 'name', + 'status': 'status', + }, + 'location_map': { + 'pet_id': 'path', + 'name': 'form', + 'status': 'form', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [ + 'application/x-www-form-urlencoded' + ] + }, + api_client=api_client, + callable=__update_pet_with_form + ) + + def __upload_file( + self, + pet_id, + **kwargs + ): + """uploads an image # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.upload_file(pet_id, async_req=True) + >>> result = thread.get() + + Args: + pet_id (int): ID of pet to update + + Keyword Args: + additional_metadata (str): Additional data to pass to server. [optional] + file (file_type): file to upload. [optional] + files ([file_type]): files to upload. [optional] + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + ApiResponse + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['pet_id'] = \ + pet_id + return self.call_with_http_info(**kwargs) + + self.upload_file = _Endpoint( + settings={ + 'response_type': (ApiResponse,), + 'auth': [ + 'petstore_auth' + ], + 'endpoint_path': '/pet/{petId}/uploadImage', + 'operation_id': 'upload_file', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'pet_id', + 'additional_metadata', + 'file', + 'files', + ], + 'required': [ + 'pet_id', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'pet_id': + (int,), + 'additional_metadata': + (str,), + 'file': + (file_type,), + 'files': + ([file_type],), + }, + 'attribute_map': { + 'pet_id': 'petId', + 'additional_metadata': 'additionalMetadata', + 'file': 'file', + 'files': 'files', + }, + 'location_map': { + 'pet_id': 'path', + 'additional_metadata': 'form', + 'file': 'form', + 'files': 'form', + }, + 'collection_format_map': { + 'files': 'csv', + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [ + 'multipart/form-data' + ] + }, + api_client=api_client, + callable=__upload_file + ) + + def __upload_file_with_required_file( + self, + pet_id, + required_file, + **kwargs + ): + """uploads an image (required) # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.upload_file_with_required_file(pet_id, required_file, async_req=True) + >>> result = thread.get() + + Args: + pet_id (int): ID of pet to update + required_file (file_type): file to upload + + Keyword Args: + additional_metadata (str): Additional data to pass to server. [optional] + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + ApiResponse + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['pet_id'] = \ + pet_id + kwargs['required_file'] = \ + required_file + return self.call_with_http_info(**kwargs) + + self.upload_file_with_required_file = _Endpoint( + settings={ + 'response_type': (ApiResponse,), + 'auth': [ + 'petstore_auth' + ], + 'endpoint_path': '/fake/{petId}/uploadImageWithRequiredFile', + 'operation_id': 'upload_file_with_required_file', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'pet_id', + 'required_file', + 'additional_metadata', + ], + 'required': [ + 'pet_id', + 'required_file', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'pet_id': + (int,), + 'required_file': + (file_type,), + 'additional_metadata': + (str,), + }, + 'attribute_map': { + 'pet_id': 'petId', + 'required_file': 'requiredFile', + 'additional_metadata': 'additionalMetadata', + }, + 'location_map': { + 'pet_id': 'path', + 'required_file': 'form', + 'additional_metadata': 'form', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [ + 'multipart/form-data' + ] + }, + api_client=api_client, + callable=__upload_file_with_required_file + ) diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/store_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/store_api.py new file mode 100644 index 000000000000..c30ca943b2dc --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/store_api.py @@ -0,0 +1,499 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.api_client import ApiClient, Endpoint as _Endpoint +from petstore_api.model_utils import ( # noqa: F401 + check_allowed_values, + check_validations, + date, + datetime, + file_type, + none_type, + validate_and_convert_types +) +from petstore_api.model.order import Order + + +class StoreApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def __delete_order( + self, + order_id, + **kwargs + ): + """Delete purchase order by ID # noqa: E501 + + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.delete_order(order_id, async_req=True) + >>> result = thread.get() + + Args: + order_id (str): ID of the order that needs to be deleted + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['order_id'] = \ + order_id + return self.call_with_http_info(**kwargs) + + self.delete_order = _Endpoint( + settings={ + 'response_type': None, + 'auth': [], + 'endpoint_path': '/store/order/{order_id}', + 'operation_id': 'delete_order', + 'http_method': 'DELETE', + 'servers': None, + }, + params_map={ + 'all': [ + 'order_id', + ], + 'required': [ + 'order_id', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'order_id': + (str,), + }, + 'attribute_map': { + 'order_id': 'order_id', + }, + 'location_map': { + 'order_id': 'path', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [], + }, + api_client=api_client, + callable=__delete_order + ) + + def __get_inventory( + self, + **kwargs + ): + """Returns pet inventories by status # noqa: E501 + + Returns a map of status codes to quantities # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.get_inventory(async_req=True) + >>> result = thread.get() + + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + {str: (int,)} + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + return self.call_with_http_info(**kwargs) + + self.get_inventory = _Endpoint( + settings={ + 'response_type': ({str: (int,)},), + 'auth': [ + 'api_key' + ], + 'endpoint_path': '/store/inventory', + 'operation_id': 'get_inventory', + 'http_method': 'GET', + 'servers': None, + }, + params_map={ + 'all': [ + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + }, + 'attribute_map': { + }, + 'location_map': { + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__get_inventory + ) + + def __get_order_by_id( + self, + order_id, + **kwargs + ): + """Find purchase order by ID # noqa: E501 + + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.get_order_by_id(order_id, async_req=True) + >>> result = thread.get() + + Args: + order_id (int): ID of pet that needs to be fetched + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + Order + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['order_id'] = \ + order_id + return self.call_with_http_info(**kwargs) + + self.get_order_by_id = _Endpoint( + settings={ + 'response_type': (Order,), + 'auth': [], + 'endpoint_path': '/store/order/{order_id}', + 'operation_id': 'get_order_by_id', + 'http_method': 'GET', + 'servers': None, + }, + params_map={ + 'all': [ + 'order_id', + ], + 'required': [ + 'order_id', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + 'order_id', + ] + }, + root_map={ + 'validations': { + ('order_id',): { + + 'inclusive_maximum': 5, + 'inclusive_minimum': 1, + }, + }, + 'allowed_values': { + }, + 'openapi_types': { + 'order_id': + (int,), + }, + 'attribute_map': { + 'order_id': 'order_id', + }, + 'location_map': { + 'order_id': 'path', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/xml', + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__get_order_by_id + ) + + def __place_order( + self, + body, + **kwargs + ): + """Place an order for a pet # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.place_order(body, async_req=True) + >>> result = thread.get() + + Args: + body (Order): order placed for purchasing the pet + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + Order + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['body'] = \ + body + return self.call_with_http_info(**kwargs) + + self.place_order = _Endpoint( + settings={ + 'response_type': (Order,), + 'auth': [], + 'endpoint_path': '/store/order', + 'operation_id': 'place_order', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'body', + ], + 'required': [ + 'body', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'body': + (Order,), + }, + 'attribute_map': { + }, + 'location_map': { + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/xml', + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__place_order + ) diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/user_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/user_api.py new file mode 100644 index 000000000000..a5ef0d5c3092 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/user_api.py @@ -0,0 +1,962 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.api_client import ApiClient, Endpoint as _Endpoint +from petstore_api.model_utils import ( # noqa: F401 + check_allowed_values, + check_validations, + date, + datetime, + file_type, + none_type, + validate_and_convert_types +) +from petstore_api.model.user import User + + +class UserApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def __create_user( + self, + body, + **kwargs + ): + """Create user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.create_user(body, async_req=True) + >>> result = thread.get() + + Args: + body (User): Created user object + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['body'] = \ + body + return self.call_with_http_info(**kwargs) + + self.create_user = _Endpoint( + settings={ + 'response_type': None, + 'auth': [], + 'endpoint_path': '/user', + 'operation_id': 'create_user', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'body', + ], + 'required': [ + 'body', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'body': + (User,), + }, + 'attribute_map': { + }, + 'location_map': { + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [], + }, + api_client=api_client, + callable=__create_user + ) + + def __create_users_with_array_input( + self, + body, + **kwargs + ): + """Creates list of users with given input array # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.create_users_with_array_input(body, async_req=True) + >>> result = thread.get() + + Args: + body ([User]): List of user object + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['body'] = \ + body + return self.call_with_http_info(**kwargs) + + self.create_users_with_array_input = _Endpoint( + settings={ + 'response_type': None, + 'auth': [], + 'endpoint_path': '/user/createWithArray', + 'operation_id': 'create_users_with_array_input', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'body', + ], + 'required': [ + 'body', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'body': + ([User],), + }, + 'attribute_map': { + }, + 'location_map': { + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [], + }, + api_client=api_client, + callable=__create_users_with_array_input + ) + + def __create_users_with_list_input( + self, + body, + **kwargs + ): + """Creates list of users with given input array # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.create_users_with_list_input(body, async_req=True) + >>> result = thread.get() + + Args: + body ([User]): List of user object + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['body'] = \ + body + return self.call_with_http_info(**kwargs) + + self.create_users_with_list_input = _Endpoint( + settings={ + 'response_type': None, + 'auth': [], + 'endpoint_path': '/user/createWithList', + 'operation_id': 'create_users_with_list_input', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'body', + ], + 'required': [ + 'body', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'body': + ([User],), + }, + 'attribute_map': { + }, + 'location_map': { + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [], + }, + api_client=api_client, + callable=__create_users_with_list_input + ) + + def __delete_user( + self, + username, + **kwargs + ): + """Delete user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.delete_user(username, async_req=True) + >>> result = thread.get() + + Args: + username (str): The name that needs to be deleted + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['username'] = \ + username + return self.call_with_http_info(**kwargs) + + self.delete_user = _Endpoint( + settings={ + 'response_type': None, + 'auth': [], + 'endpoint_path': '/user/{username}', + 'operation_id': 'delete_user', + 'http_method': 'DELETE', + 'servers': None, + }, + params_map={ + 'all': [ + 'username', + ], + 'required': [ + 'username', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'username': + (str,), + }, + 'attribute_map': { + 'username': 'username', + }, + 'location_map': { + 'username': 'path', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [], + }, + api_client=api_client, + callable=__delete_user + ) + + def __get_user_by_name( + self, + username, + **kwargs + ): + """Get user by user name # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.get_user_by_name(username, async_req=True) + >>> result = thread.get() + + Args: + username (str): The name that needs to be fetched. Use user1 for testing. + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + User + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['username'] = \ + username + return self.call_with_http_info(**kwargs) + + self.get_user_by_name = _Endpoint( + settings={ + 'response_type': (User,), + 'auth': [], + 'endpoint_path': '/user/{username}', + 'operation_id': 'get_user_by_name', + 'http_method': 'GET', + 'servers': None, + }, + params_map={ + 'all': [ + 'username', + ], + 'required': [ + 'username', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'username': + (str,), + }, + 'attribute_map': { + 'username': 'username', + }, + 'location_map': { + 'username': 'path', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/xml', + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__get_user_by_name + ) + + def __login_user( + self, + username, + password, + **kwargs + ): + """Logs user into the system # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.login_user(username, password, async_req=True) + >>> result = thread.get() + + Args: + username (str): The user name for login + password (str): The password for login in clear text + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + str + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['username'] = \ + username + kwargs['password'] = \ + password + return self.call_with_http_info(**kwargs) + + self.login_user = _Endpoint( + settings={ + 'response_type': (str,), + 'auth': [], + 'endpoint_path': '/user/login', + 'operation_id': 'login_user', + 'http_method': 'GET', + 'servers': None, + }, + params_map={ + 'all': [ + 'username', + 'password', + ], + 'required': [ + 'username', + 'password', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'username': + (str,), + 'password': + (str,), + }, + 'attribute_map': { + 'username': 'username', + 'password': 'password', + }, + 'location_map': { + 'username': 'query', + 'password': 'query', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/xml', + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client, + callable=__login_user + ) + + def __logout_user( + self, + **kwargs + ): + """Logs out current logged in user session # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.logout_user(async_req=True) + >>> result = thread.get() + + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + return self.call_with_http_info(**kwargs) + + self.logout_user = _Endpoint( + settings={ + 'response_type': None, + 'auth': [], + 'endpoint_path': '/user/logout', + 'operation_id': 'logout_user', + 'http_method': 'GET', + 'servers': None, + }, + params_map={ + 'all': [ + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + }, + 'attribute_map': { + }, + 'location_map': { + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [], + }, + api_client=api_client, + callable=__logout_user + ) + + def __update_user( + self, + username, + body, + **kwargs + ): + """Updated user # noqa: E501 + + This can only be done by the logged in user. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.update_user(username, body, async_req=True) + >>> result = thread.get() + + Args: + username (str): name that need to be deleted + body (User): Updated user object + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (float/tuple): timeout setting for this request. If one + number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + None + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['username'] = \ + username + kwargs['body'] = \ + body + return self.call_with_http_info(**kwargs) + + self.update_user = _Endpoint( + settings={ + 'response_type': None, + 'auth': [], + 'endpoint_path': '/user/{username}', + 'operation_id': 'update_user', + 'http_method': 'PUT', + 'servers': None, + }, + params_map={ + 'all': [ + 'username', + 'body', + ], + 'required': [ + 'username', + 'body', + ], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'username': + (str,), + 'body': + (User,), + }, + 'attribute_map': { + 'username': 'username', + }, + 'location_map': { + 'username': 'path', + 'body': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [], + 'content_type': [], + }, + api_client=api_client, + callable=__update_user + ) diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api_client.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api_client.py new file mode 100644 index 000000000000..a43e4ace2427 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api_client.py @@ -0,0 +1,849 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import json +import atexit +import mimetypes +from multiprocessing.pool import ThreadPool +import io +import os +import re +import typing +from urllib.parse import quote +from urllib3.fields import RequestField + + +from petstore_api import rest +from petstore_api.configuration import Configuration +from petstore_api.exceptions import ApiTypeError, ApiValueError, ApiException +from petstore_api.model_utils import ( + ModelNormal, + ModelSimple, + ModelComposed, + check_allowed_values, + check_validations, + date, + datetime, + deserialize_file, + file_type, + model_to_dict, + none_type, + validate_and_convert_types +) + + +class ApiClient(object): + """Generic API client for OpenAPI client library builds. + + OpenAPI generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the OpenAPI + templates. + + NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + Do not edit the class manually. + + :param configuration: .Configuration object for this client + :param header_name: a header to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API + :param pool_threads: The number of threads to use for async requests + to the API. More threads means more concurrent API requests. + """ + + _pool = None + + def __init__(self, configuration=None, header_name=None, header_value=None, + cookie=None, pool_threads=1): + if configuration is None: + configuration = Configuration.get_default_copy() + self.configuration = configuration + self.pool_threads = pool_threads + + self.rest_client = rest.RESTClientObject(configuration) + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.cookie = cookie + # Set default User-Agent. + self.user_agent = 'OpenAPI-Generator/1.0.0/python' + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + def close(self): + if self._pool: + self._pool.close() + self._pool.join() + self._pool = None + if hasattr(atexit, 'unregister'): + atexit.unregister(self.close) + + @property + def pool(self): + """Create thread pool on first request + avoids instantiating unused threadpool for blocking clients. + """ + if self._pool is None: + atexit.register(self.close) + self._pool = ThreadPool(self.pool_threads) + return self._pool + + @property + def user_agent(self): + """User agent for this API client""" + return self.default_headers['User-Agent'] + + @user_agent.setter + def user_agent(self, value): + self.default_headers['User-Agent'] = value + + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value + + def __call_api( + self, + resource_path: str, + method: str, + path_params: typing.Optional[typing.Dict[str, typing.Any]] = None, + query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, + header_params: typing.Optional[typing.Dict[str, typing.Any]] = None, + body: typing.Optional[typing.Any] = None, + post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, + files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None, + response_type: typing.Optional[typing.Tuple[typing.Any]] = None, + auth_settings: typing.Optional[typing.List[str]] = None, + _return_http_data_only: typing.Optional[bool] = None, + collection_formats: typing.Optional[typing.Dict[str, str]] = None, + _preload_content: bool = True, + _request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + _host: typing.Optional[str] = None, + _check_type: typing.Optional[bool] = None + ): + + config = self.configuration + + # header parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) + header_params = dict(self.parameters_to_tuples(header_params, + collection_formats)) + + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + path_params = self.parameters_to_tuples(path_params, + collection_formats) + for k, v in path_params: + # specified safe chars, encode everything + resource_path = resource_path.replace( + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) + + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + query_params = self.parameters_to_tuples(query_params, + collection_formats) + + # post parameters + if post_params or files: + post_params = post_params if post_params else [] + post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples(post_params, + collection_formats) + post_params.extend(self.files_parameters(files)) + if header_params['Content-Type'].startswith("multipart"): + post_params = self.parameters_to_multipart(post_params, + (dict) ) + + # body + if body: + body = self.sanitize_for_serialization(body) + + # auth setting + self.update_params_for_auth(header_params, query_params, + auth_settings, resource_path, method, body) + + # request url + if _host is None: + url = self.configuration.host + resource_path + else: + # use server/host defined in path or operation instead + url = _host + resource_path + + try: + # perform request and return response + response_data = self.request( + method, url, query_params=query_params, headers=header_params, + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout) + except ApiException as e: + e.body = e.body.decode('utf-8') + raise e + + self.last_response = response_data + + return_data = response_data + + if not _preload_content: + return (return_data) + return return_data + + # deserialize response data + if response_type: + if response_type != (file_type,): + encoding = "utf-8" + content_type = response_data.getheader('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type) + if match: + encoding = match.group(1) + response_data.data = response_data.data.decode(encoding) + + return_data = self.deserialize( + response_data, + response_type, + _check_type + ) + else: + return_data = None + + if _return_http_data_only: + return (return_data) + else: + return (return_data, response_data.status, + response_data.getheaders()) + + def parameters_to_multipart(self, params, collection_types): + """Get parameters as list of tuples, formatting as json if value is collection_types + + :param params: Parameters as list of two-tuples + :param dict collection_types: Parameter collection types + :return: Parameters as list of tuple or urllib3.fields.RequestField + """ + new_params = [] + if collection_types is None: + collection_types = (dict) + for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + if isinstance(v, collection_types): # v is instance of collection_type, formatting as application/json + v = json.dumps(v, ensure_ascii=False).encode("utf-8") + field = RequestField(k, v) + field.make_multipart(content_type="application/json; charset=utf-8") + new_params.append(field) + else: + new_params.append((k, v)) + return new_params + + @classmethod + def sanitize_for_serialization(cls, obj): + """Prepares data for transmission before it is sent with the rest client + If obj is None, return None. + If obj is str, int, long, float, bool, return directly. + If obj is datetime.datetime, datetime.date + convert to string in iso8601 format. + If obj is list, sanitize each element in the list. + If obj is dict, return the dict. + If obj is OpenAPI model, return the properties dict. + If obj is io.IOBase, return the bytes + :param obj: The data to serialize. + :return: The serialized form of data. + """ + if isinstance(obj, (ModelNormal, ModelComposed)): + return { + key: cls.sanitize_for_serialization(val) for key, val in model_to_dict(obj, serialize=True).items() + } + elif isinstance(obj, io.IOBase): + return cls.get_file_data_and_close_file(obj) + elif isinstance(obj, (str, int, float, none_type, bool)): + return obj + elif isinstance(obj, (datetime, date)): + return obj.isoformat() + elif isinstance(obj, ModelSimple): + return cls.sanitize_for_serialization(obj.value) + elif isinstance(obj, (list, tuple)): + return [cls.sanitize_for_serialization(item) for item in obj] + if isinstance(obj, dict): + return {key: cls.sanitize_for_serialization(val) for key, val in obj.items()} + raise ApiValueError('Unable to prepare type {} for serialization'.format(obj.__class__.__name__)) + + def deserialize(self, response, response_type, _check_type): + """Deserializes response into an object. + + :param response: RESTResponse object to be deserialized. + :param response_type: For the response, a tuple containing: + valid classes + a list containing valid classes (for list schemas) + a dict containing a tuple of valid classes as the value + Example values: + (str,) + (Pet,) + (float, none_type) + ([int, none_type],) + ({str: (bool, str, int, float, date, datetime, str, none_type)},) + :param _check_type: boolean, whether to check the types of the data + received from the server + :type _check_type: bool + + :return: deserialized object. + """ + # handle file downloading + # save response body into a tmp file and return the instance + if response_type == (file_type,): + content_disposition = response.getheader("Content-Disposition") + return deserialize_file(response.data, self.configuration, + content_disposition=content_disposition) + + # fetch data from response object + try: + received_data = json.loads(response.data) + except ValueError: + received_data = response.data + + # store our data under the key of 'received_data' so users have some + # context if they are deserializing a string and the data type is wrong + deserialized_data = validate_and_convert_types( + received_data, + response_type, + ['received_data'], + True, + _check_type, + configuration=self.configuration + ) + return deserialized_data + + def call_api( + self, + resource_path: str, + method: str, + path_params: typing.Optional[typing.Dict[str, typing.Any]] = None, + query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, + header_params: typing.Optional[typing.Dict[str, typing.Any]] = None, + body: typing.Optional[typing.Any] = None, + post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None, + files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None, + response_type: typing.Optional[typing.Tuple[typing.Any]] = None, + auth_settings: typing.Optional[typing.List[str]] = None, + async_req: typing.Optional[bool] = None, + _return_http_data_only: typing.Optional[bool] = None, + collection_formats: typing.Optional[typing.Dict[str, str]] = None, + _preload_content: bool = True, + _request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + _host: typing.Optional[str] = None, + _check_type: typing.Optional[bool] = None + ): + """Makes the HTTP request (synchronous) and returns deserialized data. + + To make an async_req request, set the async_req parameter. + + :param resource_path: Path to method endpoint. + :param method: Method to call. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param response_type: For the response, a tuple containing: + valid classes + a list containing valid classes (for list schemas) + a dict containing a tuple of valid classes as the value + Example values: + (str,) + (Pet,) + (float, none_type) + ([int, none_type],) + ({str: (bool, str, int, float, date, datetime, str, none_type)},) + :param files: key -> field name, value -> a list of open file + objects for `multipart/form-data`. + :type files: dict + :param async_req bool: execute request asynchronously + :type async_req: bool, optional + :param _return_http_data_only: response data without head status code + and headers + :type _return_http_data_only: bool, optional + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :type collection_formats: dict, optional + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :type _preload_content: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _check_type: boolean describing if the data back from the server + should have its type checked. + :type _check_type: bool, optional + :return: + If async_req parameter is True, + the request will be called asynchronously. + The method will return the request thread. + If parameter async_req is False or missing, + then the method will return the response directly. + """ + if not async_req: + return self.__call_api(resource_path, method, + path_params, query_params, header_params, + body, post_params, files, + response_type, auth_settings, + _return_http_data_only, collection_formats, + _preload_content, _request_timeout, _host, + _check_type) + + return self.pool.apply_async(self.__call_api, (resource_path, + method, path_params, + query_params, + header_params, body, + post_params, files, + response_type, + auth_settings, + _return_http_data_only, + collection_formats, + _preload_content, + _request_timeout, + _host, _check_type)) + + def request(self, method, url, query_params=None, headers=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): + """Makes the HTTP request using RESTClient.""" + if method == "GET": + return self.rest_client.GET(url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers) + elif method == "HEAD": + return self.rest_client.HEAD(url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers) + elif method == "OPTIONS": + return self.rest_client.OPTIONS(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "POST": + return self.rest_client.POST(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "PUT": + return self.rest_client.PUT(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "PATCH": + return self.rest_client.PATCH(url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + elif method == "DELETE": + return self.rest_client.DELETE(url, + query_params=query_params, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + else: + raise ApiValueError( + "http method must be `GET`, `HEAD`, `OPTIONS`," + " `POST`, `PATCH`, `PUT` or `DELETE`." + ) + + def parameters_to_tuples(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: Parameters as list of tuples, collections formatted + """ + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) + else: + new_params.append((k, v)) + return new_params + + @staticmethod + def get_file_data_and_close_file(file_instance: io.IOBase) -> bytes: + file_data = file_instance.read() + file_instance.close() + return file_data + + def files_parameters(self, files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None): + """Builds form parameters. + + :param files: None or a dict with key=param_name and + value is a list of open file objects + :return: List of tuples of form parameters with file data + """ + if files is None: + return [] + + params = [] + for param_name, file_instances in files.items(): + if file_instances is None: + # if the file field is nullable, skip None values + continue + for file_instance in file_instances: + if file_instance is None: + # if the file field is nullable, skip None values + continue + if file_instance.closed is True: + raise ApiValueError( + "Cannot read a closed file. The passed in file_type " + "for %s must be open." % param_name + ) + filename = os.path.basename(file_instance.name) + filedata = self.get_file_data_and_close_file(file_instance) + mimetype = (mimetypes.guess_type(filename)[0] or + 'application/octet-stream') + params.append( + tuple([param_name, tuple([filename, filedata, mimetype])])) + + return params + + def select_header_accept(self, accepts): + """Returns `Accept` based on an array of accepts provided. + + :param accepts: List of headers. + :return: Accept (e.g. application/json). + """ + if not accepts: + return + + accepts = [x.lower() for x in accepts] + + if 'application/json' in accepts: + return 'application/json' + else: + return ', '.join(accepts) + + def select_header_content_type(self, content_types): + """Returns `Content-Type` based on an array of content_types provided. + + :param content_types: List of content-types. + :return: Content-Type (e.g. application/json). + """ + if not content_types: + return 'application/json' + + content_types = [x.lower() for x in content_types] + + if 'application/json' in content_types or '*/*' in content_types: + return 'application/json' + else: + return content_types[0] + + def update_params_for_auth(self, headers, querys, auth_settings, + resource_path, method, body): + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param querys: Query parameters tuple list to be updated. + :param auth_settings: Authentication setting identifiers list. + :param resource_path: A string representation of the HTTP request resource path. + :param method: A string representation of the HTTP request method. + :param body: A object representing the body of the HTTP request. + The object type is the return value of _encoder.default(). + """ + if not auth_settings: + return + + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + if auth_setting['in'] == 'cookie': + headers['Cookie'] = auth_setting['value'] + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + querys.append((auth_setting['key'], auth_setting['value'])) + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) + + +class Endpoint(object): + def __init__(self, settings=None, params_map=None, root_map=None, + headers_map=None, api_client=None, callable=None): + """Creates an endpoint + + Args: + settings (dict): see below key value pairs + 'response_type' (tuple/None): response type + 'auth' (list): a list of auth type keys + 'endpoint_path' (str): the endpoint path + 'operation_id' (str): endpoint string identifier + 'http_method' (str): POST/PUT/PATCH/GET etc + 'servers' (list): list of str servers that this endpoint is at + params_map (dict): see below key value pairs + 'all' (list): list of str endpoint parameter names + 'required' (list): list of required parameter names + 'nullable' (list): list of nullable parameter names + 'enum' (list): list of parameters with enum values + 'validation' (list): list of parameters with validations + root_map + 'validations' (dict): the dict mapping endpoint parameter tuple + paths to their validation dictionaries + 'allowed_values' (dict): the dict mapping endpoint parameter + tuple paths to their allowed_values (enum) dictionaries + 'openapi_types' (dict): param_name to openapi type + 'attribute_map' (dict): param_name to camelCase name + 'location_map' (dict): param_name to 'body', 'file', 'form', + 'header', 'path', 'query' + collection_format_map (dict): param_name to `csv` etc. + headers_map (dict): see below key value pairs + 'accept' (list): list of Accept header strings + 'content_type' (list): list of Content-Type header strings + api_client (ApiClient) api client instance + callable (function): the function which is invoked when the + Endpoint is called + """ + self.settings = settings + self.params_map = params_map + self.params_map['all'].extend([ + 'async_req', + '_host_index', + '_preload_content', + '_request_timeout', + '_return_http_data_only', + '_check_input_type', + '_check_return_type' + ]) + self.params_map['nullable'].extend(['_request_timeout']) + self.validations = root_map['validations'] + self.allowed_values = root_map['allowed_values'] + self.openapi_types = root_map['openapi_types'] + extra_types = { + 'async_req': (bool,), + '_host_index': (none_type, int), + '_preload_content': (bool,), + '_request_timeout': (none_type, int, (int,), [int]), + '_return_http_data_only': (bool,), + '_check_input_type': (bool,), + '_check_return_type': (bool,) + } + self.openapi_types.update(extra_types) + self.attribute_map = root_map['attribute_map'] + self.location_map = root_map['location_map'] + self.collection_format_map = root_map['collection_format_map'] + self.headers_map = headers_map + self.api_client = api_client + self.callable = callable + + def __validate_inputs(self, kwargs): + for param in self.params_map['enum']: + if param in kwargs: + check_allowed_values( + self.allowed_values, + (param,), + kwargs[param] + ) + + for param in self.params_map['validation']: + if param in kwargs: + check_validations( + self.validations, + (param,), + kwargs[param], + configuration=self.api_client.configuration + ) + + if kwargs['_check_input_type'] is False: + return + + for key, value in kwargs.items(): + fixed_val = validate_and_convert_types( + value, + self.openapi_types[key], + [key], + False, + kwargs['_check_input_type'], + configuration=self.api_client.configuration + ) + kwargs[key] = fixed_val + + def __gather_params(self, kwargs): + params = { + 'body': None, + 'collection_format': {}, + 'file': {}, + 'form': [], + 'header': {}, + 'path': {}, + 'query': [] + } + + for param_name, param_value in kwargs.items(): + param_location = self.location_map.get(param_name) + if param_location is None: + continue + if param_location: + if param_location == 'body': + params['body'] = param_value + continue + base_name = self.attribute_map[param_name] + if (param_location == 'form' and + self.openapi_types[param_name] == (file_type,)): + params['file'][param_name] = [param_value] + elif (param_location == 'form' and + self.openapi_types[param_name] == ([file_type],)): + # param_value is already a list + params['file'][param_name] = param_value + elif param_location in {'form', 'query'}: + param_value_full = (base_name, param_value) + params[param_location].append(param_value_full) + if param_location not in {'form', 'query'}: + params[param_location][base_name] = param_value + collection_format = self.collection_format_map.get(param_name) + if collection_format: + params['collection_format'][base_name] = collection_format + + return params + + def __call__(self, *args, **kwargs): + """ This method is invoked when endpoints are called + Example: + + api_instance = AnotherFakeApi() + api_instance.call_123_test_special_tags # this is an instance of the class Endpoint + api_instance.call_123_test_special_tags() # this invokes api_instance.call_123_test_special_tags.__call__() + which then invokes the callable functions stored in that endpoint at + api_instance.call_123_test_special_tags.callable or self.callable in this class + + """ + return self.callable(self, *args, **kwargs) + + def call_with_http_info(self, **kwargs): + + try: + index = self.api_client.configuration.server_operation_index.get( + self.settings['operation_id'], self.api_client.configuration.server_index + ) if kwargs['_host_index'] is None else kwargs['_host_index'] + server_variables = self.api_client.configuration.server_operation_variables.get( + self.settings['operation_id'], self.api_client.configuration.server_variables + ) + _host = self.api_client.configuration.get_host_from_settings( + index, variables=server_variables, servers=self.settings['servers'] + ) + except IndexError: + if self.settings['servers']: + raise ApiValueError( + "Invalid host index. Must be 0 <= index < %s" % + len(self.settings['servers']) + ) + _host = None + + for key, value in kwargs.items(): + if key not in self.params_map['all']: + raise ApiTypeError( + "Got an unexpected parameter '%s'" + " to method `%s`" % + (key, self.settings['operation_id']) + ) + # only throw this nullable ApiValueError if _check_input_type + # is False, if _check_input_type==True we catch this case + # in self.__validate_inputs + if (key not in self.params_map['nullable'] and value is None + and kwargs['_check_input_type'] is False): + raise ApiValueError( + "Value may not be None for non-nullable parameter `%s`" + " when calling `%s`" % + (key, self.settings['operation_id']) + ) + + for key in self.params_map['required']: + if key not in kwargs.keys(): + raise ApiValueError( + "Missing the required parameter `%s` when calling " + "`%s`" % (key, self.settings['operation_id']) + ) + + self.__validate_inputs(kwargs) + + params = self.__gather_params(kwargs) + + accept_headers_list = self.headers_map['accept'] + if accept_headers_list: + params['header']['Accept'] = self.api_client.select_header_accept( + accept_headers_list) + + content_type_headers_list = self.headers_map['content_type'] + if content_type_headers_list: + header_list = self.api_client.select_header_content_type( + content_type_headers_list) + params['header']['Content-Type'] = header_list + + return self.api_client.call_api( + self.settings['endpoint_path'], self.settings['http_method'], + params['path'], + params['query'], + params['header'], + body=params['body'], + post_params=params['form'], + files=params['file'], + response_type=self.settings['response_type'], + auth_settings=self.settings['auth'], + async_req=kwargs['async_req'], + _check_type=kwargs['_check_return_type'], + _return_http_data_only=kwargs['_return_http_data_only'], + _preload_content=kwargs['_preload_content'], + _request_timeout=kwargs['_request_timeout'], + _host=_host, + collection_formats=params['collection_format']) diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/apis/__init__.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/apis/__init__.py new file mode 100644 index 000000000000..e4c52458a0c2 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/apis/__init__.py @@ -0,0 +1,22 @@ + +# flake8: noqa + +# Import all APIs into this package. +# If you have many APIs here with many many models used in each API this may +# raise a `RecursionError`. +# In order to avoid this, import only the API that you directly need like: +# +# from .api.another_fake_api import AnotherFakeApi +# +# or import this package, but before doing it, use: +# +# import sys +# sys.setrecursionlimit(n) + +# Import APIs into API package: +from petstore_api.api.another_fake_api import AnotherFakeApi +from petstore_api.api.fake_api import FakeApi +from petstore_api.api.fake_classname_tags_123_api import FakeClassnameTags123Api +from petstore_api.api.pet_api import PetApi +from petstore_api.api.store_api import StoreApi +from petstore_api.api.user_api import UserApi diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/configuration.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/configuration.py new file mode 100644 index 000000000000..ccd984b7f5f8 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/configuration.py @@ -0,0 +1,511 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import copy +import logging +import multiprocessing +import sys +import urllib3 + +from http import client as http_client +from petstore_api.exceptions import ApiValueError + + +JSON_SCHEMA_VALIDATION_KEYWORDS = { + 'multipleOf', 'maximum', 'exclusiveMaximum', + 'minimum', 'exclusiveMinimum', 'maxLength', + 'minLength', 'pattern', 'maxItems', 'minItems' +} + +class Configuration(object): + """NOTE: This class is auto generated by OpenAPI Generator + + Ref: https://openapi-generator.tech + Do not edit the class manually. + + :param host: Base url + :param api_key: Dict to store API key(s). + Each entry in the dict specifies an API key. + The dict key is the name of the security scheme in the OAS specification. + The dict value is the API key secret. + :param api_key_prefix: Dict to store API prefix (e.g. Bearer) + The dict key is the name of the security scheme in the OAS specification. + The dict value is an API key prefix when generating the auth data. + :param username: Username for HTTP basic authentication + :param password: Password for HTTP basic authentication + :param discard_unknown_keys: Boolean value indicating whether to discard + unknown properties. A server may send a response that includes additional + properties that are not known by the client in the following scenarios: + 1. The OpenAPI document is incomplete, i.e. it does not match the server + implementation. + 2. The client was generated using an older version of the OpenAPI document + and the server has been upgraded since then. + If a schema in the OpenAPI document defines the additionalProperties attribute, + then all undeclared properties received by the server are injected into the + additional properties map. In that case, there are undeclared properties, and + nothing to discard. + :param disabled_client_side_validations (string): Comma-separated list of + JSON schema validation keywords to disable JSON schema structural validation + rules. The following keywords may be specified: multipleOf, maximum, + exclusiveMaximum, minimum, exclusiveMinimum, maxLength, minLength, pattern, + maxItems, minItems. + By default, the validation is performed for data generated locally by the client + and data received from the server, independent of any validation performed by + the server side. If the input data does not satisfy the JSON schema validation + rules specified in the OpenAPI document, an exception is raised. + If disabled_client_side_validations is set, structural validation is + disabled. This can be useful to troubleshoot data validation problem, such as + when the OpenAPI document validation rules do not match the actual API data + received by the server. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum values before. + :param ssl_ca_cert: str - the path to a file of concatenated CA certificates + in PEM format + + :Example: + + API Key Authentication Example. + Given the following security scheme in the OpenAPI specification: + components: + securitySchemes: + cookieAuth: # name for the security scheme + type: apiKey + in: cookie + name: JSESSIONID # cookie name + + You can programmatically set the cookie: + +conf = petstore_api.Configuration( + api_key={'cookieAuth': 'abc123'} + api_key_prefix={'cookieAuth': 'JSESSIONID'} +) + + The following cookie will be added to the HTTP request: + Cookie: JSESSIONID abc123 + + HTTP Basic Authentication Example. + Given the following security scheme in the OpenAPI specification: + components: + securitySchemes: + http_basic_auth: + type: http + scheme: basic + + Configure API client with HTTP basic authentication: + +conf = petstore_api.Configuration( + username='the-user', + password='the-password', +) + + """ + + _default = None + + def __init__(self, host=None, + api_key=None, api_key_prefix=None, + access_token=None, + username=None, password=None, + discard_unknown_keys=False, + disabled_client_side_validations="", + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, + ssl_ca_cert=None, + ): + """Constructor + """ + self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host + """Default Base url + """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default server variables + """ + self.temp_folder_path = None + """Temp file folder for downloading files + """ + # Authentication Settings + self.access_token = access_token + self.api_key = {} + if api_key: + self.api_key = api_key + """dict to store API key(s) + """ + self.api_key_prefix = {} + if api_key_prefix: + self.api_key_prefix = api_key_prefix + """dict to store API prefix (e.g. Bearer) + """ + self.refresh_api_key_hook = None + """function hook to refresh API key if expired + """ + self.username = username + """Username for HTTP basic authentication + """ + self.password = password + """Password for HTTP basic authentication + """ + self.discard_unknown_keys = discard_unknown_keys + self.disabled_client_side_validations = disabled_client_side_validations + self.logger = {} + """Logging Settings + """ + self.logger["package_logger"] = logging.getLogger("petstore_api") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + self.logger_format = '%(asctime)s %(levelname)s %(message)s' + """Log format + """ + self.logger_stream_handler = None + """Log stream handler + """ + self.logger_file_handler = None + """Log file handler + """ + self.logger_file = None + """Debug file location + """ + self.debug = False + """Debug switch + """ + + self.verify_ssl = True + """SSL/TLS verification + Set this to false to skip verifying SSL certificate when calling API + from https server. + """ + self.ssl_ca_cert = ssl_ca_cert + """Set this to customize the certificate file to verify the peer. + """ + self.cert_file = None + """client certificate file + """ + self.key_file = None + """client key file + """ + self.assert_hostname = None + """Set this to True/False to enable/disable SSL hostname verification. + """ + + self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 + """urllib3 connection pool's maximum number of connections saved + per pool. urllib3 uses 1 connection as default value, but this is + not the best value when you are making a lot of possibly parallel + requests to the same host, which is often the case here. + cpu_count * 5 is used as default value to increase performance. + """ + + self.proxy = None + """Proxy URL + """ + self.proxy_headers = None + """Proxy headers + """ + self.safe_chars_for_path_param = '' + """Safe chars for path_param + """ + self.retries = None + """Adding retries to override urllib3 default value 3 + """ + # Enable client side validation + self.client_side_validation = True + + # Options to pass down to the underlying urllib3 socket + self.socket_options = None + + def __deepcopy__(self, memo): + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k not in ('logger', 'logger_file_handler'): + setattr(result, k, copy.deepcopy(v, memo)) + # shallow copy of loggers + result.logger = copy.copy(self.logger) + # use setters to configure loggers + result.logger_file = self.logger_file + result.debug = self.debug + return result + + def __setattr__(self, name, value): + object.__setattr__(self, name, value) + if name == 'disabled_client_side_validations': + s = set(filter(None, value.split(','))) + for v in s: + if v not in JSON_SCHEMA_VALIDATION_KEYWORDS: + raise ApiValueError( + "Invalid keyword: '{0}''".format(v)) + self._disabled_client_side_validations = s + + @classmethod + def set_default(cls, default): + """Set default instance of configuration. + + It stores default configuration, which can be + returned by get_default_copy method. + + :param default: object of Configuration + """ + cls._default = copy.deepcopy(default) + + @classmethod + def get_default_copy(cls): + """Return new instance of configuration. + + This method returns newly created, based on default constructor, + object of Configuration class or returns a copy of default + configuration passed by the set_default method. + + :return: The configuration object. + """ + if cls._default is not None: + return copy.deepcopy(cls._default) + return Configuration() + + @property + def logger_file(self): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + return self.__logger_file + + @logger_file.setter + def logger_file(self, value): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + self.__logger_file = value + if self.__logger_file: + # If set logging file, + # then add file handler and remove stream handler. + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) + for _, logger in self.logger.items(): + logger.addHandler(self.logger_file_handler) + + @property + def debug(self): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + return self.__debug + + @debug.setter + def debug(self, value): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + self.__debug = value + if self.__debug: + # if debug status is True, turn on debug logging + for _, logger in self.logger.items(): + logger.setLevel(logging.DEBUG) + # turn on http_client debug + http_client.HTTPConnection.debuglevel = 1 + else: + # if debug status is False, turn off debug logging, + # setting log level to default `logging.WARNING` + for _, logger in self.logger.items(): + logger.setLevel(logging.WARNING) + # turn off http_client debug + http_client.HTTPConnection.debuglevel = 0 + + @property + def logger_format(self): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + return self.__logger_format + + @logger_format.setter + def logger_format(self, value): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) + + def get_api_key_with_prefix(self, identifier, alias=None): + """Gets API key (with prefix if set). + + :param identifier: The identifier of apiKey. + :param alias: The alternative identifier of apiKey. + :return: The token for api key authentication. + """ + if self.refresh_api_key_hook is not None: + self.refresh_api_key_hook(self) + key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) + if key: + prefix = self.api_key_prefix.get(identifier) + if prefix: + return "%s %s" % (prefix, key) + else: + return key + + def get_basic_auth_token(self): + """Gets HTTP basic authentication header (string). + + :return: The token for basic HTTP authentication. + """ + username = "" + if self.username is not None: + username = self.username + password = "" + if self.password is not None: + password = self.password + return urllib3.util.make_headers( + basic_auth=username + ':' + password + ).get('authorization') + + def auth_settings(self): + """Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ + auth = {} + if 'api_key' in self.api_key: + auth['api_key'] = { + 'type': 'api_key', + 'in': 'header', + 'key': 'api_key', + 'value': self.get_api_key_with_prefix( + 'api_key', + ), + } + if 'api_key_query' in self.api_key: + auth['api_key_query'] = { + 'type': 'api_key', + 'in': 'query', + 'key': 'api_key_query', + 'value': self.get_api_key_with_prefix( + 'api_key_query', + ), + } + if self.username is not None and self.password is not None: + auth['http_basic_test'] = { + 'type': 'basic', + 'in': 'header', + 'key': 'Authorization', + 'value': self.get_basic_auth_token() + } + if self.access_token is not None: + auth['petstore_auth'] = { + 'type': 'oauth2', + 'in': 'header', + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + } + return auth + + def to_debug_report(self): + """Gets the essential information for debugging. + + :return: The report for debugging. + """ + return "Python SDK Debug Report:\n"\ + "OS: {env}\n"\ + "Python Version: {pyversion}\n"\ + "Version of the API: 1.0.0\n"\ + "SDK Package Version: 1.0.0".\ + format(env=sys.platform, pyversion=sys.version) + + def get_host_settings(self): + """Gets an array of host settings + + :return: An array of host settings + """ + return [ + { + 'url': "http://petstore.swagger.io:80/v2", + 'description': "No description provided", + } + ] + + def get_host_from_settings(self, index, variables=None, servers=None): + """Gets host URL based on the index and variables + :param index: array index of the host settings + :param variables: hash of variable and the corresponding value + :param servers: an array of host settings or None + :return: URL based on host settings + """ + if index is None: + return self._base_path + + variables = {} if variables is None else variables + servers = self.get_host_settings() if servers is None else servers + + try: + server = servers[index] + except IndexError: + raise ValueError( + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) + + url = server['url'] + + # go through variables and replace placeholders + for variable_name, variable in server.get('variables', {}).items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) + + return url + + @property + def host(self): + """Return generated host.""" + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value): + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/exceptions.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/exceptions.py new file mode 100644 index 000000000000..51527f606112 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/exceptions.py @@ -0,0 +1,159 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + + +class OpenApiException(Exception): + """The base exception class for all OpenAPIExceptions""" + + +class ApiTypeError(OpenApiException, TypeError): + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None): + """ Raises an exception for TypeErrors + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list): a list of keys an indices to get to the + current_item + None if unset + valid_classes (tuple): the primitive classes that current item + should be an instance of + None if unset + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + None if unset + """ + self.path_to_item = path_to_item + self.valid_classes = valid_classes + self.key_type = key_type + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiTypeError, self).__init__(full_msg) + + +class ApiValueError(OpenApiException, ValueError): + def __init__(self, msg, path_to_item=None): + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list) the path to the exception in the + received_data dict. None if unset + """ + + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiValueError, self).__init__(full_msg) + + +class ApiAttributeError(OpenApiException, AttributeError): + def __init__(self, msg, path_to_item=None): + """ + Raised when an attribute reference or assignment fails. + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiAttributeError, self).__init__(full_msg) + + +class ApiKeyError(OpenApiException, KeyError): + def __init__(self, msg, path_to_item=None): + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiKeyError, self).__init__(full_msg) + + +class ApiException(OpenApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + if http_resp: + self.status = http_resp.status + self.reason = http_resp.reason + self.body = http_resp.data + self.headers = http_resp.getheaders() + else: + self.status = status + self.reason = reason + self.body = None + self.headers = None + + def __str__(self): + """Custom error messages for exception""" + error_message = "({0})\n"\ + "Reason: {1}\n".format(self.status, self.reason) + if self.headers: + error_message += "HTTP response headers: {0}\n".format( + self.headers) + + if self.body: + error_message += "HTTP response body: {0}\n".format(self.body) + + return error_message + + +class NotFoundException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(NotFoundException, self).__init__(status, reason, http_resp) + + +class UnauthorizedException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(UnauthorizedException, self).__init__(status, reason, http_resp) + + +class ForbiddenException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(ForbiddenException, self).__init__(status, reason, http_resp) + + +class ServiceException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None): + super(ServiceException, self).__init__(status, reason, http_resp) + + +def render_path(path_to_item): + """Returns a string representation of a path""" + result = "" + for pth in path_to_item: + if isinstance(pth, int): + result += "[{0}]".format(pth) + else: + result += "['{0}']".format(pth) + return result diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/__init__.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/__init__.py new file mode 100644 index 000000000000..cfe32b784926 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/__init__.py @@ -0,0 +1,5 @@ +# we can not import model classes here because that would create a circular +# reference which would not work in python2 +# do not import all models into this module because that uses a lot of memory and stack frames +# if you need the ability to import all models from one package, import them with +# from {{packageName}.models import ModelA, ModelB diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_any_type.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_any_type.py new file mode 100644 index 000000000000..34ae88833fbe --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_any_type.py @@ -0,0 +1,255 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class AdditionalPropertiesAnyType(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesAnyType - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesAnyType - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_array.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_array.py new file mode 100644 index 000000000000..55f44f411c27 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_array.py @@ -0,0 +1,255 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class AdditionalPropertiesArray(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return ([bool, date, datetime, dict, float, int, list, str, none_type],) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesArray - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesArray - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_boolean.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_boolean.py new file mode 100644 index 000000000000..b9c5c258e3cc --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_boolean.py @@ -0,0 +1,255 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class AdditionalPropertiesBoolean(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesBoolean - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesBoolean - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_class.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_class.py new file mode 100644 index 000000000000..5a38128ad89e --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_class.py @@ -0,0 +1,289 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class AdditionalPropertiesClass(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'map_string': ({str: (str,)},), # noqa: E501 + 'map_number': ({str: (float,)},), # noqa: E501 + 'map_integer': ({str: (int,)},), # noqa: E501 + 'map_boolean': ({str: (bool,)},), # noqa: E501 + 'map_array_integer': ({str: ([int],)},), # noqa: E501 + 'map_array_anytype': ({str: ([bool, date, datetime, dict, float, int, list, str, none_type],)},), # noqa: E501 + 'map_map_string': ({str: ({str: (str,)},)},), # noqa: E501 + 'map_map_anytype': ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type,)},)},), # noqa: E501 + 'anytype_1': (bool, date, datetime, dict, float, int, list, str, none_type,), # noqa: E501 + 'anytype_2': (bool, date, datetime, dict, float, int, list, str, none_type,), # noqa: E501 + 'anytype_3': (bool, date, datetime, dict, float, int, list, str, none_type,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'map_string': 'map_string', # noqa: E501 + 'map_number': 'map_number', # noqa: E501 + 'map_integer': 'map_integer', # noqa: E501 + 'map_boolean': 'map_boolean', # noqa: E501 + 'map_array_integer': 'map_array_integer', # noqa: E501 + 'map_array_anytype': 'map_array_anytype', # noqa: E501 + 'map_map_string': 'map_map_string', # noqa: E501 + 'map_map_anytype': 'map_map_anytype', # noqa: E501 + 'anytype_1': 'anytype_1', # noqa: E501 + 'anytype_2': 'anytype_2', # noqa: E501 + 'anytype_3': 'anytype_3', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_string ({str: (str,)}): [optional] # noqa: E501 + map_number ({str: (float,)}): [optional] # noqa: E501 + map_integer ({str: (int,)}): [optional] # noqa: E501 + map_boolean ({str: (bool,)}): [optional] # noqa: E501 + map_array_integer ({str: ([int],)}): [optional] # noqa: E501 + map_array_anytype ({str: ([bool, date, datetime, dict, float, int, list, str, none_type],)}): [optional] # noqa: E501 + map_map_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 + map_map_anytype ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type,)},)}): [optional] # noqa: E501 + anytype_1 (bool, date, datetime, dict, float, int, list, str, none_type): [optional] # noqa: E501 + anytype_2 (bool, date, datetime, dict, float, int, list, str, none_type): no type is set for this. [optional] # noqa: E501 + anytype_3 (bool, date, datetime, dict, float, int, list, str, none_type): because of a bug in swagger-parser, this should have values {str: (str, int, float...)} but instead we get any type. See https://github.com/swagger-api/swagger-parser/issues/1378. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_string ({str: (str,)}): [optional] # noqa: E501 + map_number ({str: (float,)}): [optional] # noqa: E501 + map_integer ({str: (int,)}): [optional] # noqa: E501 + map_boolean ({str: (bool,)}): [optional] # noqa: E501 + map_array_integer ({str: ([int],)}): [optional] # noqa: E501 + map_array_anytype ({str: ([bool, date, datetime, dict, float, int, list, str, none_type],)}): [optional] # noqa: E501 + map_map_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 + map_map_anytype ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type,)},)}): [optional] # noqa: E501 + anytype_1 (bool, date, datetime, dict, float, int, list, str, none_type): [optional] # noqa: E501 + anytype_2 (bool, date, datetime, dict, float, int, list, str, none_type): no type is set for this. [optional] # noqa: E501 + anytype_3 (bool, date, datetime, dict, float, int, list, str, none_type): because of a bug in swagger-parser, this should have values {str: (str, int, float...)} but instead we get any type. See https://github.com/swagger-api/swagger-parser/issues/1378. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_integer.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_integer.py new file mode 100644 index 000000000000..f6f80f89c7ad --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_integer.py @@ -0,0 +1,255 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class AdditionalPropertiesInteger(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (int,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesInteger - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesInteger - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_number.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_number.py new file mode 100644 index 000000000000..6c094699462a --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_number.py @@ -0,0 +1,255 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class AdditionalPropertiesNumber(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (float,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesNumber - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesNumber - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_object.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_object.py new file mode 100644 index 000000000000..1fa671aff9b2 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_object.py @@ -0,0 +1,255 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class AdditionalPropertiesObject(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return ({str: (bool, date, datetime, dict, float, int, list, str, none_type,)},) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesObject - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesObject - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_string.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_string.py new file mode 100644 index 000000000000..0afa8a9e6376 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_string.py @@ -0,0 +1,255 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class AdditionalPropertiesString(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (str,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesString - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesString - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal.py new file mode 100644 index 000000000000..d1a9e4afbb06 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal.py @@ -0,0 +1,272 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.cat import Cat + from petstore_api.model.dog import Dog + globals()['Cat'] = Cat + globals()['Dog'] = Dog + + +class Animal(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'class_name': (str,), # noqa: E501 + 'color': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + lazy_import() + val = { + 'Cat': Cat, + 'Dog': Dog, + } + if not val: + return None + return {'class_name': val} + + attribute_map = { + 'class_name': 'className', # noqa: E501 + 'color': 'color', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """Animal - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, class_name, *args, **kwargs): # noqa: E501 + """Animal - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal_farm.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal_farm.py new file mode 100644 index 000000000000..042a8274ee7a --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal_farm.py @@ -0,0 +1,283 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.animal import Animal + globals()['Animal'] = Animal + + +class AnimalFarm(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'value': ([Animal],), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """AnimalFarm - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] ([Animal]): # noqa: E501 + + Keyword Args: + value ([Animal]): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """AnimalFarm - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] ([Animal]): # noqa: E501 + + Keyword Args: + value ([Animal]): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/api_response.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/api_response.py new file mode 100644 index 000000000000..5abc32eafe2a --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/api_response.py @@ -0,0 +1,257 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class ApiResponse(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'code': (int,), # noqa: E501 + 'type': (str,), # noqa: E501 + 'message': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'code': 'code', # noqa: E501 + 'type': 'type', # noqa: E501 + 'message': 'message', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ApiResponse - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + code (int): [optional] # noqa: E501 + type (str): [optional] # noqa: E501 + message (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ApiResponse - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + code (int): [optional] # noqa: E501 + type (str): [optional] # noqa: E501 + message (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_array_of_number_only.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_array_of_number_only.py new file mode 100644 index 000000000000..905860719151 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_array_of_number_only.py @@ -0,0 +1,249 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class ArrayOfArrayOfNumberOnly(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'array_array_number': ([[float]],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'array_array_number': 'ArrayArrayNumber', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayOfArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_array_number ([[float]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ArrayOfArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_array_number ([[float]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_number_only.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_number_only.py new file mode 100644 index 000000000000..e343a727d6e1 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_number_only.py @@ -0,0 +1,249 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class ArrayOfNumberOnly(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'array_number': ([float],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'array_number': 'ArrayNumber', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_number ([float]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_number ([float]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_test.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_test.py new file mode 100644 index 000000000000..13649acbe327 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_test.py @@ -0,0 +1,262 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.read_only_first import ReadOnlyFirst + globals()['ReadOnlyFirst'] = ReadOnlyFirst + + +class ArrayTest(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'array_of_string': ([str],), # noqa: E501 + 'array_array_of_integer': ([[int]],), # noqa: E501 + 'array_array_of_model': ([[ReadOnlyFirst]],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'array_of_string': 'array_of_string', # noqa: E501 + 'array_array_of_integer': 'array_array_of_integer', # noqa: E501 + 'array_array_of_model': 'array_array_of_model', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_of_string ([str]): [optional] # noqa: E501 + array_array_of_integer ([[int]]): [optional] # noqa: E501 + array_array_of_model ([[ReadOnlyFirst]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ArrayTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_of_string ([str]): [optional] # noqa: E501 + array_array_of_integer ([[int]]): [optional] # noqa: E501 + array_array_of_model ([[ReadOnlyFirst]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/capitalization.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/capitalization.py new file mode 100644 index 000000000000..75a354d29595 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/capitalization.py @@ -0,0 +1,269 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class Capitalization(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'small_camel': (str,), # noqa: E501 + 'capital_camel': (str,), # noqa: E501 + 'small_snake': (str,), # noqa: E501 + 'capital_snake': (str,), # noqa: E501 + 'sca_eth_flow_points': (str,), # noqa: E501 + 'att_name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'small_camel': 'smallCamel', # noqa: E501 + 'capital_camel': 'CapitalCamel', # noqa: E501 + 'small_snake': 'small_Snake', # noqa: E501 + 'capital_snake': 'Capital_Snake', # noqa: E501 + 'sca_eth_flow_points': 'SCA_ETH_Flow_Points', # noqa: E501 + 'att_name': 'ATT_NAME', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Capitalization - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + small_camel (str): [optional] # noqa: E501 + capital_camel (str): [optional] # noqa: E501 + small_snake (str): [optional] # noqa: E501 + capital_snake (str): [optional] # noqa: E501 + sca_eth_flow_points (str): [optional] # noqa: E501 + att_name (str): Name of the pet . [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Capitalization - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + small_camel (str): [optional] # noqa: E501 + capital_camel (str): [optional] # noqa: E501 + small_snake (str): [optional] # noqa: E501 + capital_snake (str): [optional] # noqa: E501 + sca_eth_flow_points (str): [optional] # noqa: E501 + att_name (str): Name of the pet . [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat.py new file mode 100644 index 000000000000..c67141833849 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat.py @@ -0,0 +1,318 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.animal import Animal + from petstore_api.model.cat_all_of import CatAllOf + globals()['Animal'] = Animal + globals()['CatAllOf'] = CatAllOf + + +class Cat(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'class_name': (str,), # noqa: E501 + 'declawed': (bool,), # noqa: E501 + 'color': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + val = { + } + if not val: + return None + return {'class_name': val} + + attribute_map = { + 'class_name': 'className', # noqa: E501 + 'declawed': 'declawed', # noqa: E501 + 'color': 'color', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Cat - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + declawed (bool): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Cat - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + declawed (bool): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + Animal, + CatAllOf, + ], + 'oneOf': [ + ], + } diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat_all_of.py new file mode 100644 index 000000000000..5ed2c9cdf280 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat_all_of.py @@ -0,0 +1,249 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class CatAllOf(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'declawed': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'declawed': 'declawed', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """CatAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + declawed (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """CatAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + declawed (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/category.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/category.py new file mode 100644 index 000000000000..cf8a13849754 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/category.py @@ -0,0 +1,261 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class Category(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (str,), # noqa: E501 + 'id': (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + 'id': 'id', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Category - a model defined in OpenAPI + + Args: + + Keyword Args: + name (str): defaults to "default-name" # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + """ + + name = kwargs.get('name', "default-name") + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Category - a model defined in OpenAPI + + Args: + + Keyword Args: + name (str): defaults to "default-name" # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + """ + + name = kwargs.get('name', "default-name") + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child.py new file mode 100644 index 000000000000..02324cb640c1 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child.py @@ -0,0 +1,315 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.child_all_of import ChildAllOf + from petstore_api.model.parent import Parent + globals()['ChildAllOf'] = ChildAllOf + globals()['Parent'] = Parent + + +class Child(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'radio_waves': (bool,), # noqa: E501 + 'tele_vision': (bool,), # noqa: E501 + 'inter_net': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'radio_waves': 'radioWaves', # noqa: E501 + 'tele_vision': 'teleVision', # noqa: E501 + 'inter_net': 'interNet', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Child - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + radio_waves (bool): [optional] # noqa: E501 + tele_vision (bool): [optional] # noqa: E501 + inter_net (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Child - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + radio_waves (bool): [optional] # noqa: E501 + tele_vision (bool): [optional] # noqa: E501 + inter_net (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ChildAllOf, + Parent, + ], + 'oneOf': [ + ], + } diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_all_of.py new file mode 100644 index 000000000000..e3f8db2e199a --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_all_of.py @@ -0,0 +1,249 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class ChildAllOf(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'inter_net': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'inter_net': 'interNet', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + inter_net (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ChildAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + inter_net (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat.py new file mode 100644 index 000000000000..fe267715ade7 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat.py @@ -0,0 +1,314 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.child_cat_all_of import ChildCatAllOf + from petstore_api.model.parent_pet import ParentPet + globals()['ChildCatAllOf'] = ChildCatAllOf + globals()['ParentPet'] = ParentPet + + +class ChildCat(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'pet_type': (str,), # noqa: E501 + 'name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + val = { + } + if not val: + return None + return {'pet_type': val} + + attribute_map = { + 'pet_type': 'pet_type', # noqa: E501 + 'name': 'name', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildCat - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ChildCat - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ChildCatAllOf, + ParentPet, + ], + 'oneOf': [ + ], + } diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat_all_of.py new file mode 100644 index 000000000000..ceacfbcd7b15 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat_all_of.py @@ -0,0 +1,249 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class ChildCatAllOf(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildCatAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ChildCatAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog.py new file mode 100644 index 000000000000..c1b0dc5e868a --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog.py @@ -0,0 +1,314 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.child_dog_all_of import ChildDogAllOf + from petstore_api.model.parent_pet import ParentPet + globals()['ChildDogAllOf'] = ChildDogAllOf + globals()['ParentPet'] = ParentPet + + +class ChildDog(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'pet_type': (str,), # noqa: E501 + 'bark': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + val = { + } + if not val: + return None + return {'pet_type': val} + + attribute_map = { + 'pet_type': 'pet_type', # noqa: E501 + 'bark': 'bark', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildDog - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bark (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ChildDog - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bark (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ChildDogAllOf, + ParentPet, + ], + 'oneOf': [ + ], + } diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog_all_of.py new file mode 100644 index 000000000000..41c87c20618b --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog_all_of.py @@ -0,0 +1,249 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class ChildDogAllOf(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'bark': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'bark': 'bark', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildDogAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bark (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ChildDogAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bark (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard.py new file mode 100644 index 000000000000..ef95bd5b8ca4 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard.py @@ -0,0 +1,314 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.child_lizard_all_of import ChildLizardAllOf + from petstore_api.model.parent_pet import ParentPet + globals()['ChildLizardAllOf'] = ChildLizardAllOf + globals()['ParentPet'] = ParentPet + + +class ChildLizard(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'pet_type': (str,), # noqa: E501 + 'loves_rocks': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + val = { + } + if not val: + return None + return {'pet_type': val} + + attribute_map = { + 'pet_type': 'pet_type', # noqa: E501 + 'loves_rocks': 'lovesRocks', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildLizard - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + loves_rocks (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ChildLizard - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + loves_rocks (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + ChildLizardAllOf, + ParentPet, + ], + 'oneOf': [ + ], + } diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard_all_of.py new file mode 100644 index 000000000000..f88016d08793 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard_all_of.py @@ -0,0 +1,249 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class ChildLizardAllOf(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'loves_rocks': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'loves_rocks': 'lovesRocks', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildLizardAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + loves_rocks (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ChildLizardAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + loves_rocks (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/class_model.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/class_model.py new file mode 100644 index 000000000000..0ecc844f84c3 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/class_model.py @@ -0,0 +1,249 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class ClassModel(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + '_class': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + '_class': '_class', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ClassModel - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ClassModel - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/fake_get_inline_additional_properties_payload_array_data.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/client.py similarity index 58% rename from samples/openapi3/client/petstore/python/petstore_api/model/fake_get_inline_additional_properties_payload_array_data.py rename to samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/client.py index bbbc449b4298..2b4ac4b91a82 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/fake_get_inline_additional_properties_payload_array_data.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/client.py @@ -25,9 +25,12 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError -class FakeGetInlineAdditionalPropertiesPayloadArrayData(ModelNormal): + +class Client(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -72,7 +75,7 @@ def openapi_types(): and the value is attribute type. """ return { - 'labels': ([str, none_type],), # noqa: E501 + 'client': (str,), # noqa: E501 } @cached_property @@ -81,11 +84,88 @@ def discriminator(): attribute_map = { - 'labels': 'labels', # noqa: E501 + 'client': 'client', # noqa: E501 + } + + read_only_vars = { } _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Client - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + client (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -97,7 +177,7 @@ def discriminator(): @convert_js_args_to_python_args def __init__(self, *args, **kwargs): # noqa: E501 - """FakeGetInlineAdditionalPropertiesPayloadArrayData - a model defined in OpenAPI + """Client - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -130,7 +210,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - labels ([str, none_type]): [optional] # noqa: E501 + client (str): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -164,3 +244,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog.py new file mode 100644 index 000000000000..d01bdc6e34d0 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog.py @@ -0,0 +1,318 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.animal import Animal + from petstore_api.model.dog_all_of import DogAllOf + globals()['Animal'] = Animal + globals()['DogAllOf'] = DogAllOf + + +class Dog(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'class_name': (str,), # noqa: E501 + 'breed': (str,), # noqa: E501 + 'color': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + val = { + } + if not val: + return None + return {'class_name': val} + + attribute_map = { + 'class_name': 'className', # noqa: E501 + 'breed': 'breed', # noqa: E501 + 'color': 'color', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Dog - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + breed (str): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Dog - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + breed (str): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + Animal, + DogAllOf, + ], + 'oneOf': [ + ], + } diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog_all_of.py new file mode 100644 index 000000000000..cdc633dc66ff --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog_all_of.py @@ -0,0 +1,249 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class DogAllOf(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'breed': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'breed': 'breed', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """DogAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + breed (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """DogAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + breed (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_arrays.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_arrays.py new file mode 100644 index 000000000000..39fe0ffb838c --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_arrays.py @@ -0,0 +1,261 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class EnumArrays(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('just_symbol',): { + '>=': ">=", + '$': "$", + }, + ('array_enum',): { + 'FISH': "fish", + 'CRAB': "crab", + }, + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'just_symbol': (str,), # noqa: E501 + 'array_enum': ([str],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'just_symbol': 'just_symbol', # noqa: E501 + 'array_enum': 'array_enum', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """EnumArrays - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_symbol (str): [optional] # noqa: E501 + array_enum ([str]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """EnumArrays - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_symbol (str): [optional] # noqa: E501 + array_enum ([str]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_class.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_class.py new file mode 100644 index 000000000000..b0ed3d8966d9 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_class.py @@ -0,0 +1,275 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class EnumClass(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('value',): { + '_ABC': "_abc", + '-EFG': "-efg", + '(XYZ)': "(xyz)", + }, + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (str,), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """EnumClass - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + + Keyword Args: + value (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = "-efg" + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """EnumClass - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + + Keyword Args: + value (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = "-efg" + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_test.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_test.py new file mode 100644 index 000000000000..a75f4774ae71 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_test.py @@ -0,0 +1,294 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.string_enum import StringEnum + globals()['StringEnum'] = StringEnum + + +class EnumTest(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('enum_string_required',): { + 'UPPER': "UPPER", + 'LOWER': "lower", + 'EMPTY': "", + }, + ('enum_string',): { + 'UPPER': "UPPER", + 'LOWER': "lower", + 'EMPTY': "", + }, + ('enum_integer',): { + '1': 1, + '-1': -1, + }, + ('enum_number',): { + '1.1': 1.1, + '-1.2': -1.2, + }, + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'enum_string_required': (str,), # noqa: E501 + 'enum_string': (str,), # noqa: E501 + 'enum_integer': (int,), # noqa: E501 + 'enum_number': (float,), # noqa: E501 + 'string_enum': (StringEnum,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'enum_string_required': 'enum_string_required', # noqa: E501 + 'enum_string': 'enum_string', # noqa: E501 + 'enum_integer': 'enum_integer', # noqa: E501 + 'enum_number': 'enum_number', # noqa: E501 + 'string_enum': 'stringEnum', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, enum_string_required, *args, **kwargs): # noqa: E501 + """EnumTest - a model defined in OpenAPI + + Args: + enum_string_required (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + enum_string (str): [optional] # noqa: E501 + enum_integer (int): [optional] # noqa: E501 + enum_number (float): [optional] # noqa: E501 + string_enum (StringEnum): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.enum_string_required = enum_string_required + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, enum_string_required, *args, **kwargs): # noqa: E501 + """EnumTest - a model defined in OpenAPI + + Args: + enum_string_required (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + enum_string (str): [optional] # noqa: E501 + enum_integer (int): [optional] # noqa: E501 + enum_number (float): [optional] # noqa: E501 + string_enum (StringEnum): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.enum_string_required = enum_string_required + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file.py new file mode 100644 index 000000000000..a2beaf44a016 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file.py @@ -0,0 +1,249 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class File(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'source_uri': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'source_uri': 'sourceURI', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """File - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + source_uri (str): Test capitalization. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """File - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + source_uri (str): Test capitalization. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file_schema_test_class.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file_schema_test_class.py new file mode 100644 index 000000000000..e3f7608e95da --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file_schema_test_class.py @@ -0,0 +1,258 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.file import File + globals()['File'] = File + + +class FileSchemaTestClass(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'file': (File,), # noqa: E501 + 'files': ([File],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'file': 'file', # noqa: E501 + 'files': 'files', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """FileSchemaTestClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + file (File): [optional] # noqa: E501 + files ([File]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """FileSchemaTestClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + file (File): [optional] # noqa: E501 + files ([File]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/format_test.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/format_test.py new file mode 100644 index 000000000000..1588b1de0531 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/format_test.py @@ -0,0 +1,344 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class FormatTest(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + ('number',): { + 'inclusive_maximum': 543.2, + 'inclusive_minimum': 32.1, + }, + ('byte',): { + 'regex': { + 'pattern': r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', # noqa: E501 + }, + }, + ('password',): { + 'max_length': 64, + 'min_length': 10, + }, + ('integer',): { + 'inclusive_maximum': 100, + 'inclusive_minimum': 10, + }, + ('int32',): { + 'inclusive_maximum': 200, + 'inclusive_minimum': 20, + }, + ('float',): { + 'inclusive_maximum': 987.6, + 'inclusive_minimum': 54.3, + }, + ('double',): { + 'inclusive_maximum': 123.4, + 'inclusive_minimum': 67.8, + }, + ('string',): { + 'regex': { + 'pattern': r'^[a-z]+$', # noqa: E501 + 'flags': (re.IGNORECASE) + }, + }, + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'number': (float,), # noqa: E501 + 'byte': (str,), # noqa: E501 + 'date': (date,), # noqa: E501 + 'password': (str,), # noqa: E501 + 'integer': (int,), # noqa: E501 + 'int32': (int,), # noqa: E501 + 'int64': (int,), # noqa: E501 + 'float': (float,), # noqa: E501 + 'double': (float,), # noqa: E501 + 'string': (str,), # noqa: E501 + 'binary': (file_type,), # noqa: E501 + 'date_time': (datetime,), # noqa: E501 + 'uuid': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'number': 'number', # noqa: E501 + 'byte': 'byte', # noqa: E501 + 'date': 'date', # noqa: E501 + 'password': 'password', # noqa: E501 + 'integer': 'integer', # noqa: E501 + 'int32': 'int32', # noqa: E501 + 'int64': 'int64', # noqa: E501 + 'float': 'float', # noqa: E501 + 'double': 'double', # noqa: E501 + 'string': 'string', # noqa: E501 + 'binary': 'binary', # noqa: E501 + 'date_time': 'dateTime', # noqa: E501 + 'uuid': 'uuid', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, number, byte, date, password, *args, **kwargs): # noqa: E501 + """FormatTest - a model defined in OpenAPI + + Args: + number (float): + byte (str): + date (date): + password (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + integer (int): [optional] # noqa: E501 + int32 (int): [optional] # noqa: E501 + int64 (int): [optional] # noqa: E501 + float (float): [optional] # noqa: E501 + double (float): [optional] # noqa: E501 + string (str): [optional] # noqa: E501 + binary (file_type): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + uuid (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.number = number + self.byte = byte + self.date = date + self.password = password + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, number, byte, date, password, *args, **kwargs): # noqa: E501 + """FormatTest - a model defined in OpenAPI + + Args: + number (float): + byte (str): + date (date): + password (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + integer (int): [optional] # noqa: E501 + int32 (int): [optional] # noqa: E501 + int64 (int): [optional] # noqa: E501 + float (float): [optional] # noqa: E501 + double (float): [optional] # noqa: E501 + string (str): [optional] # noqa: E501 + binary (file_type): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + uuid (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.number = number + self.byte = byte + self.date = date + self.password = password + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent.py new file mode 100644 index 000000000000..c25e0b3f843d --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent.py @@ -0,0 +1,249 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class Grandparent(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'radio_waves': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'radio_waves': 'radioWaves', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Grandparent - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + radio_waves (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Grandparent - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + radio_waves (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent_animal.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent_animal.py new file mode 100644 index 000000000000..e053af7d5387 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent_animal.py @@ -0,0 +1,274 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.child_cat import ChildCat + from petstore_api.model.child_dog import ChildDog + from petstore_api.model.child_lizard import ChildLizard + from petstore_api.model.parent_pet import ParentPet + globals()['ChildCat'] = ChildCat + globals()['ChildDog'] = ChildDog + globals()['ChildLizard'] = ChildLizard + globals()['ParentPet'] = ParentPet + + +class GrandparentAnimal(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'pet_type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + lazy_import() + val = { + 'ChildCat': ChildCat, + 'ChildDog': ChildDog, + 'ChildLizard': ChildLizard, + 'ParentPet': ParentPet, + } + if not val: + return None + return {'pet_type': val} + + attribute_map = { + 'pet_type': 'pet_type', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, pet_type, *args, **kwargs): # noqa: E501 + """GrandparentAnimal - a model defined in OpenAPI + + Args: + pet_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.pet_type = pet_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, pet_type, *args, **kwargs): # noqa: E501 + """GrandparentAnimal - a model defined in OpenAPI + + Args: + pet_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.pet_type = pet_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/has_only_read_only.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/has_only_read_only.py new file mode 100644 index 000000000000..294a16ddc46d --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/has_only_read_only.py @@ -0,0 +1,255 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class HasOnlyReadOnly(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'bar': (str,), # noqa: E501 + 'foo': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'bar': 'bar', # noqa: E501 + 'foo': 'foo', # noqa: E501 + } + + read_only_vars = { + 'bar', # noqa: E501 + 'foo', # noqa: E501 + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """HasOnlyReadOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + foo (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """HasOnlyReadOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + foo (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/list.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/list.py new file mode 100644 index 000000000000..18863e57bc74 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/list.py @@ -0,0 +1,249 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class List(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + '_123_list': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + '_123_list': '123-list', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """List - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _123_list (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """List - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _123_list (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/map_test.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/map_test.py new file mode 100644 index 000000000000..612810807990 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/map_test.py @@ -0,0 +1,270 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.string_boolean_map import StringBooleanMap + globals()['StringBooleanMap'] = StringBooleanMap + + +class MapTest(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('map_of_enum_string',): { + 'UPPER': "UPPER", + 'LOWER': "lower", + }, + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'map_map_of_string': ({str: ({str: (str,)},)},), # noqa: E501 + 'map_of_enum_string': ({str: (str,)},), # noqa: E501 + 'direct_map': ({str: (bool,)},), # noqa: E501 + 'indirect_map': (StringBooleanMap,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'map_map_of_string': 'map_map_of_string', # noqa: E501 + 'map_of_enum_string': 'map_of_enum_string', # noqa: E501 + 'direct_map': 'direct_map', # noqa: E501 + 'indirect_map': 'indirect_map', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """MapTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_map_of_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 + map_of_enum_string ({str: (str,)}): [optional] # noqa: E501 + direct_map ({str: (bool,)}): [optional] # noqa: E501 + indirect_map (StringBooleanMap): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """MapTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_map_of_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 + map_of_enum_string ({str: (str,)}): [optional] # noqa: E501 + direct_map ({str: (bool,)}): [optional] # noqa: E501 + indirect_map (StringBooleanMap): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/mixed_properties_and_additional_properties_class.py new file mode 100644 index 000000000000..954689631564 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/mixed_properties_and_additional_properties_class.py @@ -0,0 +1,262 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.animal import Animal + globals()['Animal'] = Animal + + +class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'uuid': (str,), # noqa: E501 + 'date_time': (datetime,), # noqa: E501 + 'map': ({str: (Animal,)},), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'uuid': 'uuid', # noqa: E501 + 'date_time': 'dateTime', # noqa: E501 + 'map': 'map', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """MixedPropertiesAndAdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + uuid (str): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + map ({str: (Animal,)}): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """MixedPropertiesAndAdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + uuid (str): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + map ({str: (Animal,)}): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model200_response.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model200_response.py new file mode 100644 index 000000000000..d094c7f84c64 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model200_response.py @@ -0,0 +1,253 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class Model200Response(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (int,), # noqa: E501 + '_class': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + '_class': 'class', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Model200Response - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (int): [optional] # noqa: E501 + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Model200Response - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (int): [optional] # noqa: E501 + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_return.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_return.py new file mode 100644 index 000000000000..51bcf6f1649f --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_return.py @@ -0,0 +1,249 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class ModelReturn(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + '_return': (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + '_return': 'return', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ModelReturn - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _return (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ModelReturn - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _return (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/name.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/name.py new file mode 100644 index 000000000000..4ee3e1ed2bf1 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/name.py @@ -0,0 +1,269 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class Name(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (int,), # noqa: E501 + 'snake_case': (int,), # noqa: E501 + '_property': (str,), # noqa: E501 + '_123_number': (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + 'snake_case': 'snake_case', # noqa: E501 + '_property': 'property', # noqa: E501 + '_123_number': '123Number', # noqa: E501 + } + + read_only_vars = { + 'snake_case', # noqa: E501 + '_123_number', # noqa: E501 + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, *args, **kwargs): # noqa: E501 + """Name - a model defined in OpenAPI + + Args: + name (int): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + snake_case (int): [optional] # noqa: E501 + _property (str): [optional] # noqa: E501 + _123_number (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, name, *args, **kwargs): # noqa: E501 + """Name - a model defined in OpenAPI + + Args: + name (int): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + snake_case (int): [optional] # noqa: E501 + _property (str): [optional] # noqa: E501 + _123_number (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_only.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_only.py new file mode 100644 index 000000000000..c4163787bc14 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_only.py @@ -0,0 +1,249 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class NumberOnly(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'just_number': (float,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'just_number': 'JustNumber', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """NumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_number (float): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """NumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_number (float): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_with_validations.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_with_validations.py new file mode 100644 index 000000000000..5d66fec5ec67 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_with_validations.py @@ -0,0 +1,282 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class NumberWithValidations(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + ('value',): { + 'inclusive_maximum': 2E+1, + 'inclusive_minimum': 1E+1, + }, + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (float,), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """NumberWithValidations - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (float): # noqa: E501 + + Keyword Args: + value (float): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """NumberWithValidations - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (float): # noqa: E501 + + Keyword Args: + value (float): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/object_model_with_ref_props.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/object_model_with_ref_props.py new file mode 100644 index 000000000000..dfe5d05cf051 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/object_model_with_ref_props.py @@ -0,0 +1,262 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.number_with_validations import NumberWithValidations + globals()['NumberWithValidations'] = NumberWithValidations + + +class ObjectModelWithRefProps(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'my_number': (NumberWithValidations,), # noqa: E501 + 'my_string': (str,), # noqa: E501 + 'my_boolean': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'my_number': 'my_number', # noqa: E501 + 'my_string': 'my_string', # noqa: E501 + 'my_boolean': 'my_boolean', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ObjectModelWithRefProps - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + my_number (NumberWithValidations): [optional] # noqa: E501 + my_string (str): [optional] # noqa: E501 + my_boolean (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ObjectModelWithRefProps - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + my_number (NumberWithValidations): [optional] # noqa: E501 + my_string (str): [optional] # noqa: E501 + my_boolean (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/order.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/order.py new file mode 100644 index 000000000000..b69e94ae36be --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/order.py @@ -0,0 +1,274 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class Order(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('status',): { + 'PLACED': "placed", + 'APPROVED': "approved", + 'DELIVERED': "delivered", + }, + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'id': (int,), # noqa: E501 + 'pet_id': (int,), # noqa: E501 + 'quantity': (int,), # noqa: E501 + 'ship_date': (datetime,), # noqa: E501 + 'status': (str,), # noqa: E501 + 'complete': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'id': 'id', # noqa: E501 + 'pet_id': 'petId', # noqa: E501 + 'quantity': 'quantity', # noqa: E501 + 'ship_date': 'shipDate', # noqa: E501 + 'status': 'status', # noqa: E501 + 'complete': 'complete', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Order - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + pet_id (int): [optional] # noqa: E501 + quantity (int): [optional] # noqa: E501 + ship_date (datetime): [optional] # noqa: E501 + status (str): Order Status. [optional] # noqa: E501 + complete (bool): [optional] if omitted the server will use the default value of False # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Order - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + pet_id (int): [optional] # noqa: E501 + quantity (int): [optional] # noqa: E501 + ship_date (datetime): [optional] # noqa: E501 + status (str): Order Status. [optional] # noqa: E501 + complete (bool): [optional] if omitted the server will use the default value of False # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent.py new file mode 100644 index 000000000000..13a722ff4b3a --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent.py @@ -0,0 +1,311 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.grandparent import Grandparent + from petstore_api.model.parent_all_of import ParentAllOf + globals()['Grandparent'] = Grandparent + globals()['ParentAllOf'] = ParentAllOf + + +class Parent(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'radio_waves': (bool,), # noqa: E501 + 'tele_vision': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'radio_waves': 'radioWaves', # noqa: E501 + 'tele_vision': 'teleVision', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Parent - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + radio_waves (bool): [optional] # noqa: E501 + tele_vision (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Parent - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + radio_waves (bool): [optional] # noqa: E501 + tele_vision (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + Grandparent, + ParentAllOf, + ], + 'oneOf': [ + ], + } diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_all_of.py new file mode 100644 index 000000000000..97916a1dd4e2 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_all_of.py @@ -0,0 +1,249 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class ParentAllOf(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'tele_vision': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'tele_vision': 'teleVision', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ParentAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + tele_vision (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ParentAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + tele_vision (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_pet.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_pet.py new file mode 100644 index 000000000000..a20c0d1b8672 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_pet.py @@ -0,0 +1,317 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.child_cat import ChildCat + from petstore_api.model.child_dog import ChildDog + from petstore_api.model.child_lizard import ChildLizard + from petstore_api.model.grandparent_animal import GrandparentAnimal + globals()['ChildCat'] = ChildCat + globals()['ChildDog'] = ChildDog + globals()['ChildLizard'] = ChildLizard + globals()['GrandparentAnimal'] = GrandparentAnimal + + +class ParentPet(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'pet_type': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + lazy_import() + val = { + 'ChildCat': ChildCat, + 'ChildDog': ChildDog, + 'ChildLizard': ChildLizard, + } + if not val: + return None + return {'pet_type': val} + + attribute_map = { + 'pet_type': 'pet_type', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ParentPet - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ParentPet - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + GrandparentAnimal, + ], + 'oneOf': [ + ], + } diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/pet.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/pet.py new file mode 100644 index 000000000000..a7b888a2aa38 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/pet.py @@ -0,0 +1,289 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.category import Category + from petstore_api.model.tag import Tag + globals()['Category'] = Category + globals()['Tag'] = Tag + + +class Pet(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('status',): { + 'AVAILABLE': "available", + 'PENDING': "pending", + 'SOLD': "sold", + }, + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'name': (str,), # noqa: E501 + 'photo_urls': ([str],), # noqa: E501 + 'id': (int,), # noqa: E501 + 'category': (Category,), # noqa: E501 + 'tags': ([Tag],), # noqa: E501 + 'status': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + 'photo_urls': 'photoUrls', # noqa: E501 + 'id': 'id', # noqa: E501 + 'category': 'category', # noqa: E501 + 'tags': 'tags', # noqa: E501 + 'status': 'status', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, photo_urls, *args, **kwargs): # noqa: E501 + """Pet - a model defined in OpenAPI + + Args: + name (str): + photo_urls ([str]): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + category (Category): [optional] # noqa: E501 + tags ([Tag]): [optional] # noqa: E501 + status (str): pet status in the store. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + self.photo_urls = photo_urls + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, name, photo_urls, *args, **kwargs): # noqa: E501 + """Pet - a model defined in OpenAPI + + Args: + name (str): + photo_urls ([str]): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + category (Category): [optional] # noqa: E501 + tags ([Tag]): [optional] # noqa: E501 + status (str): pet status in the store. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + self.photo_urls = photo_urls + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/player.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/player.py new file mode 100644 index 000000000000..104c4d2900df --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/player.py @@ -0,0 +1,259 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class Player(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (str,), # noqa: E501 + 'enemy_player': (Player,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + 'enemy_player': 'enemyPlayer', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, *args, **kwargs): # noqa: E501 + """Player - a model defined in OpenAPI + + Args: + name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + enemy_player (Player): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, name, *args, **kwargs): # noqa: E501 + """Player - a model defined in OpenAPI + + Args: + name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + enemy_player (Player): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/read_only_first.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/read_only_first.py new file mode 100644 index 000000000000..ad0bfbaac115 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/read_only_first.py @@ -0,0 +1,254 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class ReadOnlyFirst(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'bar': (str,), # noqa: E501 + 'baz': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'bar': 'bar', # noqa: E501 + 'baz': 'baz', # noqa: E501 + } + + read_only_vars = { + 'bar', # noqa: E501 + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ReadOnlyFirst - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + baz (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ReadOnlyFirst - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + baz (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/special_model_name.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/special_model_name.py new file mode 100644 index 000000000000..fa13828d6b9f --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/special_model_name.py @@ -0,0 +1,249 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class SpecialModelName(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'special_property_name': (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'special_property_name': '$special[property.name]', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """SpecialModelName - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + special_property_name (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """SpecialModelName - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + special_property_name (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_boolean_map.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_boolean_map.py new file mode 100644 index 000000000000..05f8527fec1e --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_boolean_map.py @@ -0,0 +1,251 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class StringBooleanMap(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """StringBooleanMap - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """StringBooleanMap - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_enum.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_enum.py new file mode 100644 index 000000000000..2397dd59fc95 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_enum.py @@ -0,0 +1,283 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class StringEnum(ModelSimple): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('value',): { + 'PLACED': "placed", + 'APPROVED': "approved", + 'DELIVERED': "delivered", + }, + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'value': (str,), + } + + @cached_property + def discriminator(): + return None + + + attribute_map = {} + + read_only_vars = set() + + _composed_schemas = None + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): + """StringEnum - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str):, must be one of ["placed", "approved", "delivered", ] # noqa: E501 + + Keyword Args: + value (str):, must be one of ["placed", "approved", "delivered", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """StringEnum - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str):, must be one of ["placed", "approved", "delivered", ] # noqa: E501 + + Keyword Args: + value (str):, must be one of ["placed", "approved", "delivered", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/tag.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/tag.py new file mode 100644 index 000000000000..913976557b40 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/tag.py @@ -0,0 +1,257 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class Tag(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'id': (int,), # noqa: E501 + 'name': (str,), # noqa: E501 + 'full_name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'id': 'id', # noqa: E501 + 'name': 'name', # noqa: E501 + 'full_name': 'fullName', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Tag - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + name (str): [optional] # noqa: E501 + full_name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Tag - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + name (str): [optional] # noqa: E501 + full_name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_default.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_default.py new file mode 100644 index 000000000000..b156cbac46e3 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_default.py @@ -0,0 +1,295 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class TypeHolderDefault(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'string_item': (str,), # noqa: E501 + 'number_item': (float,), # noqa: E501 + 'integer_item': (int,), # noqa: E501 + 'bool_item': (bool,), # noqa: E501 + 'array_item': ([int],), # noqa: E501 + 'date_item': (date,), # noqa: E501 + 'datetime_item': (datetime,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'string_item': 'string_item', # noqa: E501 + 'number_item': 'number_item', # noqa: E501 + 'integer_item': 'integer_item', # noqa: E501 + 'bool_item': 'bool_item', # noqa: E501 + 'array_item': 'array_item', # noqa: E501 + 'date_item': 'date_item', # noqa: E501 + 'datetime_item': 'datetime_item', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, array_item, *args, **kwargs): # noqa: E501 + """TypeHolderDefault - a model defined in OpenAPI + + Args: + array_item ([int]): + + Keyword Args: + string_item (str): defaults to "what" # noqa: E501 + number_item (float): defaults to 1.234 # noqa: E501 + integer_item (int): defaults to -2 # noqa: E501 + bool_item (bool): defaults to True # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + date_item (date): [optional] # noqa: E501 + datetime_item (datetime): [optional] # noqa: E501 + """ + + string_item = kwargs.get('string_item', "what") + number_item = kwargs.get('number_item', 1.234) + integer_item = kwargs.get('integer_item', -2) + bool_item = kwargs.get('bool_item', True) + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.string_item = string_item + self.number_item = number_item + self.integer_item = integer_item + self.bool_item = bool_item + self.array_item = array_item + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, array_item, *args, **kwargs): # noqa: E501 + """TypeHolderDefault - a model defined in OpenAPI + + Args: + array_item ([int]): + + Keyword Args: + string_item (str): defaults to "what" # noqa: E501 + number_item (float): defaults to 1.234 # noqa: E501 + integer_item (int): defaults to -2 # noqa: E501 + bool_item (bool): defaults to True # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + date_item (date): [optional] # noqa: E501 + datetime_item (datetime): [optional] # noqa: E501 + """ + + string_item = kwargs.get('string_item', "what") + number_item = kwargs.get('number_item', 1.234) + integer_item = kwargs.get('integer_item', -2) + bool_item = kwargs.get('bool_item', True) + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.string_item = string_item + self.number_item = number_item + self.integer_item = integer_item + self.bool_item = bool_item + self.array_item = array_item + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_example.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_example.py new file mode 100644 index 000000000000..c7a3f13b63ce --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_example.py @@ -0,0 +1,294 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class TypeHolderExample(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('string_item',): { + 'WHAT': "what", + }, + ('number_item',): { + '1.234': 1.234, + }, + ('integer_item',): { + '-2': -2, + }, + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'string_item': (str,), # noqa: E501 + 'number_item': (float,), # noqa: E501 + 'integer_item': (int,), # noqa: E501 + 'bool_item': (bool,), # noqa: E501 + 'array_item': ([int],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'string_item': 'string_item', # noqa: E501 + 'number_item': 'number_item', # noqa: E501 + 'integer_item': 'integer_item', # noqa: E501 + 'bool_item': 'bool_item', # noqa: E501 + 'array_item': 'array_item', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, bool_item, array_item, *args, **kwargs): # noqa: E501 + """TypeHolderExample - a model defined in OpenAPI + + Args: + bool_item (bool): + array_item ([int]): + + Keyword Args: + string_item (str): defaults to "what", must be one of ["what", ] # noqa: E501 + number_item (float): defaults to 1.234, must be one of [1.234, ] # noqa: E501 + integer_item (int): defaults to -2, must be one of [-2, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + string_item = kwargs.get('string_item', "what") + number_item = kwargs.get('number_item', 1.234) + integer_item = kwargs.get('integer_item', -2) + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.string_item = string_item + self.number_item = number_item + self.integer_item = integer_item + self.bool_item = bool_item + self.array_item = array_item + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, bool_item, array_item, *args, **kwargs): # noqa: E501 + """TypeHolderExample - a model defined in OpenAPI + + Args: + bool_item (bool): + array_item ([int]): + + Keyword Args: + string_item (str): defaults to "what", must be one of ["what", ] # noqa: E501 + number_item (float): defaults to 1.234, must be one of [1.234, ] # noqa: E501 + integer_item (int): defaults to -2, must be one of [-2, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + string_item = kwargs.get('string_item', "what") + number_item = kwargs.get('number_item', 1.234) + integer_item = kwargs.get('integer_item', -2) + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.string_item = string_item + self.number_item = number_item + self.integer_item = integer_item + self.bool_item = bool_item + self.array_item = array_item + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/user.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/user.py new file mode 100644 index 000000000000..a3a4019042be --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/user.py @@ -0,0 +1,277 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class User(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'id': (int,), # noqa: E501 + 'username': (str,), # noqa: E501 + 'first_name': (str,), # noqa: E501 + 'last_name': (str,), # noqa: E501 + 'email': (str,), # noqa: E501 + 'password': (str,), # noqa: E501 + 'phone': (str,), # noqa: E501 + 'user_status': (int,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'id': 'id', # noqa: E501 + 'username': 'username', # noqa: E501 + 'first_name': 'firstName', # noqa: E501 + 'last_name': 'lastName', # noqa: E501 + 'email': 'email', # noqa: E501 + 'password': 'password', # noqa: E501 + 'phone': 'phone', # noqa: E501 + 'user_status': 'userStatus', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """User - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + username (str): [optional] # noqa: E501 + first_name (str): [optional] # noqa: E501 + last_name (str): [optional] # noqa: E501 + email (str): [optional] # noqa: E501 + password (str): [optional] # noqa: E501 + phone (str): [optional] # noqa: E501 + user_status (int): User Status. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """User - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + username (str): [optional] # noqa: E501 + first_name (str): [optional] # noqa: E501 + last_name (str): [optional] # noqa: E501 + email (str): [optional] # noqa: E501 + password (str): [optional] # noqa: E501 + phone (str): [optional] # noqa: E501 + user_status (int): User Status. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/xml_item.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/xml_item.py new file mode 100644 index 000000000000..183234163189 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/xml_item.py @@ -0,0 +1,361 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class XmlItem(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'attribute_string': (str,), # noqa: E501 + 'attribute_number': (float,), # noqa: E501 + 'attribute_integer': (int,), # noqa: E501 + 'attribute_boolean': (bool,), # noqa: E501 + 'wrapped_array': ([int],), # noqa: E501 + 'name_string': (str,), # noqa: E501 + 'name_number': (float,), # noqa: E501 + 'name_integer': (int,), # noqa: E501 + 'name_boolean': (bool,), # noqa: E501 + 'name_array': ([int],), # noqa: E501 + 'name_wrapped_array': ([int],), # noqa: E501 + 'prefix_string': (str,), # noqa: E501 + 'prefix_number': (float,), # noqa: E501 + 'prefix_integer': (int,), # noqa: E501 + 'prefix_boolean': (bool,), # noqa: E501 + 'prefix_array': ([int],), # noqa: E501 + 'prefix_wrapped_array': ([int],), # noqa: E501 + 'namespace_string': (str,), # noqa: E501 + 'namespace_number': (float,), # noqa: E501 + 'namespace_integer': (int,), # noqa: E501 + 'namespace_boolean': (bool,), # noqa: E501 + 'namespace_array': ([int],), # noqa: E501 + 'namespace_wrapped_array': ([int],), # noqa: E501 + 'prefix_ns_string': (str,), # noqa: E501 + 'prefix_ns_number': (float,), # noqa: E501 + 'prefix_ns_integer': (int,), # noqa: E501 + 'prefix_ns_boolean': (bool,), # noqa: E501 + 'prefix_ns_array': ([int],), # noqa: E501 + 'prefix_ns_wrapped_array': ([int],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'attribute_string': 'attribute_string', # noqa: E501 + 'attribute_number': 'attribute_number', # noqa: E501 + 'attribute_integer': 'attribute_integer', # noqa: E501 + 'attribute_boolean': 'attribute_boolean', # noqa: E501 + 'wrapped_array': 'wrapped_array', # noqa: E501 + 'name_string': 'name_string', # noqa: E501 + 'name_number': 'name_number', # noqa: E501 + 'name_integer': 'name_integer', # noqa: E501 + 'name_boolean': 'name_boolean', # noqa: E501 + 'name_array': 'name_array', # noqa: E501 + 'name_wrapped_array': 'name_wrapped_array', # noqa: E501 + 'prefix_string': 'prefix_string', # noqa: E501 + 'prefix_number': 'prefix_number', # noqa: E501 + 'prefix_integer': 'prefix_integer', # noqa: E501 + 'prefix_boolean': 'prefix_boolean', # noqa: E501 + 'prefix_array': 'prefix_array', # noqa: E501 + 'prefix_wrapped_array': 'prefix_wrapped_array', # noqa: E501 + 'namespace_string': 'namespace_string', # noqa: E501 + 'namespace_number': 'namespace_number', # noqa: E501 + 'namespace_integer': 'namespace_integer', # noqa: E501 + 'namespace_boolean': 'namespace_boolean', # noqa: E501 + 'namespace_array': 'namespace_array', # noqa: E501 + 'namespace_wrapped_array': 'namespace_wrapped_array', # noqa: E501 + 'prefix_ns_string': 'prefix_ns_string', # noqa: E501 + 'prefix_ns_number': 'prefix_ns_number', # noqa: E501 + 'prefix_ns_integer': 'prefix_ns_integer', # noqa: E501 + 'prefix_ns_boolean': 'prefix_ns_boolean', # noqa: E501 + 'prefix_ns_array': 'prefix_ns_array', # noqa: E501 + 'prefix_ns_wrapped_array': 'prefix_ns_wrapped_array', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """XmlItem - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + attribute_string (str): [optional] # noqa: E501 + attribute_number (float): [optional] # noqa: E501 + attribute_integer (int): [optional] # noqa: E501 + attribute_boolean (bool): [optional] # noqa: E501 + wrapped_array ([int]): [optional] # noqa: E501 + name_string (str): [optional] # noqa: E501 + name_number (float): [optional] # noqa: E501 + name_integer (int): [optional] # noqa: E501 + name_boolean (bool): [optional] # noqa: E501 + name_array ([int]): [optional] # noqa: E501 + name_wrapped_array ([int]): [optional] # noqa: E501 + prefix_string (str): [optional] # noqa: E501 + prefix_number (float): [optional] # noqa: E501 + prefix_integer (int): [optional] # noqa: E501 + prefix_boolean (bool): [optional] # noqa: E501 + prefix_array ([int]): [optional] # noqa: E501 + prefix_wrapped_array ([int]): [optional] # noqa: E501 + namespace_string (str): [optional] # noqa: E501 + namespace_number (float): [optional] # noqa: E501 + namespace_integer (int): [optional] # noqa: E501 + namespace_boolean (bool): [optional] # noqa: E501 + namespace_array ([int]): [optional] # noqa: E501 + namespace_wrapped_array ([int]): [optional] # noqa: E501 + prefix_ns_string (str): [optional] # noqa: E501 + prefix_ns_number (float): [optional] # noqa: E501 + prefix_ns_integer (int): [optional] # noqa: E501 + prefix_ns_boolean (bool): [optional] # noqa: E501 + prefix_ns_array ([int]): [optional] # noqa: E501 + prefix_ns_wrapped_array ([int]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """XmlItem - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + attribute_string (str): [optional] # noqa: E501 + attribute_number (float): [optional] # noqa: E501 + attribute_integer (int): [optional] # noqa: E501 + attribute_boolean (bool): [optional] # noqa: E501 + wrapped_array ([int]): [optional] # noqa: E501 + name_string (str): [optional] # noqa: E501 + name_number (float): [optional] # noqa: E501 + name_integer (int): [optional] # noqa: E501 + name_boolean (bool): [optional] # noqa: E501 + name_array ([int]): [optional] # noqa: E501 + name_wrapped_array ([int]): [optional] # noqa: E501 + prefix_string (str): [optional] # noqa: E501 + prefix_number (float): [optional] # noqa: E501 + prefix_integer (int): [optional] # noqa: E501 + prefix_boolean (bool): [optional] # noqa: E501 + prefix_array ([int]): [optional] # noqa: E501 + prefix_wrapped_array ([int]): [optional] # noqa: E501 + namespace_string (str): [optional] # noqa: E501 + namespace_number (float): [optional] # noqa: E501 + namespace_integer (int): [optional] # noqa: E501 + namespace_boolean (bool): [optional] # noqa: E501 + namespace_array ([int]): [optional] # noqa: E501 + namespace_wrapped_array ([int]): [optional] # noqa: E501 + prefix_ns_string (str): [optional] # noqa: E501 + prefix_ns_number (float): [optional] # noqa: E501 + prefix_ns_integer (int): [optional] # noqa: E501 + prefix_ns_boolean (bool): [optional] # noqa: E501 + prefix_ns_array ([int]): [optional] # noqa: E501 + prefix_ns_wrapped_array ([int]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model_utils.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model_utils.py new file mode 100644 index 000000000000..97f9b2881cc5 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model_utils.py @@ -0,0 +1,1992 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from datetime import date, datetime # noqa: F401 +import inspect +import io +import os +import pprint +import re +import tempfile + +from dateutil.parser import parse + +from petstore_api.exceptions import ( + ApiKeyError, + ApiAttributeError, + ApiTypeError, + ApiValueError, +) + +none_type = type(None) +file_type = io.IOBase + + +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(_self, *args, **kwargs): + """ + An attribute named `self` received from the api will conflicts with the reserved `self` + parameter of a class method. During generation, `self` attributes are mapped + to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. + """ + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python(kwargs, _self if isinstance(_self, type) else _self.__class__) + return fn(_self, *args, **kwargs) + return wrapped_init + + +class cached_property(object): + # this caches the result of the function call for fn with no inputs + # use this as a decorator on fuction methods that you want converted + # into cached properties + result_key = '_results' + + def __init__(self, fn): + self._fn = fn + + def __get__(self, instance, cls=None): + if self.result_key in vars(self): + return vars(self)[self.result_key] + else: + result = self._fn() + setattr(self, self.result_key, result) + return result + + +PRIMITIVE_TYPES = (list, float, int, bool, datetime, date, str, file_type) + +def allows_single_value_input(cls): + """ + This function returns True if the input composed schema model or any + descendant model allows a value only input + This is true for cases where oneOf contains items like: + oneOf: + - float + - NumberWithValidation + - StringEnum + - ArrayModel + - null + TODO: lru_cache this + """ + if ( + issubclass(cls, ModelSimple) or + cls in PRIMITIVE_TYPES + ): + return True + elif issubclass(cls, ModelComposed): + if not cls._composed_schemas['oneOf']: + return False + return any(allows_single_value_input(c) for c in cls._composed_schemas['oneOf']) + return False + +def composed_model_input_classes(cls): + """ + This function returns a list of the possible models that can be accepted as + inputs. + TODO: lru_cache this + """ + if issubclass(cls, ModelSimple) or cls in PRIMITIVE_TYPES: + return [cls] + elif issubclass(cls, ModelNormal): + if cls.discriminator is None: + return [cls] + else: + return get_discriminated_classes(cls) + elif issubclass(cls, ModelComposed): + if not cls._composed_schemas['oneOf']: + return [] + if cls.discriminator is None: + input_classes = [] + for c in cls._composed_schemas['oneOf']: + input_classes.extend(composed_model_input_classes(c)) + return input_classes + else: + return get_discriminated_classes(cls) + return [] + + +class OpenApiModel(object): + """The base class for all OpenAPIModels""" + + def set_attribute(self, name, value): + # this is only used to set properties on self + + path_to_item = [] + if self._path_to_item: + path_to_item.extend(self._path_to_item) + path_to_item.append(name) + + if name in self.openapi_types: + required_types_mixed = self.openapi_types[name] + elif self.additional_properties_type is None: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + path_to_item + ) + elif self.additional_properties_type is not None: + required_types_mixed = self.additional_properties_type + + if get_simple_class(name) != str: + error_msg = type_error_message( + var_name=name, + var_value=name, + valid_classes=(str,), + key_type=True + ) + raise ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=(str,), + key_type=True + ) + + if self._check_type: + value = validate_and_convert_types( + value, required_types_mixed, path_to_item, self._spec_property_naming, + self._check_type, configuration=self._configuration) + if (name,) in self.allowed_values: + check_allowed_values( + self.allowed_values, + (name,), + value + ) + if (name,) in self.validations: + check_validations( + self.validations, + (name,), + value, + self._configuration + ) + self.__dict__['_data_store'][name] = value + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + return not self == other + + def __setattr__(self, attr, value): + """set the value of an attribute using dot notation: `instance.attr = val`""" + self[attr] = value + + def __getattr__(self, attr): + """get the value of an attribute using dot notation: `instance.attr`""" + return self.__getitem__(attr) + + def __new__(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return super(OpenApiModel, cls).__new__(cls) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return super(OpenApiModel, cls).__new__(cls) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = super(OpenApiModel, cls).__new__(cls) + self_inst.__init__(*args, **kwargs) + + new_inst = new_cls.__new__(new_cls, *args, **kwargs) + new_inst.__init__(*args, **kwargs) + return new_inst + + + @classmethod + @convert_js_args_to_python_args + def _new_from_openapi_data(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return cls._from_openapi_data(*args, **kwargs) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return cls._from_openapi_data(*args, **kwargs) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = cls._from_openapi_data(*args, **kwargs) + + + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + return new_inst + + +class ModelSimple(OpenApiModel): + """the parent class of models whose type != object in their + swagger/openapi""" + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + self.set_attribute(name, value) + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + return self.__dict__['_data_store'].get(name, default) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + if name in self: + return self.get(name) + + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + + def __contains__(self, name): + """used by `in` operator to check if an attrbute value was set in an instance: `'attr' in instance`""" + if name in self.required_properties: + return name in self.__dict__ + + return name in self.__dict__['_data_store'] + + def to_str(self): + """Returns the string representation of the model""" + return str(self.value) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + this_val = self._data_store['value'] + that_val = other._data_store['value'] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + return vals_equal + + +class ModelNormal(OpenApiModel): + """the parent class of models whose type == object in their + swagger/openapi""" + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + self.set_attribute(name, value) + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + return self.__dict__['_data_store'].get(name, default) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + if name in self: + return self.get(name) + + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + + def __contains__(self, name): + """used by `in` operator to check if an attrbute value was set in an instance: `'attr' in instance`""" + if name in self.required_properties: + return name in self.__dict__ + + return name in self.__dict__['_data_store'] + + def to_dict(self): + """Returns the model properties as a dict""" + return model_to_dict(self, serialize=False) + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + if not set(self._data_store.keys()) == set(other._data_store.keys()): + return False + for _var_name, this_val in self._data_store.items(): + that_val = other._data_store[_var_name] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if not vals_equal: + return False + return True + + +class ModelComposed(OpenApiModel): + """the parent class of models whose type == object in their + swagger/openapi and have oneOf/allOf/anyOf + + When one sets a property we use var_name_to_model_instances to store the value in + the correct class instances + run any type checking + validation code. + When one gets a property we use var_name_to_model_instances to get the value + from the correct class instances. + This allows multiple composed schemas to contain the same property with additive + constraints on the value. + + _composed_schemas (dict) stores the anyOf/allOf/oneOf classes + key (str): allOf/oneOf/anyOf + value (list): the classes in the XOf definition. + Note: none_type can be included when the openapi document version >= 3.1.0 + _composed_instances (list): stores a list of instances of the composed schemas + defined in _composed_schemas. When properties are accessed in the self instance, + they are returned from the self._data_store or the data stores in the instances + in self._composed_schemas + _var_name_to_model_instances (dict): maps between a variable name on self and + the composed instances (self included) which contain that data + key (str): property name + value (list): list of class instances, self or instances in _composed_instances + which contain the value that the key is referring to. + """ + + def __setitem__(self, name, value): + """set the value of an attribute using square-bracket notation: `instance[attr] = val`""" + if name in self.required_properties: + self.__dict__[name] = value + return + + """ + Use cases: + 1. additional_properties_type is None (additionalProperties == False in spec) + Check for property presence in self.openapi_types + if not present then throw an error + if present set in self, set attribute + always set on composed schemas + 2. additional_properties_type exists + set attribute on self + always set on composed schemas + """ + if self.additional_properties_type is None: + """ + For an attribute to exist on a composed schema it must: + - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND + - fulfill schema_requirements in each oneOf/anyOf/allOf schemas + + schema_requirements: + For an attribute to exist on a schema it must: + - be present in properties at the schema OR + - have additionalProperties unset (defaults additionalProperties = any type) OR + - have additionalProperties set + """ + if name not in self.openapi_types: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + # attribute must be set on self and composed instances + self.set_attribute(name, value) + for model_instance in self._composed_instances: + setattr(model_instance, name, value) + if name not in self._var_name_to_model_instances: + # we assigned an additional property + self.__dict__['_var_name_to_model_instances'][name] = self._composed_instances + [self] + return None + + __unset_attribute_value__ = object() + + def get(self, name, default=None): + """returns the value of an attribute or some default value if the attribute was not set""" + if name in self.required_properties: + return self.__dict__[name] + + # get the attribute from the correct instance + model_instances = self._var_name_to_model_instances.get(name) + values = [] + # A composed model stores self and child (oneof/anyOf/allOf) models under + # self._var_name_to_model_instances. + # Any property must exist in self and all model instances + # The value stored in all model instances must be the same + if model_instances: + for model_instance in model_instances: + if name in model_instance._data_store: + v = model_instance._data_store[name] + if v not in values: + values.append(v) + len_values = len(values) + if len_values == 0: + return default + elif len_values == 1: + return values[0] + elif len_values > 1: + raise ApiValueError( + "Values stored for property {0} in {1} differ when looking " + "at self and self's composed instances. All values must be " + "the same".format(name, type(self).__name__), + [e for e in [self._path_to_item, name] if e] + ) + + def __getitem__(self, name): + """get the value of an attribute using square-bracket notation: `instance[attr]`""" + value = self.get(name, self.__unset_attribute_value__) + if value is self.__unset_attribute_value__: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + return value + + def __contains__(self, name): + """used by `in` operator to check if an attrbute value was set in an instance: `'attr' in instance`""" + + if name in self.required_properties: + return name in self.__dict__ + + model_instances = self._var_name_to_model_instances.get( + name, self._additional_properties_model_instances) + + if model_instances: + for model_instance in model_instances: + if name in model_instance._data_store: + return True + + return False + + def to_dict(self): + """Returns the model properties as a dict""" + return model_to_dict(self, serialize=False) + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + if not set(self._data_store.keys()) == set(other._data_store.keys()): + return False + for _var_name, this_val in self._data_store.items(): + that_val = other._data_store[_var_name] + types = set() + types.add(this_val.__class__) + types.add(that_val.__class__) + vals_equal = this_val == that_val + if not vals_equal: + return False + return True + + +COERCION_INDEX_BY_TYPE = { + ModelComposed: 0, + ModelNormal: 1, + ModelSimple: 2, + none_type: 3, # The type of 'None'. + list: 4, + dict: 5, + float: 6, + int: 7, + bool: 8, + datetime: 9, + date: 10, + str: 11, + file_type: 12, # 'file_type' is an alias for the built-in 'file' or 'io.IOBase' type. +} + +# these are used to limit what type conversions we try to do +# when we have a valid type already and we want to try converting +# to another type +UPCONVERSION_TYPE_PAIRS = ( + (str, datetime), + (str, date), + (int, float), # A float may be serialized as an integer, e.g. '3' is a valid serialized float. + (list, ModelComposed), + (dict, ModelComposed), + (str, ModelComposed), + (int, ModelComposed), + (float, ModelComposed), + (list, ModelComposed), + (list, ModelNormal), + (dict, ModelNormal), + (str, ModelSimple), + (int, ModelSimple), + (float, ModelSimple), + (list, ModelSimple), +) + +COERCIBLE_TYPE_PAIRS = { + False: ( # client instantiation of a model with client data + # (dict, ModelComposed), + # (list, ModelComposed), + # (dict, ModelNormal), + # (list, ModelNormal), + # (str, ModelSimple), + # (int, ModelSimple), + # (float, ModelSimple), + # (list, ModelSimple), + # (str, int), + # (str, float), + # (str, datetime), + # (str, date), + # (int, str), + # (float, str), + ), + True: ( # server -> client data + (dict, ModelComposed), + (list, ModelComposed), + (dict, ModelNormal), + (list, ModelNormal), + (str, ModelSimple), + (int, ModelSimple), + (float, ModelSimple), + (list, ModelSimple), + # (str, int), + # (str, float), + (str, datetime), + (str, date), + # (int, str), + # (float, str), + (str, file_type) + ), +} + + +def get_simple_class(input_value): + """Returns an input_value's simple class that we will use for type checking + Python2: + float and int will return int, where int is the python3 int backport + str and unicode will return str, where str is the python3 str backport + Note: float and int ARE both instances of int backport + Note: str_py2 and unicode_py2 are NOT both instances of str backport + + Args: + input_value (class/class_instance): the item for which we will return + the simple class + """ + if isinstance(input_value, type): + # input_value is a class + return input_value + elif isinstance(input_value, tuple): + return tuple + elif isinstance(input_value, list): + return list + elif isinstance(input_value, dict): + return dict + elif isinstance(input_value, none_type): + return none_type + elif isinstance(input_value, file_type): + return file_type + elif isinstance(input_value, bool): + # this must be higher than the int check because + # isinstance(True, int) == True + return bool + elif isinstance(input_value, int): + return int + elif isinstance(input_value, datetime): + # this must be higher than the date check because + # isinstance(datetime_instance, date) == True + return datetime + elif isinstance(input_value, date): + return date + elif isinstance(input_value, str): + return str + return type(input_value) + + +def check_allowed_values(allowed_values, input_variable_path, input_values): + """Raises an exception if the input_values are not allowed + + Args: + allowed_values (dict): the allowed_values dict + input_variable_path (tuple): the path to the input variable + input_values (list/str/int/float/date/datetime): the values that we + are checking to see if they are in allowed_values + """ + these_allowed_values = list(allowed_values[input_variable_path].values()) + if (isinstance(input_values, list) + and not set(input_values).issubset( + set(these_allowed_values))): + invalid_values = ", ".join( + map(str, set(input_values) - set(these_allowed_values))), + raise ApiValueError( + "Invalid values for `%s` [%s], must be a subset of [%s]" % + ( + input_variable_path[0], + invalid_values, + ", ".join(map(str, these_allowed_values)) + ) + ) + elif (isinstance(input_values, dict) + and not set( + input_values.keys()).issubset(set(these_allowed_values))): + invalid_values = ", ".join( + map(str, set(input_values.keys()) - set(these_allowed_values))) + raise ApiValueError( + "Invalid keys in `%s` [%s], must be a subset of [%s]" % + ( + input_variable_path[0], + invalid_values, + ", ".join(map(str, these_allowed_values)) + ) + ) + elif (not isinstance(input_values, (list, dict)) + and input_values not in these_allowed_values): + raise ApiValueError( + "Invalid value for `%s` (%s), must be one of %s" % + ( + input_variable_path[0], + input_values, + these_allowed_values + ) + ) + + +def is_json_validation_enabled(schema_keyword, configuration=None): + """Returns true if JSON schema validation is enabled for the specified + validation keyword. This can be used to skip JSON schema structural validation + as requested in the configuration. + + Args: + schema_keyword (string): the name of a JSON schema validation keyword. + configuration (Configuration): the configuration class. + """ + + return (configuration is None or + not hasattr(configuration, '_disabled_client_side_validations') or + schema_keyword not in configuration._disabled_client_side_validations) + + +def check_validations( + validations, input_variable_path, input_values, + configuration=None): + """Raises an exception if the input_values are invalid + + Args: + validations (dict): the validation dictionary. + input_variable_path (tuple): the path to the input variable. + input_values (list/str/int/float/date/datetime): the values that we + are checking. + configuration (Configuration): the configuration class. + """ + + if input_values is None: + return + + current_validations = validations[input_variable_path] + if (is_json_validation_enabled('multipleOf', configuration) and + 'multiple_of' in current_validations and + isinstance(input_values, (int, float)) and + not (float(input_values) / current_validations['multiple_of']).is_integer()): + # Note 'multipleOf' will be as good as the floating point arithmetic. + raise ApiValueError( + "Invalid value for `%s`, value must be a multiple of " + "`%s`" % ( + input_variable_path[0], + current_validations['multiple_of'] + ) + ) + + if (is_json_validation_enabled('maxLength', configuration) and + 'max_length' in current_validations and + len(input_values) > current_validations['max_length']): + raise ApiValueError( + "Invalid value for `%s`, length must be less than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['max_length'] + ) + ) + + if (is_json_validation_enabled('minLength', configuration) and + 'min_length' in current_validations and + len(input_values) < current_validations['min_length']): + raise ApiValueError( + "Invalid value for `%s`, length must be greater than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['min_length'] + ) + ) + + if (is_json_validation_enabled('maxItems', configuration) and + 'max_items' in current_validations and + len(input_values) > current_validations['max_items']): + raise ApiValueError( + "Invalid value for `%s`, number of items must be less than or " + "equal to `%s`" % ( + input_variable_path[0], + current_validations['max_items'] + ) + ) + + if (is_json_validation_enabled('minItems', configuration) and + 'min_items' in current_validations and + len(input_values) < current_validations['min_items']): + raise ValueError( + "Invalid value for `%s`, number of items must be greater than or " + "equal to `%s`" % ( + input_variable_path[0], + current_validations['min_items'] + ) + ) + + items = ('exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum', + 'inclusive_minimum') + if (any(item in current_validations for item in items)): + if isinstance(input_values, list): + max_val = max(input_values) + min_val = min(input_values) + elif isinstance(input_values, dict): + max_val = max(input_values.values()) + min_val = min(input_values.values()) + else: + max_val = input_values + min_val = input_values + + if (is_json_validation_enabled('exclusiveMaximum', configuration) and + 'exclusive_maximum' in current_validations and + max_val >= current_validations['exclusive_maximum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value less than `%s`" % ( + input_variable_path[0], + current_validations['exclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('maximum', configuration) and + 'inclusive_maximum' in current_validations and + max_val > current_validations['inclusive_maximum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value less than or equal to " + "`%s`" % ( + input_variable_path[0], + current_validations['inclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('exclusiveMinimum', configuration) and + 'exclusive_minimum' in current_validations and + min_val <= current_validations['exclusive_minimum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value greater than `%s`" % + ( + input_variable_path[0], + current_validations['exclusive_maximum'] + ) + ) + + if (is_json_validation_enabled('minimum', configuration) and + 'inclusive_minimum' in current_validations and + min_val < current_validations['inclusive_minimum']): + raise ApiValueError( + "Invalid value for `%s`, must be a value greater than or equal " + "to `%s`" % ( + input_variable_path[0], + current_validations['inclusive_minimum'] + ) + ) + flags = current_validations.get('regex', {}).get('flags', 0) + if (is_json_validation_enabled('pattern', configuration) and + 'regex' in current_validations and + not re.search(current_validations['regex']['pattern'], + input_values, flags=flags)): + err_msg = r"Invalid value for `%s`, must match regular expression `%s`" % ( + input_variable_path[0], + current_validations['regex']['pattern'] + ) + if flags != 0: + # Don't print the regex flags if the flags are not + # specified in the OAS document. + err_msg = r"%s with flags=`%s`" % (err_msg, flags) + raise ApiValueError(err_msg) + + +def order_response_types(required_types): + """Returns the required types sorted in coercion order + + Args: + required_types (list/tuple): collection of classes or instance of + list or dict with class information inside it. + + Returns: + (list): coercion order sorted collection of classes or instance + of list or dict with class information inside it. + """ + + def index_getter(class_or_instance): + if isinstance(class_or_instance, list): + return COERCION_INDEX_BY_TYPE[list] + elif isinstance(class_or_instance, dict): + return COERCION_INDEX_BY_TYPE[dict] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelComposed)): + return COERCION_INDEX_BY_TYPE[ModelComposed] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelNormal)): + return COERCION_INDEX_BY_TYPE[ModelNormal] + elif (inspect.isclass(class_or_instance) + and issubclass(class_or_instance, ModelSimple)): + return COERCION_INDEX_BY_TYPE[ModelSimple] + elif class_or_instance in COERCION_INDEX_BY_TYPE: + return COERCION_INDEX_BY_TYPE[class_or_instance] + raise ApiValueError("Unsupported type: %s" % class_or_instance) + + sorted_types = sorted( + required_types, + key=lambda class_or_instance: index_getter(class_or_instance) + ) + return sorted_types + + +def remove_uncoercible(required_types_classes, current_item, spec_property_naming, + must_convert=True): + """Only keeps the type conversions that are possible + + Args: + required_types_classes (tuple): tuple of classes that are required + these should be ordered by COERCION_INDEX_BY_TYPE + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + current_item (any): the current item (input data) to be converted + + Keyword Args: + must_convert (bool): if True the item to convert is of the wrong + type and we want a big list of coercibles + if False, we want a limited list of coercibles + + Returns: + (list): the remaining coercible required types, classes only + """ + current_type_simple = get_simple_class(current_item) + + results_classes = [] + for required_type_class in required_types_classes: + # convert our models to OpenApiModel + required_type_class_simplified = required_type_class + if isinstance(required_type_class_simplified, type): + if issubclass(required_type_class_simplified, ModelComposed): + required_type_class_simplified = ModelComposed + elif issubclass(required_type_class_simplified, ModelNormal): + required_type_class_simplified = ModelNormal + elif issubclass(required_type_class_simplified, ModelSimple): + required_type_class_simplified = ModelSimple + + if required_type_class_simplified == current_type_simple: + # don't consider converting to one's own class + continue + + class_pair = (current_type_simple, required_type_class_simplified) + if must_convert and class_pair in COERCIBLE_TYPE_PAIRS[spec_property_naming]: + results_classes.append(required_type_class) + elif class_pair in UPCONVERSION_TYPE_PAIRS: + results_classes.append(required_type_class) + return results_classes + +def get_discriminated_classes(cls): + """ + Returns all the classes that a discriminator converts to + TODO: lru_cache this + """ + possible_classes = [] + key = list(cls.discriminator.keys())[0] + if is_type_nullable(cls): + possible_classes.append(cls) + for discr_cls in cls.discriminator[key].values(): + if hasattr(discr_cls, 'discriminator') and discr_cls.discriminator is not None: + possible_classes.extend(get_discriminated_classes(discr_cls)) + else: + possible_classes.append(discr_cls) + return possible_classes + + +def get_possible_classes(cls, from_server_context): + # TODO: lru_cache this + possible_classes = [cls] + if from_server_context: + return possible_classes + if hasattr(cls, 'discriminator') and cls.discriminator is not None: + possible_classes = [] + possible_classes.extend(get_discriminated_classes(cls)) + elif issubclass(cls, ModelComposed): + possible_classes.extend(composed_model_input_classes(cls)) + return possible_classes + + +def get_required_type_classes(required_types_mixed, spec_property_naming): + """Converts the tuple required_types into a tuple and a dict described + below + + Args: + required_types_mixed (tuple/list): will contain either classes or + instance of list or dict + spec_property_naming (bool): if True these values came from the + server, and we use the data types in our endpoints. + If False, we are client side and we need to include + oneOf and discriminator classes inside the data types in our endpoints + + Returns: + (valid_classes, dict_valid_class_to_child_types_mixed): + valid_classes (tuple): the valid classes that the current item + should be + dict_valid_class_to_child_types_mixed (dict): + valid_class (class): this is the key + child_types_mixed (list/dict/tuple): describes the valid child + types + """ + valid_classes = [] + child_req_types_by_current_type = {} + for required_type in required_types_mixed: + if isinstance(required_type, list): + valid_classes.append(list) + child_req_types_by_current_type[list] = required_type + elif isinstance(required_type, tuple): + valid_classes.append(tuple) + child_req_types_by_current_type[tuple] = required_type + elif isinstance(required_type, dict): + valid_classes.append(dict) + child_req_types_by_current_type[dict] = required_type[str] + else: + valid_classes.extend(get_possible_classes(required_type, spec_property_naming)) + return tuple(valid_classes), child_req_types_by_current_type + + +def change_keys_js_to_python(input_dict, model_class): + """ + Converts from javascript_key keys in the input_dict to python_keys in + the output dict using the mapping in model_class. + If the input_dict contains a key which does not declared in the model_class, + the key is added to the output dict as is. The assumption is the model_class + may have undeclared properties (additionalProperties attribute in the OAS + document). + """ + + if getattr(model_class, 'attribute_map', None) is None: + return input_dict + output_dict = {} + reversed_attr_map = {value: key for key, value in + model_class.attribute_map.items()} + for javascript_key, value in input_dict.items(): + python_key = reversed_attr_map.get(javascript_key) + if python_key is None: + # if the key is unknown, it is in error or it is an + # additionalProperties variable + python_key = javascript_key + output_dict[python_key] = value + return output_dict + + +def get_type_error(var_value, path_to_item, valid_classes, key_type=False): + error_msg = type_error_message( + var_name=path_to_item[-1], + var_value=var_value, + valid_classes=valid_classes, + key_type=key_type + ) + return ApiTypeError( + error_msg, + path_to_item=path_to_item, + valid_classes=valid_classes, + key_type=key_type + ) + + +def deserialize_primitive(data, klass, path_to_item): + """Deserializes string to primitive type. + + :param data: str/int/float + :param klass: str/class the class to convert to + + :return: int, float, str, bool, date, datetime + """ + additional_message = "" + try: + if klass in {datetime, date}: + additional_message = ( + "If you need your parameter to have a fallback " + "string value, please set its type as `type: {}` in your " + "spec. That allows the value to be any type. " + ) + if klass == datetime: + if len(data) < 8: + raise ValueError("This is not a datetime") + # The string should be in iso8601 datetime format. + parsed_datetime = parse(data) + date_only = ( + parsed_datetime.hour == 0 and + parsed_datetime.minute == 0 and + parsed_datetime.second == 0 and + parsed_datetime.tzinfo is None and + 8 <= len(data) <= 10 + ) + if date_only: + raise ValueError("This is a date, not a datetime") + return parsed_datetime + elif klass == date: + if len(data) < 8: + raise ValueError("This is not a date") + return parse(data).date() + else: + converted_value = klass(data) + if isinstance(data, str) and klass == float: + if str(converted_value) != data: + # '7' -> 7.0 -> '7.0' != '7' + raise ValueError('This is not a float') + return converted_value + except (OverflowError, ValueError) as ex: + # parse can raise OverflowError + raise ApiValueError( + "{0}Failed to parse {1} as {2}".format( + additional_message, repr(data), klass.__name__ + ), + path_to_item=path_to_item + ) from ex + + +def get_discriminator_class(model_class, + discr_name, + discr_value, cls_visited): + """Returns the child class specified by the discriminator. + + Args: + model_class (OpenApiModel): the model class. + discr_name (string): the name of the discriminator property. + discr_value (any): the discriminator value. + cls_visited (list): list of model classes that have been visited. + Used to determine the discriminator class without + visiting circular references indefinitely. + + Returns: + used_model_class (class/None): the chosen child class that will be used + to deserialize the data, for example dog.Dog. + If a class is not found, None is returned. + """ + + if model_class in cls_visited: + # The class has already been visited and no suitable class was found. + return None + cls_visited.append(model_class) + used_model_class = None + if discr_name in model_class.discriminator: + class_name_to_discr_class = model_class.discriminator[discr_name] + used_model_class = class_name_to_discr_class.get(discr_value) + if used_model_class is None: + # We didn't find a discriminated class in class_name_to_discr_class. + # So look in the ancestor or descendant discriminators + # The discriminator mapping may exist in a descendant (anyOf, oneOf) + # or ancestor (allOf). + # Ancestor example: in the GrandparentAnimal -> ParentPet -> ChildCat + # hierarchy, the discriminator mappings may be defined at any level + # in the hierarchy. + # Descendant example: mammal -> whale/zebra/Pig -> BasquePig/DanishPig + # if we try to make BasquePig from mammal, we need to travel through + # the oneOf descendant discriminators to find BasquePig + descendant_classes = model_class._composed_schemas.get('oneOf', ()) + \ + model_class._composed_schemas.get('anyOf', ()) + ancestor_classes = model_class._composed_schemas.get('allOf', ()) + possible_classes = descendant_classes + ancestor_classes + for cls in possible_classes: + # Check if the schema has inherited discriminators. + if hasattr(cls, 'discriminator') and cls.discriminator is not None: + used_model_class = get_discriminator_class( + cls, discr_name, discr_value, cls_visited) + if used_model_class is not None: + return used_model_class + return used_model_class + + +def deserialize_model(model_data, model_class, path_to_item, check_type, + configuration, spec_property_naming): + """Deserializes model_data to model instance. + + Args: + model_data (int/str/float/bool/none_type/list/dict): data to instantiate the model + model_class (OpenApiModel): the model class + path_to_item (list): path to the model in the received data + check_type (bool): whether to check the data tupe for the values in + the model + configuration (Configuration): the instance to use to convert files + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + + Returns: + model instance + + Raise: + ApiTypeError + ApiValueError + ApiKeyError + """ + + kw_args = dict(_check_type=check_type, + _path_to_item=path_to_item, + _configuration=configuration, + _spec_property_naming=spec_property_naming) + + if issubclass(model_class, ModelSimple): + return model_class._new_from_openapi_data(model_data, **kw_args) + elif isinstance(model_data, list): + return model_class._new_from_openapi_data(*model_data, **kw_args) + if isinstance(model_data, dict): + kw_args.update(model_data) + return model_class._new_from_openapi_data(**kw_args) + elif isinstance(model_data, PRIMITIVE_TYPES): + return model_class._new_from_openapi_data(model_data, **kw_args) + + +def deserialize_file(response_data, configuration, content_disposition=None): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + Args: + param response_data (str): the file data to write + configuration (Configuration): the instance to use to convert files + + Keyword Args: + content_disposition (str): the value of the Content-Disposition + header + + Returns: + (file_type): the deserialized file which is open + The user is responsible for closing and reading the file + """ + fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + if content_disposition: + filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition).group(1) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + if isinstance(response_data, str): + # change str to bytes so we can write it + response_data = response_data.encode('utf-8') + f.write(response_data) + + f = open(path, "rb") + return f + + +def attempt_convert_item(input_value, valid_classes, path_to_item, + configuration, spec_property_naming, key_type=False, + must_convert=False, check_type=True): + """ + Args: + input_value (any): the data to convert + valid_classes (any): the classes that are valid + path_to_item (list): the path to the item to convert + configuration (Configuration): the instance to use to convert files + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + key_type (bool): if True we need to convert a key type (not supported) + must_convert (bool): if True we must convert + check_type (bool): if True we check the type or the returned data in + ModelComposed/ModelNormal/ModelSimple instances + + Returns: + instance (any) the fixed item + + Raises: + ApiTypeError + ApiValueError + ApiKeyError + """ + valid_classes_ordered = order_response_types(valid_classes) + valid_classes_coercible = remove_uncoercible( + valid_classes_ordered, input_value, spec_property_naming) + if not valid_classes_coercible or key_type: + # we do not handle keytype errors, json will take care + # of this for us + if configuration is None or not configuration.discard_unknown_keys: + raise get_type_error(input_value, path_to_item, valid_classes, + key_type=key_type) + for valid_class in valid_classes_coercible: + try: + if issubclass(valid_class, OpenApiModel): + return deserialize_model(input_value, valid_class, + path_to_item, check_type, + configuration, spec_property_naming) + elif valid_class == file_type: + return deserialize_file(input_value, configuration) + return deserialize_primitive(input_value, valid_class, + path_to_item) + except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc: + if must_convert: + raise conversion_exc + # if we have conversion errors when must_convert == False + # we ignore the exception and move on to the next class + continue + # we were unable to convert, must_convert == False + return input_value + + +def is_type_nullable(input_type): + """ + Returns true if None is an allowed value for the specified input_type. + + A type is nullable if at least one of the following conditions is true: + 1. The OAS 'nullable' attribute has been specified, + 1. The type is the 'null' type, + 1. The type is a anyOf/oneOf composed schema, and a child schema is + the 'null' type. + Args: + input_type (type): the class of the input_value that we are + checking + Returns: + bool + """ + if input_type is none_type: + return True + if issubclass(input_type, OpenApiModel) and input_type._nullable: + return True + if issubclass(input_type, ModelComposed): + # If oneOf/anyOf, check if the 'null' type is one of the allowed types. + for t in input_type._composed_schemas.get('oneOf', ()): + if is_type_nullable(t): return True + for t in input_type._composed_schemas.get('anyOf', ()): + if is_type_nullable(t): return True + return False + + +def is_valid_type(input_class_simple, valid_classes): + """ + Args: + input_class_simple (class): the class of the input_value that we are + checking + valid_classes (tuple): the valid classes that the current item + should be + Returns: + bool + """ + valid_type = input_class_simple in valid_classes + if not valid_type and ( + issubclass(input_class_simple, OpenApiModel) or + input_class_simple is none_type): + for valid_class in valid_classes: + if input_class_simple is none_type and is_type_nullable(valid_class): + # Schema is oneOf/anyOf and the 'null' type is one of the allowed types. + return True + if not (issubclass(valid_class, OpenApiModel) and valid_class.discriminator): + continue + discr_propertyname_py = list(valid_class.discriminator.keys())[0] + discriminator_classes = ( + valid_class.discriminator[discr_propertyname_py].values() + ) + valid_type = is_valid_type(input_class_simple, discriminator_classes) + if valid_type: + return True + return valid_type + + +def validate_and_convert_types(input_value, required_types_mixed, path_to_item, + spec_property_naming, _check_type, configuration=None): + """Raises a TypeError is there is a problem, otherwise returns value + + Args: + input_value (any): the data to validate/convert + required_types_mixed (list/dict/tuple): A list of + valid classes, or a list tuples of valid classes, or a dict where + the value is a tuple of value classes + path_to_item: (list) the path to the data being validated + this stores a list of keys or indices to get to the data being + validated + spec_property_naming (bool): True if the variable names in the input + data are serialized names as specified in the OpenAPI document. + False if the variables names in the input data are python + variable names in PEP-8 snake case. + _check_type: (boolean) if true, type will be checked and conversion + will be attempted. + configuration: (Configuration): the configuration class to use + when converting file_type items. + If passed, conversion will be attempted when possible + If not passed, no conversions will be attempted and + exceptions will be raised + + Returns: + the correctly typed value + + Raises: + ApiTypeError + """ + results = get_required_type_classes(required_types_mixed, spec_property_naming) + valid_classes, child_req_types_by_current_type = results + + input_class_simple = get_simple_class(input_value) + valid_type = is_valid_type(input_class_simple, valid_classes) + if not valid_type: + if configuration: + # if input_value is not valid_type try to convert it + converted_instance = attempt_convert_item( + input_value, + valid_classes, + path_to_item, + configuration, + spec_property_naming, + key_type=False, + must_convert=True, + check_type=_check_type + ) + return converted_instance + else: + raise get_type_error(input_value, path_to_item, valid_classes, + key_type=False) + + # input_value's type is in valid_classes + if len(valid_classes) > 1 and configuration: + # there are valid classes which are not the current class + valid_classes_coercible = remove_uncoercible( + valid_classes, input_value, spec_property_naming, must_convert=False) + if valid_classes_coercible: + converted_instance = attempt_convert_item( + input_value, + valid_classes_coercible, + path_to_item, + configuration, + spec_property_naming, + key_type=False, + must_convert=False, + check_type=_check_type + ) + return converted_instance + + if child_req_types_by_current_type == {}: + # all types are of the required types and there are no more inner + # variables left to look at + return input_value + inner_required_types = child_req_types_by_current_type.get( + type(input_value) + ) + if inner_required_types is None: + # for this type, there are not more inner variables left to look at + return input_value + if isinstance(input_value, list): + if input_value == []: + # allow an empty list + return input_value + for index, inner_value in enumerate(input_value): + inner_path = list(path_to_item) + inner_path.append(index) + input_value[index] = validate_and_convert_types( + inner_value, + inner_required_types, + inner_path, + spec_property_naming, + _check_type, + configuration=configuration + ) + elif isinstance(input_value, dict): + if input_value == {}: + # allow an empty dict + return input_value + for inner_key, inner_val in input_value.items(): + inner_path = list(path_to_item) + inner_path.append(inner_key) + if get_simple_class(inner_key) != str: + raise get_type_error(inner_key, inner_path, valid_classes, + key_type=True) + input_value[inner_key] = validate_and_convert_types( + inner_val, + inner_required_types, + inner_path, + spec_property_naming, + _check_type, + configuration=configuration + ) + return input_value + + +def model_to_dict(model_instance, serialize=True): + """Returns the model properties as a dict + + Args: + model_instance (one of your model instances): the model instance that + will be converted to a dict. + + Keyword Args: + serialize (bool): if True, the keys in the dict will be values from + attribute_map + """ + result = {} + + model_instances = [model_instance] + if model_instance._composed_schemas: + model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} + for model_instance in model_instances: + for attr, value in model_instance._data_store.items(): + if serialize: + # we use get here because additional property key names do not + # exist in attribute_map + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) + if isinstance(value, list): + if not value: + # empty list or None + result[attr] = value + else: + res = [] + for v in value: + if isinstance(v, PRIMITIVE_TYPES) or v is None: + res.append(v) + elif isinstance(v, ModelSimple): + res.append(v.value) + else: + res.append(model_to_dict(v, serialize=serialize)) + result[attr] = res + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], + model_to_dict(item[1], serialize=serialize)) + if hasattr(item[1], '_data_store') else item, + value.items() + )) + elif isinstance(value, ModelSimple): + result[attr] = value.value + elif hasattr(value, '_data_store'): + result[attr] = model_to_dict(value, serialize=serialize) + else: + result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] + + return result + + +def type_error_message(var_value=None, var_name=None, valid_classes=None, + key_type=None): + """ + Keyword Args: + var_value (any): the variable which has the type_error + var_name (str): the name of the variable which has the typ error + valid_classes (tuple): the accepted classes for current_item's + value + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + """ + key_or_value = 'value' + if key_type: + key_or_value = 'key' + valid_classes_phrase = get_valid_classes_phrase(valid_classes) + msg = ( + "Invalid type for variable '{0}'. Required {1} type {2} and " + "passed type was {3}".format( + var_name, + key_or_value, + valid_classes_phrase, + type(var_value).__name__, + ) + ) + return msg + + +def get_valid_classes_phrase(input_classes): + """Returns a string phrase describing what types are allowed + """ + all_classes = list(input_classes) + all_classes = sorted(all_classes, key=lambda cls: cls.__name__) + all_class_names = [cls.__name__ for cls in all_classes] + if len(all_class_names) == 1: + return 'is {0}'.format(all_class_names[0]) + return "is one of [{0}]".format(", ".join(all_class_names)) + + +def get_allof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + used to make instances + constant_args (dict): + metadata arguments: + _check_type + _path_to_item + _spec_property_naming + _configuration + _visited_composed_classes + + Returns + composed_instances (list) + """ + composed_instances = [] + for allof_class in self._composed_schemas['allOf']: + + try: + allof_instance = allof_class(**model_args, **constant_args) + composed_instances.append(allof_instance) + except Exception as ex: + raise ApiValueError( + "Invalid inputs given to generate an instance of '%s'. The " + "input data was invalid for the allOf schema '%s' in the composed " + "schema '%s'. Error=%s" % ( + allof_class.__name__, + allof_class.__name__, + self.__class__.__name__, + str(ex) + ) + ) from ex + return composed_instances + + +def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): + """ + Find the oneOf schema that matches the input data (e.g. payload). + If exactly one schema matches the input data, an instance of that schema + is returned. + If zero or more than one schema match the input data, an exception is raised. + In OAS 3.x, the payload MUST, by validation, match exactly one of the + schemas described by oneOf. + + Args: + cls: the class we are handling + model_kwargs (dict): var_name to var_value + The input data, e.g. the payload that must match a oneOf schema + in the OpenAPI document. + constant_kwargs (dict): var_name to var_value + args that every model requires, including configuration, server + and path to item. + + Kwargs: + model_arg: (int, float, bool, str, date, datetime, ModelSimple, None): + the value to assign to a primitive class or ModelSimple class + Notes: + - this is only passed in when oneOf includes types which are not object + - None is used to suppress handling of model_arg, nullable models are handled in __new__ + + Returns + oneof_instance (instance) + """ + if len(cls._composed_schemas['oneOf']) == 0: + return None + + oneof_instances = [] + # Iterate over each oneOf schema and determine if the input data + # matches the oneOf schemas. + for oneof_class in cls._composed_schemas['oneOf']: + # The composed oneOf schema allows the 'null' type and the input data + # is the null value. This is a OAS >= 3.1 feature. + if oneof_class is none_type: + # skip none_types because we are deserializing dict data. + # none_type deserialization is handled in the __new__ method + continue + + single_value_input = allows_single_value_input(oneof_class) + + try: + if not single_value_input: + oneof_instance = oneof_class(**model_kwargs, **constant_kwargs) + else: + if issubclass(oneof_class, ModelSimple): + oneof_instance = oneof_class(model_arg, **constant_kwargs) + elif oneof_class in PRIMITIVE_TYPES: + oneof_instance = validate_and_convert_types( + model_arg, + (oneof_class,), + constant_kwargs['_path_to_item'], + constant_kwargs['_spec_property_naming'], + constant_kwargs['_check_type'], + configuration=constant_kwargs['_configuration'] + ) + oneof_instances.append(oneof_instance) + except Exception: + pass + if len(oneof_instances) == 0: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. None " + "of the oneOf schemas matched the input data." % + cls.__name__ + ) + elif len(oneof_instances) > 1: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. Multiple " + "oneOf schemas matched the inputs, but a max of one is allowed." % + cls.__name__ + ) + return oneof_instances[0] + + +def get_anyof_instances(self, model_args, constant_args): + """ + Args: + self: the class we are handling + model_args (dict): var_name to var_value + The input data, e.g. the payload that must match at least one + anyOf child schema in the OpenAPI document. + constant_args (dict): var_name to var_value + args that every model requires, including configuration, server + and path to item. + + Returns + anyof_instances (list) + """ + anyof_instances = [] + if len(self._composed_schemas['anyOf']) == 0: + return anyof_instances + + for anyof_class in self._composed_schemas['anyOf']: + # The composed oneOf schema allows the 'null' type and the input data + # is the null value. This is a OAS >= 3.1 feature. + if anyof_class is none_type: + # skip none_types because we are deserializing dict data. + # none_type deserialization is handled in the __new__ method + continue + + try: + anyof_instance = anyof_class(**model_args, **constant_args) + anyof_instances.append(anyof_instance) + except Exception: + pass + if len(anyof_instances) == 0: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. None of the " + "anyOf schemas matched the inputs." % + self.__class__.__name__ + ) + return anyof_instances + + +def get_discarded_args(self, composed_instances, model_args): + """ + Gathers the args that were discarded by configuration.discard_unknown_keys + """ + model_arg_keys = model_args.keys() + discarded_args = set() + # arguments passed to self were already converted to python names + # before __init__ was called + for instance in composed_instances: + if instance.__class__ in self._composed_schemas['allOf']: + try: + keys = instance.to_dict().keys() + discarded_keys = model_args - keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass + else: + try: + all_keys = set(model_to_dict(instance, serialize=False).keys()) + js_keys = model_to_dict(instance, serialize=True).keys() + all_keys.update(js_keys) + discarded_keys = model_arg_keys - all_keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass + return discarded_args + + +def validate_get_composed_info(constant_args, model_args, self): + """ + For composed schemas, generate schema instances for + all schemas in the oneOf/anyOf/allOf definition. If additional + properties are allowed, also assign those properties on + all matched schemas that contain additionalProperties. + Openapi schemas are python classes. + + Exceptions are raised if: + - 0 or > 1 oneOf schema matches the model_args input data + - no anyOf schema matches the model_args input data + - any of the allOf schemas do not match the model_args input data + + Args: + constant_args (dict): these are the args that every model requires + model_args (dict): these are the required and optional spec args that + were passed in to make this model + self (class): the class that we are instantiating + This class contains self._composed_schemas + + Returns: + composed_info (list): length three + composed_instances (list): the composed instances which are not + self + var_name_to_model_instances (dict): a dict going from var_name + to the model_instance which holds that var_name + the model_instance may be self or an instance of one of the + classes in self.composed_instances() + additional_properties_model_instances (list): a list of the + model instances which have the property + additional_properties_type. This list can include self + """ + # create composed_instances + composed_instances = [] + allof_instances = get_allof_instances(self, model_args, constant_args) + composed_instances.extend(allof_instances) + oneof_instance = get_oneof_instance(self.__class__, model_args, constant_args) + if oneof_instance is not None: + composed_instances.append(oneof_instance) + anyof_instances = get_anyof_instances(self, model_args, constant_args) + composed_instances.extend(anyof_instances) + """ + set additional_properties_model_instances + additional properties must be evaluated at the schema level + so self's additional properties are most important + If self is a composed schema with: + - no properties defined in self + - additionalProperties: False + Then for object payloads every property is an additional property + and they are not allowed, so only empty dict is allowed + + Properties must be set on all matching schemas + so when a property is assigned toa composed instance, it must be set on all + composed instances regardless of additionalProperties presence + keeping it to prevent breaking changes in v5.0.1 + TODO remove cls._additional_properties_model_instances in 6.0.0 + """ + additional_properties_model_instances = [] + if self.additional_properties_type is not None: + additional_properties_model_instances = [self] + + """ + no need to set properties on self in here, they will be set in __init__ + By here all composed schema oneOf/anyOf/allOf instances have their properties set using + model_args + """ + discarded_args = get_discarded_args(self, composed_instances, model_args) + + # map variable names to composed_instances + var_name_to_model_instances = {} + for prop_name in model_args: + if prop_name not in discarded_args: + var_name_to_model_instances[prop_name] = [self] + composed_instances + + return [ + composed_instances, + var_name_to_model_instances, + additional_properties_model_instances, + discarded_args + ] diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/models/__init__.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/models/__init__.py new file mode 100644 index 000000000000..361e2bd9766c --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/models/__init__.py @@ -0,0 +1,74 @@ +# flake8: noqa + +# import all models into this package +# if you have many models here with many references from one model to another this may +# raise a RecursionError +# to avoid this, import only the models that you directly need like: +# from from petstore_api.model.pet import Pet +# or import this package, but before doing it, use: +# import sys +# sys.setrecursionlimit(n) + +from petstore_api.model.additional_properties_any_type import AdditionalPropertiesAnyType +from petstore_api.model.additional_properties_array import AdditionalPropertiesArray +from petstore_api.model.additional_properties_boolean import AdditionalPropertiesBoolean +from petstore_api.model.additional_properties_class import AdditionalPropertiesClass +from petstore_api.model.additional_properties_integer import AdditionalPropertiesInteger +from petstore_api.model.additional_properties_number import AdditionalPropertiesNumber +from petstore_api.model.additional_properties_object import AdditionalPropertiesObject +from petstore_api.model.additional_properties_string import AdditionalPropertiesString +from petstore_api.model.animal import Animal +from petstore_api.model.animal_farm import AnimalFarm +from petstore_api.model.api_response import ApiResponse +from petstore_api.model.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly +from petstore_api.model.array_of_number_only import ArrayOfNumberOnly +from petstore_api.model.array_test import ArrayTest +from petstore_api.model.capitalization import Capitalization +from petstore_api.model.cat import Cat +from petstore_api.model.cat_all_of import CatAllOf +from petstore_api.model.category import Category +from petstore_api.model.child import Child +from petstore_api.model.child_all_of import ChildAllOf +from petstore_api.model.child_cat import ChildCat +from petstore_api.model.child_cat_all_of import ChildCatAllOf +from petstore_api.model.child_dog import ChildDog +from petstore_api.model.child_dog_all_of import ChildDogAllOf +from petstore_api.model.child_lizard import ChildLizard +from petstore_api.model.child_lizard_all_of import ChildLizardAllOf +from petstore_api.model.class_model import ClassModel +from petstore_api.model.client import Client +from petstore_api.model.dog import Dog +from petstore_api.model.dog_all_of import DogAllOf +from petstore_api.model.enum_arrays import EnumArrays +from petstore_api.model.enum_class import EnumClass +from petstore_api.model.enum_test import EnumTest +from petstore_api.model.file import File +from petstore_api.model.file_schema_test_class import FileSchemaTestClass +from petstore_api.model.format_test import FormatTest +from petstore_api.model.grandparent import Grandparent +from petstore_api.model.grandparent_animal import GrandparentAnimal +from petstore_api.model.has_only_read_only import HasOnlyReadOnly +from petstore_api.model.list import List +from petstore_api.model.map_test import MapTest +from petstore_api.model.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass +from petstore_api.model.model200_response import Model200Response +from petstore_api.model.model_return import ModelReturn +from petstore_api.model.name import Name +from petstore_api.model.number_only import NumberOnly +from petstore_api.model.number_with_validations import NumberWithValidations +from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps +from petstore_api.model.order import Order +from petstore_api.model.parent import Parent +from petstore_api.model.parent_all_of import ParentAllOf +from petstore_api.model.parent_pet import ParentPet +from petstore_api.model.pet import Pet +from petstore_api.model.player import Player +from petstore_api.model.read_only_first import ReadOnlyFirst +from petstore_api.model.special_model_name import SpecialModelName +from petstore_api.model.string_boolean_map import StringBooleanMap +from petstore_api.model.string_enum import StringEnum +from petstore_api.model.tag import Tag +from petstore_api.model.type_holder_default import TypeHolderDefault +from petstore_api.model.type_holder_example import TypeHolderExample +from petstore_api.model.user import User +from petstore_api.model.xml_item import XmlItem diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/rest.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/rest.py new file mode 100644 index 000000000000..a1d580fbe05b --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/rest.py @@ -0,0 +1,292 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import io +import json +import logging +import re +import ssl +from urllib.parse import urlencode + +import urllib3 + +from petstore_api.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError + + +logger = logging.getLogger(__name__) + + +class RESTResponse(io.IOBase): + + def __init__(self, resp): + self.urllib3_response = resp + self.status = resp.status + self.reason = resp.reason + self.data = resp.data + + def getheaders(self): + """Returns a dictionary of the response headers.""" + return self.urllib3_response.getheaders() + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.urllib3_response.getheader(name, default) + + +class RESTClientObject(object): + + def __init__(self, configuration, pools_size=4, maxsize=None): + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 + + # cert_reqs + if configuration.verify_ssl: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + + addition_pool_args = {} + if configuration.assert_hostname is not None: + addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 + + if configuration.retries is not None: + addition_pool_args['retries'] = configuration.retries + + if configuration.socket_options is not None: + addition_pool_args['socket_options'] = configuration.socket_options + + if maxsize is None: + if configuration.connection_pool_maxsize is not None: + maxsize = configuration.connection_pool_maxsize + else: + maxsize = 4 + + # https pool manager + if configuration.proxy: + self.pool_manager = urllib3.ProxyManager( + num_pools=pools_size, + maxsize=maxsize, + cert_reqs=cert_reqs, + ca_certs=configuration.ssl_ca_cert, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + proxy_url=configuration.proxy, + proxy_headers=configuration.proxy_headers, + **addition_pool_args + ) + else: + self.pool_manager = urllib3.PoolManager( + num_pools=pools_size, + maxsize=maxsize, + cert_reqs=cert_reqs, + ca_certs=configuration.ssl_ca_cert, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + **addition_pool_args + ) + + def request(self, method, url, query_params=None, headers=None, + body=None, post_params=None, _preload_content=True, + _request_timeout=None): + """Perform requests. + + :param method: http request method + :param url: http request url + :param query_params: query parameters in the url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', + 'PATCH', 'OPTIONS'] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or {} + headers = headers or {} + + timeout = None + if _request_timeout: + if isinstance(_request_timeout, (int, float)): # noqa: E501,F821 + timeout = urllib3.Timeout(total=_request_timeout) + elif (isinstance(_request_timeout, tuple) and + len(_request_timeout) == 2): + timeout = urllib3.Timeout( + connect=_request_timeout[0], read=_request_timeout[1]) + + if 'Content-Type' not in headers: + headers['Content-Type'] = 'application/json' + + try: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + if query_params: + url += '?' + urlencode(query_params) + if re.search('json', headers['Content-Type'], re.IGNORECASE): + request_body = None + if body is not None: + request_body = json.dumps(body) + r = self.pool_manager.request( + method, url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + r = self.pool_manager.request( + method, url, + fields=post_params, + encode_multipart=False, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + elif headers['Content-Type'] == 'multipart/form-data': + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. + del headers['Content-Type'] + r = self.pool_manager.request( + method, url, + fields=post_params, + encode_multipart=True, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + # Pass a `string` parameter directly in the body to support + # other content types than Json when `body` argument is + # provided in serialized form + elif isinstance(body, str) or isinstance(body, bytes): + request_body = body + r = self.pool_manager.request( + method, url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + # For `GET`, `HEAD` + else: + r = self.pool_manager.request(method, url, + fields=query_params, + preload_content=_preload_content, + timeout=timeout, + headers=headers) + except urllib3.exceptions.SSLError as e: + msg = "{0}\n{1}".format(type(e).__name__, str(e)) + raise ApiException(status=0, reason=msg) + + if _preload_content: + r = RESTResponse(r) + + # log response body + logger.debug("response body: %s", r.data) + + if not 200 <= r.status <= 299: + if r.status == 401: + raise UnauthorizedException(http_resp=r) + + if r.status == 403: + raise ForbiddenException(http_resp=r) + + if r.status == 404: + raise NotFoundException(http_resp=r) + + if 500 <= r.status <= 599: + raise ServiceException(http_resp=r) + + raise ApiException(http_resp=r) + + return r + + def GET(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): + return self.request("GET", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) + + def HEAD(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): + return self.request("HEAD", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) + + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("OPTIONS", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def DELETE(self, url, headers=None, query_params=None, body=None, + _preload_content=True, _request_timeout=None): + return self.request("DELETE", url, + headers=headers, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def POST(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("POST", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def PUT(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("PUT", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + + def PATCH(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return self.request("PATCH", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/pom.xml b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/pom.xml new file mode 100644 index 000000000000..1db0285b1812 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + org.openapitools + PythonV2PetstoreClientTestsDisallowAdditionalPropertiesIfNotPresent + pom + 1.0-SNAPSHOT + Python OpenAPI Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + test + integration-test + + exec + + + make + + test + + + + + + + + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/requirements.txt b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/requirements.txt new file mode 100644 index 000000000000..96947f60408f --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/requirements.txt @@ -0,0 +1,3 @@ +python_dateutil >= 2.5.3 +setuptools >= 21.0.0 +urllib3 >= 1.25.3 diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/setup.cfg b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/setup.cfg new file mode 100644 index 000000000000..11433ee875ab --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/setup.cfg @@ -0,0 +1,2 @@ +[flake8] +max-line-length=99 diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/setup.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/setup.py new file mode 100644 index 000000000000..c484eec94f36 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/setup.py @@ -0,0 +1,43 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from setuptools import setup, find_packages # noqa: H301 + +NAME = "petstore-api" +VERSION = "1.0.0" +# To install the library, run the following +# +# python setup.py install +# +# prerequisite: setuptools +# http://pypi.python.org/pypi/setuptools + +REQUIRES = [ + "urllib3 >= 1.25.3", + "python-dateutil", +] + +setup( + name=NAME, + version=VERSION, + description="OpenAPI Petstore", + author="OpenAPI Generator community", + author_email="team@openapitools.org", + url="", + keywords=["OpenAPI", "OpenAPI-Generator", "OpenAPI Petstore"], + python_requires=">=3.6", + install_requires=REQUIRES, + packages=find_packages(exclude=["test", "tests"]), + include_package_data=True, + license="Apache-2.0", + long_description="""\ + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + """ +) diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test-requirements.txt b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test-requirements.txt new file mode 100644 index 000000000000..bb4f22bb7a6e --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test-requirements.txt @@ -0,0 +1 @@ +pytest-cov>=2.8.1 diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/__init__.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/samples/openapi3/client/petstore/python/test/test_fake_get_inline_additional_properties_payload_array_data.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_any_type.py similarity index 52% rename from samples/openapi3/client/petstore/python/test/test_fake_get_inline_additional_properties_payload_array_data.py rename to samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_any_type.py index 2e95eb37dffc..ce985f76ed9e 100644 --- a/samples/openapi3/client/petstore/python/test/test_fake_get_inline_additional_properties_payload_array_data.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_any_type.py @@ -1,3 +1,5 @@ +# coding: utf-8 + """ OpenAPI Petstore @@ -8,15 +10,16 @@ """ +from __future__ import absolute_import import sys import unittest import petstore_api -from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData +from petstore_api.model.additional_properties_any_type import AdditionalPropertiesAnyType -class TestFakeGetInlineAdditionalPropertiesPayloadArrayData(unittest.TestCase): - """FakeGetInlineAdditionalPropertiesPayloadArrayData unit test stubs""" +class TestAdditionalPropertiesAnyType(unittest.TestCase): + """AdditionalPropertiesAnyType unit test stubs""" def setUp(self): pass @@ -24,10 +27,10 @@ def setUp(self): def tearDown(self): pass - def testFakeGetInlineAdditionalPropertiesPayloadArrayData(self): - """Test FakeGetInlineAdditionalPropertiesPayloadArrayData""" + def testAdditionalPropertiesAnyType(self): + """Test AdditionalPropertiesAnyType""" # FIXME: construct object with mandatory attributes with example values - # model = FakeGetInlineAdditionalPropertiesPayloadArrayData() # noqa: E501 + # model = AdditionalPropertiesAnyType() # noqa: E501 pass diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_array.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_array.py new file mode 100644 index 000000000000..f63ca82f6c22 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_array.py @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.additional_properties_array import AdditionalPropertiesArray + + +class TestAdditionalPropertiesArray(unittest.TestCase): + """AdditionalPropertiesArray unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testAdditionalPropertiesArray(self): + """Test AdditionalPropertiesArray""" + # can make model without additional properties + model = AdditionalPropertiesArray() + + # can make one with additional properties + import datetime + some_val = [] + model = AdditionalPropertiesArray(some_key=some_val) + assert model['some_key'] == some_val + some_val = [True, datetime.date(1970,1,1), datetime.datetime(1970,1,1), {}, 3.1, 1, [], 'hello'] + model = AdditionalPropertiesArray(some_key=some_val) + assert model['some_key'] == some_val + + # type checking works on additional properties + with self.assertRaises(petstore_api.ApiTypeError) as exc: + model = AdditionalPropertiesArray(some_key='some string') + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_boolean.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_boolean.py new file mode 100644 index 000000000000..e5a13891c098 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_boolean.py @@ -0,0 +1,45 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.additional_properties_boolean import AdditionalPropertiesBoolean + + +class TestAdditionalPropertiesBoolean(unittest.TestCase): + """AdditionalPropertiesBoolean unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testAdditionalPropertiesBoolean(self): + """Test AdditionalPropertiesBoolean""" + # can make model without additional properties + model = AdditionalPropertiesBoolean() + + # can make one with additional properties + model = AdditionalPropertiesBoolean(some_key=True) + assert model['some_key'] == True + + # type checking works on additional properties + with self.assertRaises(petstore_api.ApiTypeError) as exc: + model = AdditionalPropertiesBoolean(some_key='True') + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_class.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_class.py new file mode 100644 index 000000000000..befc14455da2 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_class.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.additional_properties_class import AdditionalPropertiesClass + + +class TestAdditionalPropertiesClass(unittest.TestCase): + """AdditionalPropertiesClass unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testAdditionalPropertiesClass(self): + """Test AdditionalPropertiesClass""" + # FIXME: construct object with mandatory attributes with example values + # model = AdditionalPropertiesClass() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_integer.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_integer.py new file mode 100644 index 000000000000..0e08b8f87706 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_integer.py @@ -0,0 +1,45 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.additional_properties_integer import AdditionalPropertiesInteger + + +class TestAdditionalPropertiesInteger(unittest.TestCase): + """AdditionalPropertiesInteger unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testAdditionalPropertiesInteger(self): + """Test AdditionalPropertiesInteger""" + # can make model without additional properties + model = AdditionalPropertiesInteger() + + # can make one with additional properties + model = AdditionalPropertiesInteger(some_key=3) + assert model['some_key'] == 3 + + # type checking works on additional properties + with self.assertRaises(petstore_api.ApiTypeError) as exc: + model = AdditionalPropertiesInteger(some_key=11.3) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_number.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_number.py new file mode 100644 index 000000000000..90f4429e989f --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_number.py @@ -0,0 +1,45 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.additional_properties_number import AdditionalPropertiesNumber + + +class TestAdditionalPropertiesNumber(unittest.TestCase): + """AdditionalPropertiesNumber unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testAdditionalPropertiesNumber(self): + """Test AdditionalPropertiesNumber""" + # can make model without additional properties + model = AdditionalPropertiesNumber() + + # can make one with additional properties + model = AdditionalPropertiesNumber(some_key=11.3) + assert model['some_key'] == 11.3 + + # type checking works on additional properties + with self.assertRaises(petstore_api.ApiTypeError) as exc: + model = AdditionalPropertiesNumber(some_key=10) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_object.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_object.py new file mode 100644 index 000000000000..ded4a8e8a124 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_object.py @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.additional_properties_object import AdditionalPropertiesObject + + +class TestAdditionalPropertiesObject(unittest.TestCase): + """AdditionalPropertiesObject unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testAdditionalPropertiesObject(self): + """Test AdditionalPropertiesObject""" + # can make model without additional properties + model = AdditionalPropertiesObject() + + # can make one with additional properties + some_val = {} + model = AdditionalPropertiesObject(some_key=some_val) + assert model['some_key'] == some_val + import datetime + some_val = {'a': True, 'b': datetime.date(1970,1,1), 'c': datetime.datetime(1970,1,1), 'd': {}, 'e': 3.1, 'f': 1, 'g': [], 'h': 'hello'} + model = AdditionalPropertiesObject(some_key=some_val) + assert model['some_key'] == some_val + + # type checking works on additional properties + with self.assertRaises(petstore_api.ApiTypeError) as exc: + model = AdditionalPropertiesObject(some_key='some string') + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_string.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_string.py new file mode 100644 index 000000000000..cff2c31921fe --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_additional_properties_string.py @@ -0,0 +1,45 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.additional_properties_string import AdditionalPropertiesString + + +class TestAdditionalPropertiesString(unittest.TestCase): + """AdditionalPropertiesString unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testAdditionalPropertiesString(self): + """Test AdditionalPropertiesString""" + # can make model without additional properties + model = AdditionalPropertiesString() + + # can make one with additional properties + model = AdditionalPropertiesString(some_key='some_val') + assert model['some_key'] == 'some_val' + + # type checking works on additional properties + with self.assertRaises(petstore_api.ApiTypeError) as exc: + model = AdditionalPropertiesString(some_key=True) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_animal.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_animal.py new file mode 100644 index 000000000000..958f303f13e3 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_animal.py @@ -0,0 +1,48 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import cat +except ImportError: + cat = sys.modules[ + 'petstore_api.model.cat'] +try: + from petstore_api.model import dog +except ImportError: + dog = sys.modules[ + 'petstore_api.model.dog'] +from petstore_api.model.animal import Animal + + +class TestAnimal(unittest.TestCase): + """Animal unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testAnimal(self): + """Test Animal""" + # FIXME: construct object with mandatory attributes with example values + # model = Animal() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_animal_farm.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_animal_farm.py new file mode 100644 index 000000000000..7117d42b430e --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_animal_farm.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import animal +except ImportError: + animal = sys.modules[ + 'petstore_api.model.animal'] +from petstore_api.model.animal_farm import AnimalFarm + + +class TestAnimalFarm(unittest.TestCase): + """AnimalFarm unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testAnimalFarm(self): + """Test AnimalFarm""" + # FIXME: construct object with mandatory attributes with example values + # model = AnimalFarm() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_another_fake_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_another_fake_api.py new file mode 100644 index 000000000000..f79966a26961 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_another_fake_api.py @@ -0,0 +1,39 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api +from petstore_api.api.another_fake_api import AnotherFakeApi # noqa: E501 + + +class TestAnotherFakeApi(unittest.TestCase): + """AnotherFakeApi unit test stubs""" + + def setUp(self): + self.api = AnotherFakeApi() # noqa: E501 + + def tearDown(self): + pass + + def test_call_123_test_special_tags(self): + """Test case for call_123_test_special_tags + + To test special tags # noqa: E501 + """ + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_api_response.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_api_response.py new file mode 100644 index 000000000000..9db92633f626 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_api_response.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.api_response import ApiResponse + + +class TestApiResponse(unittest.TestCase): + """ApiResponse unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testApiResponse(self): + """Test ApiResponse""" + # FIXME: construct object with mandatory attributes with example values + # model = ApiResponse() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_array_of_array_of_number_only.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_array_of_array_of_number_only.py new file mode 100644 index 000000000000..4980ad17afb5 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_array_of_array_of_number_only.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly + + +class TestArrayOfArrayOfNumberOnly(unittest.TestCase): + """ArrayOfArrayOfNumberOnly unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testArrayOfArrayOfNumberOnly(self): + """Test ArrayOfArrayOfNumberOnly""" + # FIXME: construct object with mandatory attributes with example values + # model = ArrayOfArrayOfNumberOnly() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_array_of_number_only.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_array_of_number_only.py new file mode 100644 index 000000000000..479c537cada7 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_array_of_number_only.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.array_of_number_only import ArrayOfNumberOnly + + +class TestArrayOfNumberOnly(unittest.TestCase): + """ArrayOfNumberOnly unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testArrayOfNumberOnly(self): + """Test ArrayOfNumberOnly""" + # FIXME: construct object with mandatory attributes with example values + # model = ArrayOfNumberOnly() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_array_test.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_array_test.py new file mode 100644 index 000000000000..2426b27b7e46 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_array_test.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import read_only_first +except ImportError: + read_only_first = sys.modules[ + 'petstore_api.model.read_only_first'] +from petstore_api.model.array_test import ArrayTest + + +class TestArrayTest(unittest.TestCase): + """ArrayTest unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testArrayTest(self): + """Test ArrayTest""" + # FIXME: construct object with mandatory attributes with example values + # model = ArrayTest() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_capitalization.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_capitalization.py new file mode 100644 index 000000000000..20d2649c01eb --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_capitalization.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.capitalization import Capitalization + + +class TestCapitalization(unittest.TestCase): + """Capitalization unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testCapitalization(self): + """Test Capitalization""" + # FIXME: construct object with mandatory attributes with example values + # model = Capitalization() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_cat.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_cat.py new file mode 100644 index 000000000000..64b525aaf118 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_cat.py @@ -0,0 +1,48 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import animal +except ImportError: + animal = sys.modules[ + 'petstore_api.model.animal'] +try: + from petstore_api.model import cat_all_of +except ImportError: + cat_all_of = sys.modules[ + 'petstore_api.model.cat_all_of'] +from petstore_api.model.cat import Cat + + +class TestCat(unittest.TestCase): + """Cat unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testCat(self): + """Test Cat""" + # FIXME: construct object with mandatory attributes with example values + # model = Cat() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_cat_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_cat_all_of.py new file mode 100644 index 000000000000..a5bb91ac864e --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_cat_all_of.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.cat_all_of import CatAllOf + + +class TestCatAllOf(unittest.TestCase): + """CatAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testCatAllOf(self): + """Test CatAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = CatAllOf() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_category.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_category.py new file mode 100644 index 000000000000..59b64e5924a8 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_category.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.category import Category + + +class TestCategory(unittest.TestCase): + """Category unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testCategory(self): + """Test Category""" + # FIXME: construct object with mandatory attributes with example values + # model = Category() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child.py new file mode 100644 index 000000000000..790fc1abc8da --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import child_all_of +except ImportError: + child_all_of = sys.modules[ + 'petstore_api.model.child_all_of'] +try: + from petstore_api.model import parent +except ImportError: + parent = sys.modules[ + 'petstore_api.model.parent'] +from petstore_api.model.child import Child + + +class TestChild(unittest.TestCase): + """Child unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testChild(self): + """Test Child + This will fail because additional_properties_type is None in ChildAllOf and it must be defined as any type + to allow in the property radio_waves which is not defined in ChildAllOf, it is defined in Grandparent + """ + # make an instance of Child, a composed schema model + radio_waves = True + tele_vision = True + inter_net = True + with self.assertRaises(petstore_api.exceptions.ApiValueError): + child = Child( + radio_waves=radio_waves, + tele_vision=tele_vision, + inter_net=inter_net + ) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_all_of.py new file mode 100644 index 000000000000..96e479cf0796 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_all_of.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.child_all_of import ChildAllOf + + +class TestChildAllOf(unittest.TestCase): + """ChildAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testChildAllOf(self): + """Test ChildAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = ChildAllOf() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_cat.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_cat.py new file mode 100644 index 000000000000..34c085515a80 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_cat.py @@ -0,0 +1,48 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import child_cat_all_of +except ImportError: + child_cat_all_of = sys.modules[ + 'petstore_api.model.child_cat_all_of'] +try: + from petstore_api.model import parent_pet +except ImportError: + parent_pet = sys.modules[ + 'petstore_api.model.parent_pet'] +from petstore_api.model.child_cat import ChildCat + + +class TestChildCat(unittest.TestCase): + """ChildCat unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testChildCat(self): + """Test ChildCat""" + # FIXME: construct object with mandatory attributes with example values + # model = ChildCat() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_cat_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_cat_all_of.py new file mode 100644 index 000000000000..2a7aab100fbf --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_cat_all_of.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.child_cat_all_of import ChildCatAllOf + + +class TestChildCatAllOf(unittest.TestCase): + """ChildCatAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testChildCatAllOf(self): + """Test ChildCatAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = ChildCatAllOf() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_dog.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_dog.py new file mode 100644 index 000000000000..dfb09213e40c --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_dog.py @@ -0,0 +1,48 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import child_dog_all_of +except ImportError: + child_dog_all_of = sys.modules[ + 'petstore_api.model.child_dog_all_of'] +try: + from petstore_api.model import parent_pet +except ImportError: + parent_pet = sys.modules[ + 'petstore_api.model.parent_pet'] +from petstore_api.model.child_dog import ChildDog + + +class TestChildDog(unittest.TestCase): + """ChildDog unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testChildDog(self): + """Test ChildDog""" + # FIXME: construct object with mandatory attributes with example values + # model = ChildDog() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_dog_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_dog_all_of.py new file mode 100644 index 000000000000..ca75000c650e --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_dog_all_of.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.child_dog_all_of import ChildDogAllOf + + +class TestChildDogAllOf(unittest.TestCase): + """ChildDogAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testChildDogAllOf(self): + """Test ChildDogAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = ChildDogAllOf() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_lizard.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_lizard.py new file mode 100644 index 000000000000..975dc1612a9f --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_lizard.py @@ -0,0 +1,48 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import child_lizard_all_of +except ImportError: + child_lizard_all_of = sys.modules[ + 'petstore_api.model.child_lizard_all_of'] +try: + from petstore_api.model import parent_pet +except ImportError: + parent_pet = sys.modules[ + 'petstore_api.model.parent_pet'] +from petstore_api.model.child_lizard import ChildLizard + + +class TestChildLizard(unittest.TestCase): + """ChildLizard unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testChildLizard(self): + """Test ChildLizard""" + # FIXME: construct object with mandatory attributes with example values + # model = ChildLizard() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_lizard_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_lizard_all_of.py new file mode 100644 index 000000000000..1b3bf4dba943 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child_lizard_all_of.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.child_lizard_all_of import ChildLizardAllOf + + +class TestChildLizardAllOf(unittest.TestCase): + """ChildLizardAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testChildLizardAllOf(self): + """Test ChildLizardAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = ChildLizardAllOf() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_class_model.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_class_model.py new file mode 100644 index 000000000000..060df39e4b5e --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_class_model.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.class_model import ClassModel + + +class TestClassModel(unittest.TestCase): + """ClassModel unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testClassModel(self): + """Test ClassModel""" + # FIXME: construct object with mandatory attributes with example values + # model = ClassModel() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_client.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_client.py new file mode 100644 index 000000000000..ab5e3a80d377 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_client.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.client import Client + + +class TestClient(unittest.TestCase): + """Client unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testClient(self): + """Test Client""" + # FIXME: construct object with mandatory attributes with example values + # model = Client() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_dog.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_dog.py new file mode 100644 index 000000000000..9fb96ebc6b92 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_dog.py @@ -0,0 +1,57 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import animal +except ImportError: + animal = sys.modules[ + 'petstore_api.model.animal'] +try: + from petstore_api.model import dog_all_of +except ImportError: + dog_all_of = sys.modules[ + 'petstore_api.model.dog_all_of'] +from petstore_api.model.dog import Dog + + +class TestDog(unittest.TestCase): + """Dog unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testDog(self): + """Test Dog + This will fail because additional_properties_type is None in Animal and it must be defined as any type + to allow in the property breed which is not defined in Animal, it is defined in Dog + """ + # make an instance of dog, a composed schema model + class_name = 'Dog' + color = 'white' + breed = 'Jack Russel Terrier' + with self.assertRaises(petstore_api.exceptions.ApiValueError): + dog = Dog( + class_name=class_name, + color=color, + breed=breed + ) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_dog_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_dog_all_of.py new file mode 100644 index 000000000000..7ab4e8ae79d8 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_dog_all_of.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.dog_all_of import DogAllOf + + +class TestDogAllOf(unittest.TestCase): + """DogAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testDogAllOf(self): + """Test DogAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = DogAllOf() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_enum_arrays.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_enum_arrays.py new file mode 100644 index 000000000000..64ad5fd7dc08 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_enum_arrays.py @@ -0,0 +1,162 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.enum_arrays import EnumArrays + + +class TestEnumArrays(unittest.TestCase): + """EnumArrays unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_enumarrays_init(self): + # + # Check various combinations of valid values. + # + fish_or_crab = EnumArrays(just_symbol=">=") + self.assertEqual(fish_or_crab.just_symbol, ">=") + # if optional property is unset we raise an exception + with self.assertRaises(petstore_api.ApiAttributeError) as exc: + self.assertEqual(fish_or_crab.array_enum, None) + + fish_or_crab = EnumArrays(just_symbol="$", array_enum=["fish"]) + self.assertEqual(fish_or_crab.just_symbol, "$") + self.assertEqual(fish_or_crab.array_enum, ["fish"]) + + fish_or_crab = EnumArrays(just_symbol=">=", array_enum=["fish"]) + self.assertEqual(fish_or_crab.just_symbol, ">=") + self.assertEqual(fish_or_crab.array_enum, ["fish"]) + + fish_or_crab = EnumArrays(just_symbol="$", array_enum=["crab"]) + self.assertEqual(fish_or_crab.just_symbol, "$") + self.assertEqual(fish_or_crab.array_enum, ["crab"]) + + + # + # Check if setting invalid values fails + # + with self.assertRaises(petstore_api.ApiValueError) as exc: + fish_or_crab = EnumArrays(just_symbol="<=") + + with self.assertRaises(petstore_api.ApiValueError) as exc: + fish_or_crab = EnumArrays(just_symbol="$", array_enum=["dog"]) + + with self.assertRaises(petstore_api.ApiTypeError) as exc: + fish_or_crab = EnumArrays(just_symbol=["$"], array_enum=["crab"]) + + + def test_enumarrays_setter(self): + + # + # Check various combinations of valid values + # + fish_or_crab = EnumArrays() + + fish_or_crab.just_symbol = ">=" + self.assertEqual(fish_or_crab.just_symbol, ">=") + + fish_or_crab.just_symbol = "$" + self.assertEqual(fish_or_crab.just_symbol, "$") + + fish_or_crab.array_enum = [] + self.assertEqual(fish_or_crab.array_enum, []) + + fish_or_crab.array_enum = ["fish"] + self.assertEqual(fish_or_crab.array_enum, ["fish"]) + + fish_or_crab.array_enum = ["fish", "fish", "fish"] + self.assertEqual(fish_or_crab.array_enum, ["fish", "fish", "fish"]) + + fish_or_crab.array_enum = ["crab"] + self.assertEqual(fish_or_crab.array_enum, ["crab"]) + + fish_or_crab.array_enum = ["crab", "fish"] + self.assertEqual(fish_or_crab.array_enum, ["crab", "fish"]) + + fish_or_crab.array_enum = ["crab", "fish", "crab", "fish"] + self.assertEqual(fish_or_crab.array_enum, ["crab", "fish", "crab", "fish"]) + + # + # Check if setting invalid values fails + # + fish_or_crab = EnumArrays() + with self.assertRaises(petstore_api.ApiValueError) as exc: + fish_or_crab.just_symbol = "!=" + + with self.assertRaises(petstore_api.ApiTypeError) as exc: + fish_or_crab.just_symbol = ["fish"] + + with self.assertRaises(petstore_api.ApiValueError) as exc: + fish_or_crab.array_enum = ["cat"] + + with self.assertRaises(petstore_api.ApiValueError) as exc: + fish_or_crab.array_enum = ["fish", "crab", "dog"] + + with self.assertRaises(petstore_api.ApiTypeError) as exc: + fish_or_crab.array_enum = "fish" + + + def test_todict(self): + # + # Check if dictionary serialization works + # + dollar_fish_crab_dict = { + 'just_symbol': "$", + 'array_enum': ["fish", "crab"] + } + + dollar_fish_crab = EnumArrays( + just_symbol="$", array_enum=["fish", "crab"]) + + self.assertEqual(dollar_fish_crab_dict, dollar_fish_crab.to_dict()) + + # + # Sanity check for different arrays + # + dollar_crab_fish_dict = { + 'just_symbol': "$", + 'array_enum': ["crab", "fish"] + } + + dollar_fish_crab = EnumArrays( + just_symbol="$", array_enum=["fish", "crab"]) + + self.assertNotEqual(dollar_crab_fish_dict, dollar_fish_crab.to_dict()) + + + def test_equals(self): + # + # Check if object comparison works + # + fish1 = EnumArrays(just_symbol="$", array_enum=["fish"]) + fish2 = EnumArrays(just_symbol="$", array_enum=["fish"]) + self.assertEqual(fish1, fish2) + + fish = EnumArrays(just_symbol="$", array_enum=["fish"]) + crab = EnumArrays(just_symbol="$", array_enum=["crab"]) + self.assertNotEqual(fish, crab) + + dollar = EnumArrays(just_symbol="$") + greater = EnumArrays(just_symbol=">=") + self.assertNotEqual(dollar, greater) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_enum_class.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_enum_class.py new file mode 100644 index 000000000000..f910231c9d02 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_enum_class.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.enum_class import EnumClass + + +class TestEnumClass(unittest.TestCase): + """EnumClass unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testEnumClass(self): + """Test EnumClass""" + # FIXME: construct object with mandatory attributes with example values + # model = EnumClass() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_enum_test.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_enum_test.py new file mode 100644 index 000000000000..7b4c1b6b66ac --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_enum_test.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import string_enum +except ImportError: + string_enum = sys.modules[ + 'petstore_api.model.string_enum'] +from petstore_api.model.enum_test import EnumTest + + +class TestEnumTest(unittest.TestCase): + """EnumTest unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testEnumTest(self): + """Test EnumTest""" + # FIXME: construct object with mandatory attributes with example values + # model = EnumTest() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_fake_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_fake_api.py new file mode 100644 index 000000000000..34d207f3c71d --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_fake_api.py @@ -0,0 +1,197 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api +from petstore_api.api.fake_api import FakeApi # noqa: E501 + + +class TestFakeApi(unittest.TestCase): + """FakeApi unit test stubs""" + + def setUp(self): + self.api = FakeApi() # noqa: E501 + + def tearDown(self): + pass + + def test_create_xml_item(self): + """Test case for create_xml_item + + creates an XmlItem # noqa: E501 + """ + pass + + def test_boolean(self): + """Test case for boolean + + """ + endpoint = self.api.boolean + assert endpoint.openapi_types['body'] == (bool,) + assert endpoint.settings['response_type'] == (bool,) + + def test_string(self): + """Test case for string + + """ + endpoint = self.api.string + assert endpoint.openapi_types['body'] == (str,) + assert endpoint.settings['response_type'] == (str,) + + def test_object_model_with_ref_props(self): + """Test case for object_model_with_ref_props + + """ + from petstore_api.model import object_model_with_ref_props + endpoint = self.api.object_model_with_ref_props + assert endpoint.openapi_types['body'] == (object_model_with_ref_props.ObjectModelWithRefProps,) + assert endpoint.settings['response_type'] == (object_model_with_ref_props.ObjectModelWithRefProps,) + + def test_string_enum(self): + """Test case for string_enum + + """ + from petstore_api.model import string_enum + endpoint = self.api.string_enum + assert endpoint.openapi_types['body'] == (string_enum.StringEnum,) + assert endpoint.settings['response_type'] == (string_enum.StringEnum,) + + def test_array_model(self): + """Test case for array_model + + """ + from petstore_api.model import animal_farm + endpoint = self.api.array_model + assert endpoint.openapi_types['body'] == (animal_farm.AnimalFarm,) + assert endpoint.settings['response_type'] == (animal_farm.AnimalFarm,) + + def test_number_with_validations(self): + """Test case for number_with_validations + + """ + from petstore_api.model import number_with_validations + endpoint = self.api.number_with_validations + assert endpoint.openapi_types['body'] == (number_with_validations.NumberWithValidations,) + assert endpoint.settings['response_type'] == (number_with_validations.NumberWithValidations,) + + def test_test_body_with_file_schema(self): + """Test case for test_body_with_file_schema + + """ + pass + + def test_test_body_with_query_params(self): + """Test case for test_body_with_query_params + + """ + pass + + def test_test_client_model(self): + """Test case for test_client_model + + To test \"client\" model # noqa: E501 + """ + pass + + def test_test_endpoint_enums_length_one(self): + """Test case for test_endpoint_enums_length_one + + """ + # when we omit the required enums of length one, they are still set + endpoint = self.api.test_endpoint_enums_length_one + import six + if six.PY3: + from unittest.mock import patch + else: + from mock import patch + with patch.object(endpoint, 'call_with_http_info') as call_with_http_info: + endpoint() + call_with_http_info.assert_called_with( + _check_input_type=True, + _check_return_type=True, + _host_index=None, + _preload_content=True, + _request_timeout=None, + _return_http_data_only=True, + async_req=False, + header_number=1.234, + path_integer=34, + path_string='hello', + query_integer=3, + query_string='brillig' + ) + + def test_test_endpoint_parameters(self): + """Test case for test_endpoint_parameters + + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 + """ + # check that we can access the endpoint's validations + endpoint = self.api.test_endpoint_parameters + assert endpoint.validations[('number',)] == { + 'inclusive_maximum': 543.2, + 'inclusive_minimum': 32.1, + } + # make sure that an exception is thrown on an invalid value + keyword_args = dict( + number=544, # invalid + double=100, + pattern_without_delimiter="abc", + byte='sample string' + ) + with self.assertRaises(petstore_api.ApiValueError): + self.api.test_endpoint_parameters(**keyword_args) + + def test_test_enum_parameters(self): + """Test case for test_enum_parameters + + To test enum parameters # noqa: E501 + """ + # check that we can access the endpoint's allowed_values + endpoint = self.api.test_enum_parameters + assert endpoint.allowed_values[('enum_query_string',)] == { + "_ABC": "_abc", + "-EFG": "-efg", + "(XYZ)": "(xyz)" + } + # make sure that an exception is thrown on an invalid value + keyword_args = dict(enum_query_string="bad value") + with self.assertRaises(petstore_api.ApiValueError): + self.api.test_enum_parameters(**keyword_args) + + def test_test_group_parameters(self): + """Test case for test_group_parameters + + Fake endpoint to test group parameters (optional) # noqa: E501 + """ + pass + + def test_test_inline_additional_properties(self): + """Test case for test_inline_additional_properties + + test inline additionalProperties # noqa: E501 + """ + pass + + def test_test_json_form_data(self): + """Test case for test_json_form_data + + test json serialization of form data # noqa: E501 + """ + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_fake_classname_tags_123_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_fake_classname_tags_123_api.py new file mode 100644 index 000000000000..1ade31405a62 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_fake_classname_tags_123_api.py @@ -0,0 +1,39 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.api.fake_classname_tags_123_api import FakeClassnameTags123Api # noqa: E501 + + +class TestFakeClassnameTags123Api(unittest.TestCase): + """FakeClassnameTags123Api unit test stubs""" + + def setUp(self): + self.api = FakeClassnameTags123Api() # noqa: E501 + + def tearDown(self): + pass + + def test_test_classname(self): + """Test case for test_classname + + To test class name in snake case # noqa: E501 + """ + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_file.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_file.py new file mode 100644 index 000000000000..8d60f64e01cc --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_file.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.file import File + + +class TestFile(unittest.TestCase): + """File unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testFile(self): + """Test File""" + # FIXME: construct object with mandatory attributes with example values + # model = File() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_file_schema_test_class.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_file_schema_test_class.py new file mode 100644 index 000000000000..9a4f6d38dfef --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_file_schema_test_class.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import file +except ImportError: + file = sys.modules[ + 'petstore_api.model.file'] +from petstore_api.model.file_schema_test_class import FileSchemaTestClass + + +class TestFileSchemaTestClass(unittest.TestCase): + """FileSchemaTestClass unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testFileSchemaTestClass(self): + """Test FileSchemaTestClass""" + # FIXME: construct object with mandatory attributes with example values + # model = FileSchemaTestClass() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_format_test.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_format_test.py new file mode 100644 index 000000000000..ca37b005fd96 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_format_test.py @@ -0,0 +1,153 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.format_test import FormatTest + + +class TestFormatTest(unittest.TestCase): + """FormatTest unit test stubs""" + + def setUp(self): + import datetime + self.required_named_args = dict( + number=40.1, + byte='what', + date=datetime.date(2019, 3, 23), + password='rainbowtable' + ) + + def test_integer(self): + var_name = 'integer' + validations = FormatTest.validations[(var_name,)] + keyword_args = {} + keyword_args.update(self.required_named_args) + key_adder_pairs = [('inclusive_maximum', 1), ('inclusive_minimum', -1)] + for key, adder in key_adder_pairs: + # value outside the bounds throws an error + with self.assertRaises(petstore_api.ApiValueError): + keyword_args[var_name] = validations[key] + adder + FormatTest(**keyword_args) + + # value inside the bounds works + keyword_args[var_name] = validations[key] + assert (getattr(FormatTest(**keyword_args), var_name) == + validations[key]) + + def test_int32(self): + var_name = 'int32' + validations = FormatTest.validations[(var_name,)] + keyword_args = {} + keyword_args.update(self.required_named_args) + key_adder_pairs = [('inclusive_maximum', 1), ('inclusive_minimum', -1)] + for key, adder in key_adder_pairs: + # value outside the bounds throws an error + with self.assertRaises(petstore_api.ApiValueError): + keyword_args[var_name] = validations[key] + adder + FormatTest(**keyword_args) + + # value inside the bounds works + keyword_args[var_name] = validations[key] + assert (getattr(FormatTest(**keyword_args), var_name) == + validations[key]) + + def test_number(self): + var_name = 'number' + validations = FormatTest.validations[(var_name,)] + keyword_args = {} + keyword_args.update(self.required_named_args) + key_adder_pairs = [('inclusive_maximum', 1), ('inclusive_minimum', -1)] + for key, adder in key_adder_pairs: + # value outside the bounds throws an error + with self.assertRaises(petstore_api.ApiValueError): + keyword_args[var_name] = validations[key] + adder + FormatTest(**keyword_args) + + # value inside the bounds works + keyword_args[var_name] = validations[key] + assert (getattr(FormatTest(**keyword_args), var_name) == + validations[key]) + + def test_float(self): + var_name = 'float' + validations = FormatTest.validations[(var_name,)] + keyword_args = {} + keyword_args.update(self.required_named_args) + key_adder_pairs = [('inclusive_maximum', 1), ('inclusive_minimum', -1)] + for key, adder in key_adder_pairs: + # value outside the bounds throws an error + with self.assertRaises(petstore_api.ApiValueError): + keyword_args[var_name] = validations[key] + adder + FormatTest(**keyword_args) + + # value inside the bounds works + keyword_args[var_name] = validations[key] + assert (getattr(FormatTest(**keyword_args), var_name) == + validations[key]) + + def test_double(self): + var_name = 'double' + validations = FormatTest.validations[(var_name,)] + keyword_args = {} + keyword_args.update(self.required_named_args) + key_adder_pairs = [('inclusive_maximum', 1), ('inclusive_minimum', -1)] + for key, adder in key_adder_pairs: + # value outside the bounds throws an error + with self.assertRaises(petstore_api.ApiValueError): + keyword_args[var_name] = validations[key] + adder + FormatTest(**keyword_args) + + # value inside the bounds works + keyword_args[var_name] = validations[key] + assert (getattr(FormatTest(**keyword_args), var_name) == + validations[key]) + + def test_password(self): + var_name = 'password' + validations = FormatTest.validations[(var_name,)] + keyword_args = {} + keyword_args.update(self.required_named_args) + key_adder_pairs = [('max_length', 1), ('min_length', -1)] + for key, adder in key_adder_pairs: + # value outside the bounds throws an error + with self.assertRaises(petstore_api.ApiValueError): + keyword_args[var_name] = 'a'*(validations[key] + adder) + FormatTest(**keyword_args) + + # value inside the bounds works + keyword_args[var_name] = 'a'*validations[key] + assert (getattr(FormatTest(**keyword_args), var_name) == + 'a'*validations[key]) + + def test_string(self): + var_name = 'string' + validations = FormatTest.validations[(var_name,)] + keyword_args = {} + keyword_args.update(self.required_named_args) + values_invalid = ['abc3', '1', '.', ' ', 'مرحبا', ''] + for value_invalid in values_invalid: + # invalid values throw exceptions + with self.assertRaises(petstore_api.ApiValueError): + keyword_args[var_name] = value_invalid + FormatTest(**keyword_args) + + # valid value works + value_valid = 'abcdz' + keyword_args[var_name] = value_valid + assert getattr(FormatTest(**keyword_args), var_name) == value_valid + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_grandparent.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_grandparent.py new file mode 100644 index 000000000000..2972d01161cd --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_grandparent.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.grandparent import Grandparent + + +class TestGrandparent(unittest.TestCase): + """Grandparent unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testGrandparent(self): + """Test Grandparent""" + # FIXME: construct object with mandatory attributes with example values + # model = Grandparent() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_grandparent_animal.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_grandparent_animal.py new file mode 100644 index 000000000000..cabe4d81f98e --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_grandparent_animal.py @@ -0,0 +1,58 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import child_cat +except ImportError: + child_cat = sys.modules[ + 'petstore_api.model.child_cat'] +try: + from petstore_api.model import child_dog +except ImportError: + child_dog = sys.modules[ + 'petstore_api.model.child_dog'] +try: + from petstore_api.model import child_lizard +except ImportError: + child_lizard = sys.modules[ + 'petstore_api.model.child_lizard'] +try: + from petstore_api.model import parent_pet +except ImportError: + parent_pet = sys.modules[ + 'petstore_api.model.parent_pet'] +from petstore_api.model.grandparent_animal import GrandparentAnimal + + +class TestGrandparentAnimal(unittest.TestCase): + """GrandparentAnimal unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testGrandparentAnimal(self): + """Test GrandparentAnimal""" + # FIXME: construct object with mandatory attributes with example values + # model = GrandparentAnimal() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_has_only_read_only.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_has_only_read_only.py new file mode 100644 index 000000000000..9ebd7683b398 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_has_only_read_only.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.has_only_read_only import HasOnlyReadOnly + + +class TestHasOnlyReadOnly(unittest.TestCase): + """HasOnlyReadOnly unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testHasOnlyReadOnly(self): + """Test HasOnlyReadOnly""" + # FIXME: construct object with mandatory attributes with example values + # model = HasOnlyReadOnly() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_list.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_list.py new file mode 100644 index 000000000000..52156adfed2e --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_list.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.list import List + + +class TestList(unittest.TestCase): + """List unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testList(self): + """Test List""" + # FIXME: construct object with mandatory attributes with example values + # model = List() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_map_test.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_map_test.py new file mode 100644 index 000000000000..3feda0f688df --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_map_test.py @@ -0,0 +1,125 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import string_boolean_map +except ImportError: + string_boolean_map = sys.modules[ + 'petstore_api.model.string_boolean_map'] +from petstore_api.model.map_test import MapTest + + +class TestMapTest(unittest.TestCase): + """MapTest unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_maptest_init(self): + # + # Test MapTest construction with valid values + # + up_or_low_dict = { + 'UPPER': "UP", + 'lower': "low" + } + map_enum_test = MapTest(map_of_enum_string=up_or_low_dict) + + self.assertEqual(map_enum_test.map_of_enum_string, up_or_low_dict) + + map_of_map_of_strings = { + 'valueDict': up_or_low_dict + } + map_enum_test = MapTest(map_map_of_string=map_of_map_of_strings) + + self.assertEqual(map_enum_test.map_map_of_string, map_of_map_of_strings) + + # + # Make sure that the init fails for invalid enum values + # + black_or_white_dict = { + 'black': "UP", + 'white': "low" + } + with self.assertRaises(petstore_api.ApiValueError): + MapTest(map_of_enum_string=black_or_white_dict) + + def test_maptest_setter(self): + # + # Check with some valid values + # + map_enum_test = MapTest() + up_or_low_dict = { + 'UPPER': "UP", + 'lower': "low" + } + map_enum_test.map_of_enum_string = up_or_low_dict + self.assertEqual(map_enum_test.map_of_enum_string, up_or_low_dict) + + # + # Check if the setter fails for invalid enum values + # + map_enum_test = MapTest() + black_or_white_dict = { + 'black': "UP", + 'white': "low" + } + with self.assertRaises(petstore_api.ApiValueError): + map_enum_test.map_of_enum_string = black_or_white_dict + + def test_todict(self): + # + # Check dictionary serialization + # + map_enum_test = MapTest() + up_or_low_dict = { + 'UPPER': "UP", + 'lower': "low" + } + map_of_map_of_strings = { + 'valueDict': up_or_low_dict + } + indirect_map = string_boolean_map.StringBooleanMap(**{ + 'option1': True + }) + direct_map = { + 'option2': False + } + map_enum_test.map_of_enum_string = up_or_low_dict + map_enum_test.map_map_of_string = map_of_map_of_strings + map_enum_test.indirect_map = indirect_map + map_enum_test.direct_map = direct_map + + self.assertEqual(map_enum_test.map_of_enum_string, up_or_low_dict) + self.assertEqual(map_enum_test.map_map_of_string, map_of_map_of_strings) + self.assertEqual(map_enum_test.indirect_map, indirect_map) + self.assertEqual(map_enum_test.direct_map, direct_map) + + expected_dict = { + 'map_of_enum_string': up_or_low_dict, + 'map_map_of_string': map_of_map_of_strings, + 'indirect_map': indirect_map.to_dict(), + 'direct_map': direct_map + } + + self.assertEqual(map_enum_test.to_dict(), expected_dict) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_mixed_properties_and_additional_properties_class.py new file mode 100644 index 000000000000..4dcb5ad4268c --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_mixed_properties_and_additional_properties_class.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import animal +except ImportError: + animal = sys.modules[ + 'petstore_api.model.animal'] +from petstore_api.model.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass + + +class TestMixedPropertiesAndAdditionalPropertiesClass(unittest.TestCase): + """MixedPropertiesAndAdditionalPropertiesClass unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testMixedPropertiesAndAdditionalPropertiesClass(self): + """Test MixedPropertiesAndAdditionalPropertiesClass""" + # FIXME: construct object with mandatory attributes with example values + # model = MixedPropertiesAndAdditionalPropertiesClass() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_model200_response.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_model200_response.py new file mode 100644 index 000000000000..4012eaae3362 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_model200_response.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.model200_response import Model200Response + + +class TestModel200Response(unittest.TestCase): + """Model200Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testModel200Response(self): + """Test Model200Response""" + # FIXME: construct object with mandatory attributes with example values + # model = Model200Response() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_model_return.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_model_return.py new file mode 100644 index 000000000000..54c98b33cd66 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_model_return.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.model_return import ModelReturn + + +class TestModelReturn(unittest.TestCase): + """ModelReturn unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testModelReturn(self): + """Test ModelReturn""" + # FIXME: construct object with mandatory attributes with example values + # model = ModelReturn() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_name.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_name.py new file mode 100644 index 000000000000..6a9be99d1a57 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_name.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.name import Name + + +class TestName(unittest.TestCase): + """Name unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testName(self): + """Test Name""" + # FIXME: construct object with mandatory attributes with example values + # model = Name() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_number_only.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_number_only.py new file mode 100644 index 000000000000..07aab1d78af7 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_number_only.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.number_only import NumberOnly + + +class TestNumberOnly(unittest.TestCase): + """NumberOnly unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testNumberOnly(self): + """Test NumberOnly""" + # FIXME: construct object with mandatory attributes with example values + # model = NumberOnly() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_number_with_validations.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_number_with_validations.py new file mode 100644 index 000000000000..3f0b78835d4b --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_number_with_validations.py @@ -0,0 +1,45 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.number_with_validations import NumberWithValidations + + +class TestNumberWithValidations(unittest.TestCase): + """NumberWithValidations unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testNumberWithValidations(self): + """Test NumberWithValidations""" + valid_values = [10.0, 15.0, 20.0] + for valid_value in valid_values: + model = NumberWithValidations(valid_value) + assert model.value == valid_value + + invalid_values = [9.0, 21.0] + for invalid_value in invalid_values: + with self.assertRaises(petstore_api.ApiValueError): + NumberWithValidations(invalid_value) + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_object_model_with_ref_props.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_object_model_with_ref_props.py new file mode 100644 index 000000000000..35bd3b6d8ec7 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_object_model_with_ref_props.py @@ -0,0 +1,49 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import number_with_validations +except ImportError: + number_with_validations = sys.modules[ + 'petstore_api.model.number_with_validations'] +from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps + + +class TestObjectModelWithRefProps(unittest.TestCase): + """ObjectModelWithRefProps unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testObjectModelWithRefProps(self): + """Test ObjectModelWithRefProps""" + from petstore_api.model.number_with_validations import NumberWithValidations + self.assertEqual( + ObjectModelWithRefProps.openapi_types, + { + 'my_number': (NumberWithValidations,), + 'my_string': (str,), + 'my_boolean': (bool,), + } + ) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_order.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_order.py new file mode 100644 index 000000000000..ee6988e28ccd --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_order.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.order import Order + + +class TestOrder(unittest.TestCase): + """Order unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testOrder(self): + """Test Order""" + order = Order() + order.status = "placed" + self.assertEqual("placed", order.status) + with self.assertRaises(petstore_api.ApiValueError): + order.status = "invalid" + + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_parent.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_parent.py new file mode 100644 index 000000000000..20282dfb41ea --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_parent.py @@ -0,0 +1,48 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import grandparent +except ImportError: + grandparent = sys.modules[ + 'petstore_api.model.grandparent'] +try: + from petstore_api.model import parent_all_of +except ImportError: + parent_all_of = sys.modules[ + 'petstore_api.model.parent_all_of'] +from petstore_api.model.parent import Parent + + +class TestParent(unittest.TestCase): + """Parent unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testParent(self): + """Test Parent""" + # FIXME: construct object with mandatory attributes with example values + # model = Parent() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_parent_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_parent_all_of.py new file mode 100644 index 000000000000..ca87189bba50 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_parent_all_of.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.parent_all_of import ParentAllOf + + +class TestParentAllOf(unittest.TestCase): + """ParentAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testParentAllOf(self): + """Test ParentAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = ParentAllOf() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_parent_pet.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_parent_pet.py new file mode 100644 index 000000000000..17a4d60e75dc --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_parent_pet.py @@ -0,0 +1,58 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import child_cat +except ImportError: + child_cat = sys.modules[ + 'petstore_api.model.child_cat'] +try: + from petstore_api.model import child_dog +except ImportError: + child_dog = sys.modules[ + 'petstore_api.model.child_dog'] +try: + from petstore_api.model import child_lizard +except ImportError: + child_lizard = sys.modules[ + 'petstore_api.model.child_lizard'] +try: + from petstore_api.model import grandparent_animal +except ImportError: + grandparent_animal = sys.modules[ + 'petstore_api.model.grandparent_animal'] +from petstore_api.model.parent_pet import ParentPet + + +class TestParentPet(unittest.TestCase): + """ParentPet unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testParentPet(self): + """Test ParentPet""" + # FIXME: construct object with mandatory attributes with example values + # model = ParentPet() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_pet.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_pet.py new file mode 100644 index 000000000000..b072cff5e9ad --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_pet.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +try: + from petstore_api.model import category +except ImportError: + category = sys.modules[ + 'petstore_api.model.category'] +try: + from petstore_api.models import tag +except ImportError: + tag = sys.modules[ + 'petstore_api.model.tag'] +from petstore_api.model.pet import Pet + + +class TestPet(unittest.TestCase): + """Pet unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_to_str(self): + pet = Pet(name="test name", photo_urls=["string"]) + pet.id = 1 + pet.status = "available" + cate = category.Category() + cate.id = 1 + cate.name = "dog" + pet.category = cate + tag1 = tag.Tag() + tag1.id = 1 + pet.tags = [tag1] + + data = ("{'category': {'id': 1, 'name': 'dog'},\n" + " 'id': 1,\n" + " 'name': 'test name',\n" + " 'photo_urls': ['string'],\n" + " 'status': 'available',\n" + " 'tags': [{'id': 1}]}") + self.assertEqual(data, pet.to_str()) + + def test_equal(self): + pet1 = Pet(name="test name", photo_urls=["string"]) + pet1.id = 1 + pet1.status = "available" + cate1 = category.Category() + cate1.id = 1 + cate1.name = "dog" + tag1 = tag.Tag() + tag1.id = 1 + pet1.tags = [tag1] + + pet2 = Pet(name="test name", photo_urls=["string"]) + pet2.id = 1 + pet2.status = "available" + cate2 = category.Category() + cate2.id = 1 + cate2.name = "dog" + tag2 = tag.Tag() + tag2.id = 1 + pet2.tags = [tag2] + + self.assertTrue(pet1 == pet2) + + # reset pet1 tags to empty array so that object comparison returns false + pet1.tags = [] + self.assertFalse(pet1 == pet2) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_pet_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_pet_api.py new file mode 100644 index 000000000000..091b30cf8ac0 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_pet_api.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.api.pet_api import PetApi # noqa: E501 + + +class TestPetApi(unittest.TestCase): + """PetApi unit test stubs""" + + def setUp(self): + self.api = PetApi() # noqa: E501 + + def tearDown(self): + pass + + def test_add_pet(self): + """Test case for add_pet + + Add a new pet to the store # noqa: E501 + """ + pass + + def test_delete_pet(self): + """Test case for delete_pet + + Deletes a pet # noqa: E501 + """ + pass + + def test_find_pets_by_status(self): + """Test case for find_pets_by_status + + Finds Pets by status # noqa: E501 + """ + pass + + def test_find_pets_by_tags(self): + """Test case for find_pets_by_tags + + Finds Pets by tags # noqa: E501 + """ + pass + + def test_get_pet_by_id(self): + """Test case for get_pet_by_id + + Find pet by ID # noqa: E501 + """ + pass + + def test_update_pet(self): + """Test case for update_pet + + Update an existing pet # noqa: E501 + """ + pass + + def test_update_pet_with_form(self): + """Test case for update_pet_with_form + + Updates a pet in the store with form data # noqa: E501 + """ + pass + + def test_upload_file(self): + """Test case for upload_file + + uploads an image # noqa: E501 + """ + pass + + def test_upload_file_with_required_file(self): + """Test case for upload_file_with_required_file + + uploads an image (required) # noqa: E501 + """ + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_player.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_player.py new file mode 100644 index 000000000000..ee7b95a677f1 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_player.py @@ -0,0 +1,44 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.player import Player + + +class TestPlayer(unittest.TestCase): + """Player unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testPlayer(self): + """Test Player""" + # we can make a player without an enemy_player property + jane = Player(name="Jane") + # we can make a player with an enemy_player + sally = Player(name="Sally", enemy_player=jane) + # we can make a player with an inline enemy_player + jim = Player( + name="Jim", + enemy_player=Player(name="Sam") + ) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_read_only_first.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_read_only_first.py new file mode 100644 index 000000000000..c2dcde240e77 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_read_only_first.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.read_only_first import ReadOnlyFirst + + +class TestReadOnlyFirst(unittest.TestCase): + """ReadOnlyFirst unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testReadOnlyFirst(self): + """Test ReadOnlyFirst""" + # FIXME: construct object with mandatory attributes with example values + # model = ReadOnlyFirst() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_special_model_name.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_special_model_name.py new file mode 100644 index 000000000000..6124525f5170 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_special_model_name.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.special_model_name import SpecialModelName + + +class TestSpecialModelName(unittest.TestCase): + """SpecialModelName unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testSpecialModelName(self): + """Test SpecialModelName""" + # FIXME: construct object with mandatory attributes with example values + # model = SpecialModelName() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_store_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_store_api.py new file mode 100644 index 000000000000..0d9cc3dd36ea --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_store_api.py @@ -0,0 +1,60 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api +from petstore_api.api.store_api import StoreApi # noqa: E501 + + +class TestStoreApi(unittest.TestCase): + """StoreApi unit test stubs""" + + def setUp(self): + self.api = StoreApi() # noqa: E501 + + def tearDown(self): + pass + + def test_delete_order(self): + """Test case for delete_order + + Delete purchase order by ID # noqa: E501 + """ + pass + + def test_get_inventory(self): + """Test case for get_inventory + + Returns pet inventories by status # noqa: E501 + """ + pass + + def test_get_order_by_id(self): + """Test case for get_order_by_id + + Find purchase order by ID # noqa: E501 + """ + pass + + def test_place_order(self): + """Test case for place_order + + Place an order for a pet # noqa: E501 + """ + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_string_boolean_map.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_string_boolean_map.py new file mode 100644 index 000000000000..e2e9d8b420b8 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_string_boolean_map.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.string_boolean_map import StringBooleanMap + + +class TestStringBooleanMap(unittest.TestCase): + """StringBooleanMap unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testStringBooleanMap(self): + """Test StringBooleanMap""" + # FIXME: construct object with mandatory attributes with example values + # model = StringBooleanMap() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_string_enum.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_string_enum.py new file mode 100644 index 000000000000..5eed0ad6f0e9 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_string_enum.py @@ -0,0 +1,49 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.string_enum import StringEnum + + +class TestStringEnum(unittest.TestCase): + """StringEnum unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testStringEnum(self): + """Test StringEnum""" + + """Test OuterEnum""" + # make sure that we can access its allowed_values + assert StringEnum.allowed_values[('value',)] == { + 'PLACED': "placed", + 'APPROVED': "approved", + 'DELIVERED': "delivered" + } + # make sure that an exception is thrown on an invalid value + with self.assertRaises(petstore_api.ApiValueError): + StringEnum('bad_value') + # make sure valid value works + valid_value = StringEnum.allowed_values[('value',)]['PLACED'] + assert valid_value == StringEnum(valid_value).value + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_tag.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_tag.py new file mode 100644 index 000000000000..68a3b9046bf4 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_tag.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.tag import Tag + + +class TestTag(unittest.TestCase): + """Tag unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testTag(self): + """Test Tag""" + # FIXME: construct object with mandatory attributes with example values + # model = Tag() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_type_holder_default.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_type_holder_default.py new file mode 100644 index 000000000000..f9c050b81a82 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_type_holder_default.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.type_holder_default import TypeHolderDefault + + +class TestTypeHolderDefault(unittest.TestCase): + """TypeHolderDefault unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testTypeHolderDefault(self): + """Test TypeHolderDefault""" + # required_vars are set to None now until swagger-parser/swagger-core fixes + # https://github.com/swagger-api/swagger-parser/issues/971 + array_item = [1, 2, 3] + model = TypeHolderDefault(array_item=array_item) + self.assertEqual(model.string_item, 'what') + self.assertEqual(model.bool_item, True) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_type_holder_example.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_type_holder_example.py new file mode 100644 index 000000000000..e1ee7c368628 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_type_holder_example.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.type_holder_example import TypeHolderExample + + +class TestTypeHolderExample(unittest.TestCase): + """TypeHolderExample unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testTypeHolderExample(self): + """Test TypeHolderExample""" + # FIXME: construct object with mandatory attributes with example values + # model = TypeHolderExample() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_user.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_user.py new file mode 100644 index 000000000000..7241bb589c52 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_user.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.user import User + + +class TestUser(unittest.TestCase): + """User unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testUser(self): + """Test User""" + # FIXME: construct object with mandatory attributes with example values + # model = User() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_user_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_user_api.py new file mode 100644 index 000000000000..df306da07761 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_user_api.py @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api +from petstore_api.api.user_api import UserApi # noqa: E501 + + +class TestUserApi(unittest.TestCase): + """UserApi unit test stubs""" + + def setUp(self): + self.api = UserApi() # noqa: E501 + + def tearDown(self): + pass + + def test_create_user(self): + """Test case for create_user + + Create user # noqa: E501 + """ + pass + + def test_create_users_with_array_input(self): + """Test case for create_users_with_array_input + + Creates list of users with given input array # noqa: E501 + """ + pass + + def test_create_users_with_list_input(self): + """Test case for create_users_with_list_input + + Creates list of users with given input array # noqa: E501 + """ + pass + + def test_delete_user(self): + """Test case for delete_user + + Delete user # noqa: E501 + """ + pass + + def test_get_user_by_name(self): + """Test case for get_user_by_name + + Get user by user name # noqa: E501 + """ + pass + + def test_login_user(self): + """Test case for login_user + + Logs user into the system # noqa: E501 + """ + pass + + def test_logout_user(self): + """Test case for logout_user + + Logs out current logged in user session # noqa: E501 + """ + pass + + def test_update_user(self): + """Test case for update_user + + Updated user # noqa: E501 + """ + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_xml_item.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_xml_item.py new file mode 100644 index 000000000000..4354664815ff --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_xml_item.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import sys +import unittest + +import petstore_api +from petstore_api.model.xml_item import XmlItem + + +class TestXmlItem(unittest.TestCase): + """XmlItem unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testXmlItem(self): + """Test XmlItem""" + # FIXME: construct object with mandatory attributes with example values + # model = XmlItem() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test_python.sh b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test_python.sh new file mode 100644 index 000000000000..6f5e2c41d3a6 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test_python.sh @@ -0,0 +1,31 @@ +#!/bin/bash + +REQUIREMENTS_FILE=dev-requirements.txt +REQUIREMENTS_OUT=dev-requirements.txt.log +SETUP_OUT=*.egg-info +VENV=venv +DEACTIVE=false + +export LC_ALL=en_US.UTF-8 +export LANG=en_US.UTF-8 + +### set virtualenv +if [ -z "$VIRTUAL_ENV" ]; then + virtualenv $VENV --no-site-packages --always-copy + source $VENV/bin/activate + DEACTIVE=true +fi + +### install dependencies +pip install -r $REQUIREMENTS_FILE | tee -a $REQUIREMENTS_OUT + +### run tests +tox || exit 1 + +### static analysis of code +#flake8 --show-source petstore_api/ + +### deactivate virtualenv +#if [ $DEACTIVE == true ]; then +# deactivate +#fi diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/testfiles/1px_pic1.png b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/testfiles/1px_pic1.png new file mode 100644 index 000000000000..7d3a386a2102 Binary files /dev/null and b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/testfiles/1px_pic1.png differ diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/testfiles/1px_pic2.png b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/testfiles/1px_pic2.png new file mode 100644 index 000000000000..7d3a386a2102 Binary files /dev/null and b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/testfiles/1px_pic2.png differ diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/testfiles/foo.png b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/testfiles/foo.png new file mode 100644 index 000000000000..a9b12cf5927a Binary files /dev/null and b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/testfiles/foo.png differ diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/__init__.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_api_client.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_api_client.py new file mode 100644 index 000000000000..c249bf1fc5e8 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_api_client.py @@ -0,0 +1,221 @@ +# coding: utf-8 + +# flake8: noqa + +""" +Run the tests. +$ pip install nose (optional) +$ cd OpenAPIetstore-python +$ nosetests -v +""" + +import os +import time +import atexit +import weakref +import unittest +from dateutil.parser import parse + +import petstore_api +import petstore_api.configuration + +HOST = 'http://petstore.swagger.io/v2' + + +class ApiClientTests(unittest.TestCase): + + def setUp(self): + self.api_client = petstore_api.ApiClient() + + def test_configuration(self): + config = petstore_api.Configuration() + config.host = 'http://localhost/' + + config.api_key['api_key'] = '123456' + config.api_key_prefix['api_key'] = 'PREFIX' + config.username = 'test_username' + config.password = 'test_password' + + header_params = {'test1': 'value1'} + query_params = {'test2': 'value2'} + auth_settings = ['api_key', 'unknown'] + + client = petstore_api.ApiClient(config) + + # test prefix + self.assertEqual('PREFIX', client.configuration.api_key_prefix['api_key']) + + # update parameters based on auth setting + client.update_params_for_auth(header_params, query_params, auth_settings, resource_path=None, method=None, body=None) + + # test api key auth + self.assertEqual(header_params['test1'], 'value1') + self.assertEqual(header_params['api_key'], 'PREFIX 123456') + self.assertEqual(query_params['test2'], 'value2') + + # test basic auth + self.assertEqual('test_username', client.configuration.username) + self.assertEqual('test_password', client.configuration.password) + + # test api key without prefix + config.api_key['api_key'] = '123456' + config.api_key_prefix['api_key'] = None + # update parameters based on auth setting + client.update_params_for_auth(header_params, query_params, auth_settings, resource_path=None, method=None, body=None) + self.assertEqual(header_params['api_key'], '123456') + + # test api key with empty prefix + config.api_key['api_key'] = '123456' + config.api_key_prefix['api_key'] = '' + # update parameters based on auth setting + client.update_params_for_auth(header_params, query_params, auth_settings, resource_path=None, method=None, body=None) + self.assertEqual(header_params['api_key'], '123456') + + # test api key with prefix specified in the api_key, useful when the prefix + # must include '=' sign followed by the API key secret without space. + config.api_key['api_key'] = 'PREFIX=123456' + config.api_key_prefix['api_key'] = None + # update parameters based on auth setting + client.update_params_for_auth(header_params, query_params, auth_settings, resource_path=None, method=None, body=None) + self.assertEqual(header_params['api_key'], 'PREFIX=123456') + + + def test_select_header_accept(self): + accepts = ['APPLICATION/JSON', 'APPLICATION/XML'] + accept = self.api_client.select_header_accept(accepts) + self.assertEqual(accept, 'application/json') + + accepts = ['application/json', 'application/xml'] + accept = self.api_client.select_header_accept(accepts) + self.assertEqual(accept, 'application/json') + + accepts = ['application/xml', 'application/json'] + accept = self.api_client.select_header_accept(accepts) + self.assertEqual(accept, 'application/json') + + accepts = ['text/plain', 'application/xml'] + accept = self.api_client.select_header_accept(accepts) + self.assertEqual(accept, 'text/plain, application/xml') + + accepts = [] + accept = self.api_client.select_header_accept(accepts) + self.assertEqual(accept, None) + + def test_select_header_content_type(self): + content_types = ['APPLICATION/JSON', 'APPLICATION/XML'] + content_type = self.api_client.select_header_content_type(content_types) + self.assertEqual(content_type, 'application/json') + + content_types = ['application/json', 'application/xml'] + content_type = self.api_client.select_header_content_type(content_types) + self.assertEqual(content_type, 'application/json') + + content_types = ['application/xml', 'application/json'] + content_type = self.api_client.select_header_content_type(content_types) + self.assertEqual(content_type, 'application/json') + + content_types = ['text/plain', 'application/xml'] + content_type = self.api_client.select_header_content_type(content_types) + self.assertEqual(content_type, 'text/plain') + + content_types = [] + content_type = self.api_client.select_header_content_type(content_types) + self.assertEqual(content_type, 'application/json') + + def test_sanitize_for_serialization(self): + # None + data = None + result = self.api_client.sanitize_for_serialization(None) + self.assertEqual(result, data) + + # str + data = "test string" + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, data) + + # int + data = 1 + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, data) + + # bool + data = True + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, data) + + # date + data = parse("1997-07-16").date() # date + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, "1997-07-16") + + # datetime + data = parse("1997-07-16T19:20:30.45+01:00") # datetime + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, "1997-07-16T19:20:30.450000+01:00") + + # list + data = [1] + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, data) + + # dict + data = {"test key": "test value"} + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, data) + + # model + pet_dict = {"id": 1, "name": "monkey", + "category": {"id": 1, "name": "test category"}, + "tags": [{"id": 1, "fullName": "test tag1"}, + {"id": 2, "fullName": "test tag2"}], + "status": "available", + "photoUrls": ["http://foo.bar.com/3", + "http://foo.bar.com/4"]} + from petstore_api.model.pet import Pet + from petstore_api.model.category import Category + from petstore_api.model.tag import Tag + from petstore_api.model.string_boolean_map import StringBooleanMap + pet = Pet(name=pet_dict["name"], photo_urls=pet_dict["photoUrls"]) + pet.id = pet_dict["id"] + cate = Category() + cate.id = pet_dict["category"]["id"] + cate.name = pet_dict["category"]["name"] + pet.category = cate + tag1 = Tag() + tag1.id = pet_dict["tags"][0]["id"] + tag1.full_name = pet_dict["tags"][0]["fullName"] + tag2 = Tag() + tag2.id = pet_dict["tags"][1]["id"] + tag2.full_name = pet_dict["tags"][1]["fullName"] + pet.tags = [tag1, tag2] + pet.status = pet_dict["status"] + + data = pet + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, pet_dict) + + # list of models + list_of_pet_dict = [pet_dict] + data = [pet] + result = self.api_client.sanitize_for_serialization(data) + self.assertEqual(result, list_of_pet_dict) + + # model with additional proerties + model_dict = {'some_key': True} + model = StringBooleanMap(**model_dict) + result = self.api_client.sanitize_for_serialization(model) + self.assertEqual(result, model_dict) + + def test_context_manager_closes_threadpool(self): + with petstore_api.ApiClient() as client: + self.assertIsNotNone(client.pool) + pool_ref = weakref.ref(client._pool) + self.assertIsNotNone(pool_ref()) + self.assertIsNone(pool_ref()) + + def test_atexit_closes_threadpool(self): + client = petstore_api.ApiClient() + self.assertIsNotNone(client.pool) + self.assertIsNotNone(client._pool) + atexit._run_exitfuncs() + self.assertIsNone(client._pool) diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_api_exception.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_api_exception.py new file mode 100644 index 000000000000..0d0771b57850 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_api_exception.py @@ -0,0 +1,86 @@ +# coding: utf-8 + +# flake8: noqa + +""" +Run the tests. +$ pip install nose (optional) +$ cd petstore_api-python +$ nosetests -v +""" + +import os +import six +import sys +import unittest + +import petstore_api + +from .util import id_gen + +class ApiExceptionTests(unittest.TestCase): + + def setUp(self): + self.api_client = petstore_api.ApiClient() + from petstore_api.api.pet_api import PetApi + self.pet_api = PetApi(self.api_client) + self.setUpModels() + + def setUpModels(self): + from petstore_api.model import category, tag, pet + self.category = category.Category() + self.category.id = id_gen() + self.category.name = "dog" + self.tag = tag.Tag() + self.tag.id = id_gen() + self.tag.full_name = "blank" + self.pet = pet.Pet(name="hello kity", photo_urls=["http://foo.bar.com/1", "http://foo.bar.com/2"]) + self.pet.id = id_gen() + self.pet.status = "sold" + self.pet.category = self.category + self.pet.tags = [self.tag] + + def test_404_error(self): + self.pet_api.add_pet(self.pet) + self.pet_api.delete_pet(pet_id=self.pet.id) + + with self.checkRaiseRegex(petstore_api.ApiException, "Pet not found"): + self.pet_api.get_pet_by_id(pet_id=self.pet.id) + + try: + self.pet_api.get_pet_by_id(pet_id=self.pet.id) + except petstore_api.ApiException as e: + self.assertEqual(e.status, 404) + self.assertEqual(e.reason, "Not Found") + self.checkRegex(e.body, "Pet not found") + + def test_500_error(self): + self.pet_api.add_pet(self.pet) + + with self.checkRaiseRegex(petstore_api.ApiException, "Internal Server Error"): + self.pet_api.upload_file( + pet_id=self.pet.id, + additional_metadata="special" + ) + + try: + self.pet_api.upload_file( + pet_id=self.pet.id, + additional_metadata="special" + ) + except petstore_api.ApiException as e: + self.assertEqual(e.status, 500) + self.assertEqual(e.reason, "Internal Server Error") + self.checkRegex(e.body, "Error 500 Internal Server Error") + + def checkRaiseRegex(self, expected_exception, expected_regex): + if sys.version_info < (3, 0): + return self.assertRaisesRegexp(expected_exception, expected_regex) + + return self.assertRaisesRegex(expected_exception, expected_regex) + + def checkRegex(self, text, expected_regex): + if sys.version_info < (3, 0): + return self.assertRegexpMatches(text, expected_regex) + + return self.assertRegex(text, expected_regex) diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_deserialization.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_deserialization.py new file mode 100644 index 000000000000..92903bb232dd --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_deserialization.py @@ -0,0 +1,442 @@ +# coding: utf-8 + +# flake8: noqa + +""" +Run the tests. +$ pip install nose (optional) +$ cd OpenAPIPetstore-python +$ nosetests -v +""" +from collections import namedtuple +import json +import os +import time +import unittest +import datetime + +import six + +import petstore_api + +from petstore_api.exceptions import ( + ApiTypeError, + ApiKeyError, + ApiValueError, +) +from petstore_api.model import ( + enum_test, + pet, + animal, + dog, + parent_pet, + child_lizard, + category, + string_enum, + number_with_validations, + string_boolean_map, +) +from petstore_api.model_utils import ( + file_type, + model_to_dict, +) + +from petstore_api.rest import RESTResponse + +MockResponse = namedtuple('MockResponse', 'data') + +class DeserializationTests(unittest.TestCase): + + def setUp(self): + self.api_client = petstore_api.ApiClient() + self.deserialize = self.api_client.deserialize + + def test_enum_test(self): + """ deserialize dict(str, Enum_Test) """ + data = { + 'enum_test': { + "enum_string": "UPPER", + "enum_string_required": "lower", + "enum_integer": 1, + "enum_number": 1.1, + "stringEnum": "placed" + } + } + response = MockResponse(data=json.dumps(data)) + + deserialized = self.deserialize(response, + ({str: (enum_test.EnumTest,)},), True) + self.assertTrue(isinstance(deserialized, dict)) + self.assertTrue( + isinstance(deserialized['enum_test'], enum_test.EnumTest)) + value = ( + string_enum.StringEnum.allowed_values[('value',)]["PLACED"]) + string_enum_val = string_enum.StringEnum(value) + sample_instance = enum_test.EnumTest( + enum_string="UPPER", + enum_string_required="lower", + enum_integer=1, + enum_number=1.1, + string_enum=string_enum_val + ) + self.assertEqual(deserialized['enum_test'], sample_instance) + + def test_deserialize_dict_str_pet(self): + """ deserialize dict(str, Pet) """ + data = { + 'pet': { + "id": 0, + "category": { + "id": 0, + "name": "string" + }, + "name": "doggie", + "photoUrls": [ + "string" + ], + "tags": [ + { + "id": 0, + "fullName": "string" + } + ], + "status": "available" + } + } + response = MockResponse(data=json.dumps(data)) + + deserialized = self.deserialize(response, + ({str: (pet.Pet,)},), True) + self.assertTrue(isinstance(deserialized, dict)) + self.assertTrue(isinstance(deserialized['pet'], pet.Pet)) + + def test_deserialize_dict_str_dog(self): + """ deserialize dict(str, Dog), use discriminator + This will fail because additional_properties_type is None in Animal and it must be defined as any type + to allow in the property breed which is not defined in Animal, it is defined in Dog + """ + with self.assertRaises(petstore_api.exceptions.ApiValueError): + data = { + 'dog': { + "className": "Dog", + "color": "white", + "breed": "Jack Russel Terrier" + } + } + response = MockResponse(data=json.dumps(data)) + + deserialized = self.deserialize(response, + ({str: (animal.Animal,)},), True) + + def test_deserialize_lizard(self): + """ deserialize ChildLizard, use discriminator + because additional_properties_type is None in ChildLizardAllOf + we are unable to use the discriminator + For this to work correctly, additional_properties_type must allow in any type + Then in ChildLizardAllOf defines the property pet_type and allows in lovesRocks as an additionalProperty + """ + with self.assertRaises(petstore_api.exceptions.ApiValueError): + data = { + "pet_type": "ChildLizard", + "lovesRocks": True + } + response = MockResponse(data=json.dumps(data)) + + lizard = self.deserialize(response, + (parent_pet.ParentPet,), True) + + def test_deserialize_dict_str_int(self): + """ deserialize dict(str, int) """ + data = { + 'integer': 1 + } + response = MockResponse(data=json.dumps(data)) + + deserialized = self.deserialize(response, ({str: (int,)},), True) + self.assertTrue(isinstance(deserialized, dict)) + self.assertTrue(isinstance(deserialized['integer'], int)) + + def test_deserialize_str(self): + """ deserialize str """ + data = "test str" + response = MockResponse(data=json.dumps(data)) + + deserialized = self.deserialize(response, (str,), True) + self.assertTrue(isinstance(deserialized, str)) + + def test_deserialize_date(self): + """ deserialize date """ + data = "1997-07-16" + response = MockResponse(data=json.dumps(data)) + + deserialized = self.deserialize(response, (datetime.date,), True) + self.assertTrue(isinstance(deserialized, datetime.date)) + + def test_deserialize_datetime(self): + """ deserialize datetime """ + data = "1997-07-16T19:20:30.45+01:00" + response = MockResponse(data=json.dumps(data)) + + deserialized = self.deserialize(response, (datetime.datetime,), True) + self.assertTrue(isinstance(deserialized, datetime.datetime)) + + def test_deserialize_pet(self): + """ deserialize pet """ + data = { + "id": 0, + "category": { + "id": 0, + "name": "string" + }, + "name": "doggie", + "photoUrls": [ + "string" + ], + "tags": [ + { + "id": 0, + "fullName": "string" + } + ], + "status": "available" + } + response = MockResponse(data=json.dumps(data)) + + deserialized = self.deserialize(response, (pet.Pet,), True) + self.assertTrue(isinstance(deserialized, pet.Pet)) + self.assertEqual(deserialized.id, 0) + self.assertEqual(deserialized.name, "doggie") + self.assertTrue(isinstance(deserialized.category, category.Category)) + self.assertEqual(deserialized.category.name, "string") + self.assertTrue(isinstance(deserialized.tags, list)) + self.assertEqual(deserialized.tags[0].full_name, "string") + + def test_deserialize_list_of_pet(self): + """ deserialize list[Pet] """ + data = [ + { + "id": 0, + "category": { + "id": 0, + "name": "string" + }, + "name": "doggie0", + "photoUrls": [ + "string" + ], + "tags": [ + { + "id": 0, + "fullName": "string" + } + ], + "status": "available" + }, + { + "id": 1, + "category": { + "id": 0, + "name": "string" + }, + "name": "doggie1", + "photoUrls": [ + "string" + ], + "tags": [ + { + "id": 0, + "fullName": "string" + } + ], + "status": "available" + }] + response = MockResponse(data=json.dumps(data)) + + deserialized = self.deserialize(response, + ([pet.Pet],), True) + self.assertTrue(isinstance(deserialized, list)) + self.assertTrue(isinstance(deserialized[0], pet.Pet)) + self.assertEqual(deserialized[0].id, 0) + self.assertEqual(deserialized[1].id, 1) + self.assertEqual(deserialized[0].name, "doggie0") + self.assertEqual(deserialized[1].name, "doggie1") + + def test_deserialize_nested_dict(self): + """ deserialize dict(str, dict(str, int)) """ + data = { + "foo": { + "bar": 1 + } + } + response = MockResponse(data=json.dumps(data)) + + deserialized = self.deserialize(response, + ({str: ({str: (int,)},)},), True) + self.assertTrue(isinstance(deserialized, dict)) + self.assertTrue(isinstance(deserialized["foo"], dict)) + self.assertTrue(isinstance(deserialized["foo"]["bar"], int)) + + def test_deserialize_nested_list(self): + """ deserialize list[list[str]] """ + data = [["foo"]] + response = MockResponse(data=json.dumps(data)) + + deserialized = self.deserialize(response, ([[str]],), True) + self.assertTrue(isinstance(deserialized, list)) + self.assertTrue(isinstance(deserialized[0], list)) + self.assertTrue(isinstance(deserialized[0][0], str)) + + def test_deserialize_none(self): + """ deserialize None """ + response = MockResponse(data=json.dumps(None)) + + error_msg = ( + "Invalid type for variable 'received_data'. Required value type is " + "datetime and passed type was NoneType at ['received_data']" + ) + with self.assertRaises(ApiTypeError) as exc: + deserialized = self.deserialize(response, (datetime.datetime,), True) + self.assertEqual(str(exc.exception), error_msg) + + def test_deserialize_OuterEnum(self): + """ deserialize OuterEnum """ + # make sure that an exception is thrown on an invalid value + with self.assertRaises(ApiValueError): + self.deserialize( + MockResponse(data=json.dumps("test str")), + (string_enum.StringEnum,), + True + ) + + # valid value works + placed_str = ( + string_enum.StringEnum.allowed_values[('value',)]["PLACED"] + ) + response = MockResponse(data=json.dumps(placed_str)) + deserialized = self.deserialize(response, + (string_enum.StringEnum,), True) + self.assertTrue(isinstance(deserialized, string_enum.StringEnum)) + self.assertTrue(deserialized.value == placed_str) + + def test_deserialize_NumberWithValidations(self): + """ deserialize NumberWithValidations """ + # make sure that an exception is thrown on an invalid type value + with self.assertRaises(ApiTypeError): + deserialized = self.deserialize( + MockResponse(data=json.dumps("test str")), + (number_with_validations.NumberWithValidations,), + True + ) + + # make sure that an exception is thrown on an invalid value + with self.assertRaises(ApiValueError): + deserialized = self.deserialize( + MockResponse(data=json.dumps(21.0)), + (number_with_validations.NumberWithValidations,), + True + ) + + # valid value works + number_val = 11.0 + response = MockResponse(data=json.dumps(number_val)) + number = self.deserialize(response, + (number_with_validations.NumberWithValidations,), True) + self.assertTrue(isinstance(number, number_with_validations.NumberWithValidations)) + self.assertTrue(number.value == number_val) + + def test_deserialize_file(self): + """Ensures that file deserialization works""" + response_types_mixed = (file_type,) + + # sample from http://www.jtricks.com/download-text + HTTPResponse = namedtuple( + 'urllib3_response_HTTPResponse', + ['status', 'reason', 'data', 'getheaders', 'getheader'] + ) + headers = {'Content-Disposition': 'attachment; filename=content.txt'} + def get_headers(): + return headers + def get_header(name, default=None): + return headers.get(name, default) + file_data = ( + "You are reading text file that was supposed to be downloaded\r\n" + "to your hard disk. If your browser offered to save you the file," + "\r\nthen it handled the Content-Disposition header correctly." + ) + http_response = HTTPResponse( + status=200, + reason='OK', + data=file_data, + getheaders=get_headers, + getheader=get_header + ) + # response which is deserialized to a file + mock_response = RESTResponse(http_response) + file_path = None + try: + file_object = self.deserialize( + mock_response, response_types_mixed, True) + self.assertTrue(isinstance(file_object, file_type)) + file_path = file_object.name + self.assertFalse(file_object.closed) + file_object.close() + if six.PY3: + file_data = file_data.encode('utf-8') + with open(file_path, 'rb') as other_file_object: + self.assertEqual(other_file_object.read(), file_data) + finally: + os.unlink(file_path) + + def test_deserialize_binary_to_str(self): + """Ensures that bytes deserialization works""" + response_types_mixed = (str,) + + # sample from http://www.jtricks.com/download-text + HTTPResponse = namedtuple( + 'urllib3_response_HTTPResponse', + ['status', 'reason', 'data', 'getheaders', 'getheader'] + ) + headers = {} + def get_headers(): + return headers + def get_header(name, default=None): + return headers.get(name, default) + data = "str" + + http_response = HTTPResponse( + status=200, + reason='OK', + data=json.dumps(data).encode("utf-8") if six.PY3 else json.dumps(data), + getheaders=get_headers, + getheader=get_header + ) + + mock_response = RESTResponse(http_response) + + result = self.deserialize(mock_response, response_types_mixed, True) + self.assertEqual(isinstance(result, str), True) + self.assertEqual(result, data) + + def test_deserialize_string_boolean_map(self): + """ + Ensures that string boolean (additional properties) + deserialization works + """ + # make sure that an exception is thrown on an invalid type + with self.assertRaises(ApiTypeError): + deserialized = self.deserialize( + MockResponse(data=json.dumps("test str")), + (string_boolean_map.StringBooleanMap,), + True + ) + + # valid value works + item_val = {'some_key': True} + response = MockResponse(data=json.dumps(item_val)) + model = string_boolean_map.StringBooleanMap(**item_val) + deserialized = self.deserialize(response, + (string_boolean_map.StringBooleanMap,), True) + self.assertTrue(isinstance(deserialized, string_boolean_map.StringBooleanMap)) + self.assertTrue(deserialized['some_key'] == True) + self.assertTrue(deserialized == model) + diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_pet_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_pet_api.py new file mode 100644 index 000000000000..38d7a1cc0b82 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_pet_api.py @@ -0,0 +1,406 @@ +# coding: utf-8 + +# flake8: noqa + +""" +Run the tests. +$ docker pull swaggerapi/petstore +$ docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore +$ pip install nose (optional) +$ cd petstore_api-python +$ nosetests -v +""" + +from collections import namedtuple +import json +import os +import unittest + +import petstore_api +from petstore_api import Configuration +from petstore_api.rest import ( + RESTClientObject, + RESTResponse +) + +import six + +from petstore_api.exceptions import ( + ApiException, + ApiValueError, + ApiTypeError, +) +from petstore_api.api.pet_api import PetApi +from petstore_api.model import pet +from .util import id_gen + +import urllib3 + +if six.PY3: + from unittest.mock import patch +else: + from mock import patch + +HOST = 'http://localhost/v2' + + +class TimeoutWithEqual(urllib3.Timeout): + def __init__(self, *arg, **kwargs): + super(TimeoutWithEqual, self).__init__(*arg, **kwargs) + + def __eq__(self, other): + return self._read == other._read and self._connect == other._connect and self.total == other.total + + +class MockPoolManager(object): + def __init__(self, tc): + self._tc = tc + self._reqs = [] + + def expect_request(self, *args, **kwargs): + self._reqs.append((args, kwargs)) + + def request(self, *args, **kwargs): + self._tc.assertTrue(len(self._reqs) > 0) + r = self._reqs.pop(0) + self._tc.maxDiff = None + self._tc.assertEqual(r[0], args) + self._tc.assertEqual(r[1], kwargs) + return urllib3.HTTPResponse(status=200, body=b'test') + + +class PetApiTests(unittest.TestCase): + + def setUp(self): + config = Configuration() + config.host = HOST + config.access_token = 'ACCESS_TOKEN' + self.api_client = petstore_api.ApiClient(config) + self.pet_api = PetApi(self.api_client) + self.setUpModels() + self.setUpFiles() + + def setUpModels(self): + from petstore_api.model import category, tag + self.category = category.Category() + self.category.id = id_gen() + self.category.name = "dog" + self.tag = tag.Tag() + self.tag.id = id_gen() + self.tag.name = "python-pet-tag" + self.pet = pet.Pet(name="hello kity", photo_urls=["http://foo.bar.com/1", "http://foo.bar.com/2"]) + self.pet.id = id_gen() + self.pet.status = "sold" + self.pet.category = self.category + self.pet.tags = [self.tag] + + def setUpFiles(self): + self.test_file_dir = os.path.join(os.path.dirname(__file__), "..", "testfiles") + self.test_file_dir = os.path.realpath(self.test_file_dir) + + def test_preload_content_flag(self): + self.pet_api.add_pet(self.pet) + + resp = self.pet_api.find_pets_by_status(status=[self.pet.status], _preload_content=False) + + # return response should at least have read and close methods. + self.assertTrue(hasattr(resp, 'read')) + self.assertTrue(hasattr(resp, 'close')) + + # Also we need to make sure we can release the connection to a pool (if exists) when we are done with it. + self.assertTrue(hasattr(resp, 'release_conn')) + + # Right now, the client returns urllib3.HTTPResponse. If that changed in future, it is probably a breaking + # change, however supporting above methods should be enough for most usecases. Remove this test case if + # we followed the breaking change procedure for python client (e.g. increasing major version). + self.assertTrue(resp.__class__, 'urllib3.response.HTTPResponse') + + resp.close() + resp.release_conn() + + def test_config(self): + config = Configuration(host=HOST) + self.assertIsNotNone(config.get_host_settings()) + self.assertEqual(config.get_basic_auth_token(), + urllib3.util.make_headers(basic_auth=":").get('authorization')) + # No authentication scheme has been configured at this point, so auth_settings() + # should return an empty list. + self.assertEqual(len(config.auth_settings()), 0) + # Configure OAuth2 access token and verify the auth_settings have OAuth2 parameters. + config.access_token = 'MY-ACCESS_TOKEN' + self.assertEqual(len(config.auth_settings()), 1) + self.assertIn("petstore_auth", config.auth_settings().keys()) + config.username = "user" + config.password = "password" + self.assertEqual( + config.get_basic_auth_token(), + urllib3.util.make_headers(basic_auth="user:password").get('authorization')) + self.assertEqual(len(config.auth_settings()), 2) + self.assertIn("petstore_auth", config.auth_settings().keys()) + self.assertIn("http_basic_test", config.auth_settings().keys()) + config.username = None + config.password = None + self.assertEqual(len(config.auth_settings()), 1) + self.assertIn("petstore_auth", config.auth_settings().keys()) + + def test_timeout(self): + mock_pool = MockPoolManager(self) + self.api_client.rest_client.pool_manager = mock_pool + + mock_pool.expect_request('POST', 'http://localhost/v2/pet', + body=json.dumps(self.api_client.sanitize_for_serialization(self.pet)), + headers={'Content-Type': 'application/json', + 'Authorization': 'Bearer ACCESS_TOKEN', + 'User-Agent': 'OpenAPI-Generator/1.0.0/python'}, + preload_content=True, timeout=TimeoutWithEqual(total=5)) + mock_pool.expect_request('POST', 'http://localhost/v2/pet', + body=json.dumps(self.api_client.sanitize_for_serialization(self.pet)), + headers={'Content-Type': 'application/json', + 'Authorization': 'Bearer ACCESS_TOKEN', + 'User-Agent': 'OpenAPI-Generator/1.0.0/python'}, + preload_content=True, timeout=TimeoutWithEqual(connect=1, read=2)) + + self.pet_api.add_pet(self.pet, _request_timeout=5) + self.pet_api.add_pet(self.pet, _request_timeout=(1, 2)) + + def test_separate_default_client_instances(self): + pet_api = PetApi() + pet_api2 = PetApi() + self.assertNotEqual(pet_api.api_client, pet_api2.api_client) + + pet_api.api_client.user_agent = 'api client 3' + pet_api2.api_client.user_agent = 'api client 4' + + self.assertNotEqual(pet_api.api_client.user_agent, pet_api2.api_client.user_agent) + + def test_separate_default_config_instances(self): + pet_api = PetApi() + pet_api2 = PetApi() + self.assertNotEqual(pet_api.api_client.configuration, pet_api2.api_client.configuration) + + pet_api.api_client.configuration.host = 'somehost' + pet_api2.api_client.configuration.host = 'someotherhost' + self.assertNotEqual(pet_api.api_client.configuration.host, pet_api2.api_client.configuration.host) + + def test_async_request(self): + thread = self.pet_api.add_pet(self.pet, async_req=True) + response = thread.get() + self.assertIsNone(response) + + thread = self.pet_api.get_pet_by_id(self.pet.id, async_req=True) + result = thread.get() + self.assertIsInstance(result, pet.Pet) + + def test_async_with_result(self): + self.pet_api.add_pet(self.pet, async_req=False) + + thread = self.pet_api.get_pet_by_id(self.pet.id, async_req=True) + thread2 = self.pet_api.get_pet_by_id(self.pet.id, async_req=True) + + response = thread.get() + response2 = thread2.get() + + self.assertEqual(response.id, self.pet.id) + self.assertIsNotNone(response2.id, self.pet.id) + + def test_async_with_http_info(self): + self.pet_api.add_pet(self.pet) + + thread = self.pet_api.get_pet_by_id(self.pet.id, async_req=True, + _return_http_data_only=False) + data, status, headers = thread.get() + + self.assertIsInstance(data, pet.Pet) + self.assertEqual(status, 200) + + def test_async_exception(self): + self.pet_api.add_pet(self.pet) + + thread = self.pet_api.get_pet_by_id(-9999999999999, async_req=True) + + exception = None + try: + thread.get() + except ApiException as e: + exception = e + + self.assertIsInstance(exception, ApiException) + self.assertEqual(exception.status, 404) + + def test_add_pet_and_get_pet_by_id(self): + self.pet_api.add_pet(self.pet) + + fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id) + self.assertIsNotNone(fetched) + self.assertEqual(self.pet.id, fetched.id) + self.assertIsNotNone(fetched.category) + self.assertEqual(self.pet.category.name, fetched.category.name) + + def test_add_pet_and_get_pet_by_id_with_http_info(self): + self.pet_api.add_pet(self.pet) + + fetched = self.pet_api.get_pet_by_id( + pet_id=self.pet.id, + _return_http_data_only=False + ) + self.assertIsNotNone(fetched) + self.assertEqual(self.pet.id, fetched[0].id) + self.assertIsNotNone(fetched[0].category) + self.assertEqual(self.pet.category.name, fetched[0].category.name) + + def test_update_pet(self): + self.pet.name = "hello kity with updated" + self.pet_api.update_pet(self.pet) + + fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id) + self.assertIsNotNone(fetched) + self.assertEqual(self.pet.id, fetched.id) + self.assertEqual(self.pet.name, fetched.name) + self.assertIsNotNone(fetched.category) + self.assertEqual(fetched.category.name, self.pet.category.name) + + def test_find_pets_by_status(self): + self.pet_api.add_pet(self.pet) + + self.assertIn( + self.pet.id, + list(map(lambda x: getattr(x, 'id'), self.pet_api.find_pets_by_status(status=[self.pet.status]))) + ) + + def test_find_pets_by_tags(self): + self.pet_api.add_pet(self.pet) + + self.assertIn( + self.pet.id, + list(map(lambda x: getattr(x, 'id'), self.pet_api.find_pets_by_tags(tags=[self.tag.name]))) + ) + + def test_update_pet_with_form(self): + self.pet_api.add_pet(self.pet) + + name = "hello kity with form updated" + status = "pending" + self.pet_api.update_pet_with_form(pet_id=self.pet.id, name=name, status=status) + + fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id) + self.assertEqual(self.pet.id, fetched.id) + self.assertEqual(name, fetched.name) + self.assertEqual(status, fetched.status) + + def test_upload_file(self): + # upload file with form parameter + file_path1 = os.path.join(self.test_file_dir, "1px_pic1.png") + file_path2 = os.path.join(self.test_file_dir, "1px_pic2.png") + try: + file = open(file_path1, "rb") + additional_metadata = "special" + self.pet_api.upload_file( + pet_id=self.pet.id, + additional_metadata=additional_metadata, + file=file + ) + except ApiException as e: + self.fail("upload_file() raised {0} unexpectedly".format(type(e))) + finally: + file.close() + + # upload only one file + try: + file = open(file_path1, "rb") + self.pet_api.upload_file(pet_id=self.pet.id, file=file) + except ApiException as e: + self.fail("upload_file() raised {0} unexpectedly".format(type(e))) + finally: + file.close() + + # upload multiple files + HTTPResponse = namedtuple( + 'urllib3_response_HTTPResponse', + ['status', 'reason', 'data', 'getheaders', 'getheader'] + ) + headers = {} + def get_headers(): + return headers + def get_header(name, default=None): + return headers.get(name, default) + api_respponse = { + 'code': 200, + 'type': 'blah', + 'message': 'file upload succeeded' + } + http_response = HTTPResponse( + status=200, + reason='OK', + data=json.dumps(api_respponse).encode('utf-8'), + getheaders=get_headers, + getheader=get_header + ) + mock_response = RESTResponse(http_response) + try: + file1 = open(file_path1, "rb") + file2 = open(file_path2, "rb") + with patch.object(RESTClientObject, 'request') as mock_method: + mock_method.return_value = mock_response + res = self.pet_api.upload_file( + pet_id=684696917, files=[file1, file2]) + mock_method.assert_called_with( + 'POST', + 'http://localhost/v2/pet/684696917/uploadImage', + _preload_content=True, + _request_timeout=None, + body=None, + headers={ + 'Accept': 'application/json', + 'Content-Type': 'multipart/form-data', + 'User-Agent': 'OpenAPI-Generator/1.0.0/python', + 'Authorization': 'Bearer ACCESS_TOKEN' + }, + post_params=[ + ('files', ('1px_pic1.png', b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x00\x00\x00\x00:~\x9bU\x00\x00\x00\nIDATx\x9cc\xfa\x0f\x00\x01\x05\x01\x02\xcf\xa0.\xcd\x00\x00\x00\x00IEND\xaeB`\x82', 'image/png')), + ('files', ('1px_pic2.png', b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x00\x00\x00\x00:~\x9bU\x00\x00\x00\nIDATx\x9cc\xfa\x0f\x00\x01\x05\x01\x02\xcf\xa0.\xcd\x00\x00\x00\x00IEND\xaeB`\x82', 'image/png')) + ], + query_params=[] + ) + except ApiException as e: + self.fail("upload_file() raised {0} unexpectedly".format(type(e))) + finally: + file1.close() + file2.close() + + # passing in an array of files to when file only allows one + # raises an exceptions + try: + file = open(file_path1, "rb") + with self.assertRaises(ApiTypeError) as exc: + self.pet_api.upload_file(pet_id=self.pet.id, file=[file]) + finally: + file.close() + + # passing in a single file when an array of file is required + # raises an exception + try: + file = open(file_path1, "rb") + with self.assertRaises(ApiTypeError) as exc: + self.pet_api.upload_file(pet_id=self.pet.id, files=file) + finally: + file.close() + + # passing in a closed file raises an exception + with self.assertRaises(ApiValueError) as exc: + file = open(file_path1, "rb") + file.close() + self.pet_api.upload_file(pet_id=self.pet.id, file=file) + + + def test_delete_pet(self): + self.pet_api.add_pet(self.pet) + self.pet_api.delete_pet(pet_id=self.pet.id, api_key="special-key") + + try: + self.pet_api.get_pet_by_id(pet_id=self.pet.id) + raise Exception("expected an error") + except ApiException as e: + self.assertEqual(404, e.status) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_serialization.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_serialization.py new file mode 100644 index 000000000000..1f718ecca6b5 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_serialization.py @@ -0,0 +1,78 @@ +# coding: utf-8 + +# flake8: noqa + +""" +Run the tests. +$ pip install nose (optional) +$ cd OpenAPIPetstore-python +$ nosetests -v +""" +from collections import namedtuple +import json +import os +import time +import unittest +import datetime + +import six + +import petstore_api + +from petstore_api.exceptions import ( + ApiTypeError, + ApiKeyError, + ApiValueError, +) +from petstore_api.model import ( + enum_test, + pet, + animal, + dog, + parent_pet, + child_lizard, + category, + string_enum, + string_boolean_map, +) +from petstore_api.model_utils import ( + file_type, + model_to_dict, +) + +from petstore_api.rest import RESTResponse + +MockResponse = namedtuple('MockResponse', 'data') + +class SerializationTests(unittest.TestCase): + + def setUp(self): + self.api_client = petstore_api.ApiClient() + self.serialize = self.api_client.sanitize_for_serialization + + def test_enum_test(self): + """ serialize dict(str, Enum_Test) """ + value = ( + string_enum.StringEnum.allowed_values[('value',)]["PLACED"]) + string_enum_val = string_enum.StringEnum(value) + + source = enum_test.EnumTest( + enum_string="UPPER", + enum_string_required="lower", + enum_integer=1, + enum_number=1.1, + string_enum=string_enum_val + ) + + result = { + 'enum_test': { + "enum_string": "UPPER", + "enum_string_required": "lower", + "enum_integer": 1, + "enum_number": 1.1, + "stringEnum": "placed" + } + } + serialized = self.serialize({"enum_test": source}) + + self.assertEqual(result, serialized) diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_store_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_store_api.py new file mode 100644 index 000000000000..a7c1d5dd6670 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/test_store_api.py @@ -0,0 +1,32 @@ +# coding: utf-8 + +# flake8: noqa + +""" +Run the tests. +$ pip install nose (optional) +$ cd OpenAP/Petstore-python +$ nosetests -v +""" + +import os +import time +import unittest + +import petstore_api +from petstore_api.api.store_api import StoreApi + + +class StoreApiTests(unittest.TestCase): + + def setUp(self): + self.store_api = StoreApi() + + def tearDown(self): + # sleep 1 sec between two every 2 tests + time.sleep(1) + + def test_get_inventory(self): + data = self.store_api.get_inventory() + self.assertIsNotNone(data) + self.assertTrue(isinstance(data, dict)) diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/util.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/util.py new file mode 100644 index 000000000000..113d7dcc5478 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tests/util.py @@ -0,0 +1,8 @@ +# flake8: noqa + +import random + + +def id_gen(bits=32): + """ Returns a n-bit randomly generated int """ + return int(random.getrandbits(bits)) diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tox.ini b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tox.ini new file mode 100644 index 000000000000..8989fc3c4d96 --- /dev/null +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/tox.ini @@ -0,0 +1,9 @@ +[tox] +envlist = py3 + +[testenv] +deps=-r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt + +commands= + pytest --cov=petstore_api diff --git a/samples/client/petstore/ruby-faraday/.openapi-generator/VERSION b/samples/client/petstore/ruby-faraday/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/ruby-faraday/.openapi-generator/VERSION +++ b/samples/client/petstore/ruby-faraday/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/ruby-faraday/README.md b/samples/client/petstore/ruby-faraday/README.md index f7d8816e8ca8..e4cc57adb514 100644 --- a/samples/client/petstore/ruby-faraday/README.md +++ b/samples/client/petstore/ruby-faraday/README.md @@ -84,6 +84,7 @@ Class | Method | HTTP request | Description *Petstore::FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | *Petstore::FakeApi* | [**fake_outer_string_serialize**](docs/FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | *Petstore::FakeApi* | [**fake_property_enum_integer_serialize**](docs/FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +*Petstore::FakeApi* | [**test_body_with_binary**](docs/FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | *Petstore::FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | *Petstore::FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | *Petstore::FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model diff --git a/samples/client/petstore/ruby-faraday/docs/FakeApi.md b/samples/client/petstore/ruby-faraday/docs/FakeApi.md index ce74242565c9..696f5ff48203 100644 --- a/samples/client/petstore/ruby-faraday/docs/FakeApi.md +++ b/samples/client/petstore/ruby-faraday/docs/FakeApi.md @@ -11,6 +11,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fake_outer_number_serialize**](FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | | | [**fake_outer_string_serialize**](FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | | | [**fake_property_enum_integer_serialize**](FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | | +| [**test_body_with_binary**](FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | | | [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | | | [**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | | | [**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model | @@ -479,13 +480,76 @@ No authorization required - **Accept**: */* +## test_body_with_binary + +> test_body_with_binary(body) + + + +For this test, the body has to be a binary file. + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +body = File.new('/path/to/some/file') # File | image to upload + +begin + + api_instance.test_body_with_binary(body) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_body_with_binary: #{e}" +end +``` + +#### Using the test_body_with_binary_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> test_body_with_binary_with_http_info(body) + +```ruby +begin + + data, status_code, headers = api_instance.test_body_with_binary_with_http_info(body) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_body_with_binary_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **body** | **File** | image to upload | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: image/png +- **Accept**: Not defined + + ## test_body_with_file_schema > test_body_with_file_schema(file_schema_test_class) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Examples diff --git a/samples/client/petstore/ruby-faraday/lib/petstore.rb b/samples/client/petstore/ruby-faraday/lib/petstore.rb index f9a198e1b3ae..2634c4d132ec 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api/another_fake_api.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api/another_fake_api.rb index 31f396bc6fff..6145ff7431c0 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api/another_fake_api.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api/another_fake_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api/default_api.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api/default_api.rb index 8ddf6417a454..9d3dc978d094 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api/default_api.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api/default_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api/fake_api.rb index cade25d18cea..50a336275d71 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api/fake_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end @@ -440,7 +440,64 @@ def fake_property_enum_integer_serialize_with_http_info(outer_object_with_enum_p return data, status_code, headers end - # For this test, the body for this request much reference a schema named `File`. + # For this test, the body has to be a binary file. + # @param body [File] image to upload + # @param [Hash] opts the optional parameters + # @return [nil] + def test_body_with_binary(body, opts = {}) + test_body_with_binary_with_http_info(body, opts) + nil + end + + # For this test, the body has to be a binary file. + # @param body [File] image to upload + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def test_body_with_binary_with_http_info(body, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_body_with_binary ...' + end + # resource path + local_var_path = '/fake/body-with-binary' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + header_params['Content-Type'] = @api_client.select_header_content_type(['image/png']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(body) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.test_body_with_binary", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:PUT, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_body_with_binary\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # For this test, the body for this request must reference a schema named `File`. # @param file_schema_test_class [FileSchemaTestClass] # @param [Hash] opts the optional parameters # @return [nil] @@ -449,7 +506,7 @@ def test_body_with_file_schema(file_schema_test_class, opts = {}) nil end - # For this test, the body for this request much reference a schema named `File`. + # For this test, the body for this request must reference a schema named `File`. # @param file_schema_test_class [FileSchemaTestClass] # @param [Hash] opts the optional parameters # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers @@ -1179,7 +1236,7 @@ def test_query_parameter_collection_format_with_http_info(pipe, ioutil, http, ur # query parameters query_params = opts[:query_params] || {} - query_params[:'pipe'] = @api_client.build_collection_param(pipe, :multi) + query_params[:'pipe'] = @api_client.build_collection_param(pipe, :pipes) query_params[:'ioutil'] = @api_client.build_collection_param(ioutil, :csv) query_params[:'http'] = @api_client.build_collection_param(http, :ssv) query_params[:'url'] = @api_client.build_collection_param(url, :csv) diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api/fake_classname_tags123_api.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api/fake_classname_tags123_api.rb index 2e79f8990631..fd68ab477734 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api/fake_classname_tags123_api.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api/fake_classname_tags123_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api/pet_api.rb index 5603a1a75a13..4754887194d1 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api/pet_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api/store_api.rb index 3660dee4ed96..3851c7b2ab6f 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api/store_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api/user_api.rb index dfa6e8b57d35..73bca582e269 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api/user_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api_client.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api_client.rb index 2fb744160be6..c50394c22f26 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api_client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api_error.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api_error.rb index 4d782c07943e..124c188d8d8d 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api_error.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api_error.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb b/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb index 7baf9de86426..9b2851dfaa08 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/additional_properties_class.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/additional_properties_class.rb index 523e041be8f3..01b2eb58d7f3 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/additional_properties_class.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/additional_properties_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/animal.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/animal.rb index eba827e1c697..8e737d582c84 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/animal.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/animal.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/api_response.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/api_response.rb index 203ffa7b52be..2bbfba46c3f0 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/api_response.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/api_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/array_of_array_of_number_only.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/array_of_array_of_number_only.rb index 00aeb8af61b2..057c5b787b60 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/array_of_array_of_number_only.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/array_of_array_of_number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/array_of_number_only.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/array_of_number_only.rb index ef39e5f498f5..9585dd80a6ba 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/array_of_number_only.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/array_of_number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/array_test.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/array_test.rb index a6ffbc5a783b..583ea424607c 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/array_test.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/array_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/capitalization.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/capitalization.rb index c27768d78d07..0d698fee60fd 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/capitalization.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/capitalization.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/cat.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/cat.rb index 56219265c257..984aee85a084 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/cat.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/cat.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/cat_all_of.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/cat_all_of.rb index c9277722620b..cca5e6828b35 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/cat_all_of.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/cat_all_of.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/category.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/category.rb index 622bc6faac92..3bdce1b83f3a 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/category.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/category.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/class_model.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/class_model.rb index 8fd250a74181..d185566668f1 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/class_model.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/class_model.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/client.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/client.rb index 124b4b82ed90..7f6d0947223d 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/client.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/dog.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/dog.rb index 82ba33c1257a..9874575bd0bb 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/dog.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/dog.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/dog_all_of.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/dog_all_of.rb index 3fadc430f4c8..62839a7cb131 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/dog_all_of.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/dog_all_of.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_arrays.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_arrays.rb index 29b4ca8c98d8..e281d2ddc469 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_arrays.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_arrays.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_class.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_class.rb index 4ecaa5b59314..6c44023fb2b2 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_class.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_test.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_test.rb index 28a3d7e15fca..d3416f495acf 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_test.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/file.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/file.rb index 6c94412ae1b2..76ee99558105 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/file.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/file.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/file_schema_test_class.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/file_schema_test_class.rb index b0766bb8b405..c07f1a43ea08 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/file_schema_test_class.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/file_schema_test_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/foo.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/foo.rb index f7912997098a..54eb0760f5e8 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/foo.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/foo.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/format_test.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/format_test.rb index dadf1b830250..0c57d78ac252 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/format_test.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/format_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/has_only_read_only.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/has_only_read_only.rb index efd7d13f25f2..3fe1977ba7d3 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/has_only_read_only.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/has_only_read_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/health_check_result.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/health_check_result.rb index a6ef81651a14..aebfc27084e6 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/health_check_result.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/health_check_result.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/inline_response_default.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/inline_response_default.rb index 7e16c669206f..2eb6b88a2242 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/inline_response_default.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/inline_response_default.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/list.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/list.rb index 7c7f31a3fbdb..f04fceff81b6 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/list.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/list.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/map_test.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/map_test.rb index 74b5bfe8f086..552d9ae330ac 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/map_test.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/map_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/mixed_properties_and_additional_properties_class.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/mixed_properties_and_additional_properties_class.rb index 142e6863ab89..bf90d3cd06f7 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/mixed_properties_and_additional_properties_class.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/mixed_properties_and_additional_properties_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/model200_response.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/model200_response.rb index ec5c0050ba37..bad3bfcce3a3 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/model200_response.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/model200_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/model_return.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/model_return.rb index 9614b6d779d8..d33b1bf1dac4 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/model_return.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/model_return.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/name.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/name.rb index 56e27726a180..6a1777a426da 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/name.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/name.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/nullable_class.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/nullable_class.rb index 2e73715f8815..3d0d81a74442 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/nullable_class.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/nullable_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/number_only.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/number_only.rb index ed136aee1a5d..7359f1b1115b 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/number_only.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/order.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/order.rb index fed40c355d49..6778c4b97fb3 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/order.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/order.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_composite.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_composite.rb index 06989683169e..b6d4bd88ace7 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_composite.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_composite.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum.rb index 871c119cf872..92a7aac382b7 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_default_value.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_default_value.rb index 0da84d9c8908..7097f7d9fb95 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_default_value.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_default_value.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer.rb index 7d81f819acf4..30c26017cc75 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer_default_value.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer_default_value.rb index 7b42c137e3f0..a95eab63a6ee 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer_default_value.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer_default_value.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_object_with_enum_property.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_object_with_enum_property.rb index 142aea914503..6950269d9971 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_object_with_enum_property.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_object_with_enum_property.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/pet.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/pet.rb index 6d28da4b86d0..c810bf54845f 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/pet.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/pet.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/read_only_first.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/read_only_first.rb index 522c0f0fbeb1..53774ce12d44 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/read_only_first.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/read_only_first.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/special_model_name.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/special_model_name.rb index 5101343d5f2e..06d53c68ff09 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/special_model_name.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/special_model_name.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/tag.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/tag.rb index 0f8faa295b43..b9a14f579744 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/tag.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/tag.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/user.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/user.rb index 7364a794f503..c1f7816f475b 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/user.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/user.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/version.rb b/samples/client/petstore/ruby-faraday/lib/petstore/version.rb index 5b0cca787bc5..ab3b0dfefbde 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/version.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/version.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/petstore.gemspec b/samples/client/petstore/ruby-faraday/petstore.gemspec index d649b5e641ab..06a7eb1a52c1 100644 --- a/samples/client/petstore/ruby-faraday/petstore.gemspec +++ b/samples/client/petstore/ruby-faraday/petstore.gemspec @@ -8,7 +8,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/spec/api_client_spec.rb b/samples/client/petstore/ruby-faraday/spec/api_client_spec.rb index 9d0bb4ced1da..05a5580fd4d1 100644 --- a/samples/client/petstore/ruby-faraday/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby-faraday/spec/api_client_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/spec/configuration_spec.rb b/samples/client/petstore/ruby-faraday/spec/configuration_spec.rb index 1770139baa3e..10c9510b2398 100644 --- a/samples/client/petstore/ruby-faraday/spec/configuration_spec.rb +++ b/samples/client/petstore/ruby-faraday/spec/configuration_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/spec/spec_helper.rb b/samples/client/petstore/ruby-faraday/spec/spec_helper.rb index 50cce9b05c77..86d92cda2b9f 100644 --- a/samples/client/petstore/ruby-faraday/spec/spec_helper.rb +++ b/samples/client/petstore/ruby-faraday/spec/spec_helper.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/.openapi-generator/VERSION b/samples/client/petstore/ruby/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/ruby/.openapi-generator/VERSION +++ b/samples/client/petstore/ruby/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index f7d8816e8ca8..e4cc57adb514 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -84,6 +84,7 @@ Class | Method | HTTP request | Description *Petstore::FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | *Petstore::FakeApi* | [**fake_outer_string_serialize**](docs/FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | *Petstore::FakeApi* | [**fake_property_enum_integer_serialize**](docs/FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +*Petstore::FakeApi* | [**test_body_with_binary**](docs/FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | *Petstore::FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | *Petstore::FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | *Petstore::FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model diff --git a/samples/client/petstore/ruby/docs/FakeApi.md b/samples/client/petstore/ruby/docs/FakeApi.md index ce74242565c9..696f5ff48203 100644 --- a/samples/client/petstore/ruby/docs/FakeApi.md +++ b/samples/client/petstore/ruby/docs/FakeApi.md @@ -11,6 +11,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fake_outer_number_serialize**](FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | | | [**fake_outer_string_serialize**](FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | | | [**fake_property_enum_integer_serialize**](FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | | +| [**test_body_with_binary**](FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | | | [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | | | [**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | | | [**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model | @@ -479,13 +480,76 @@ No authorization required - **Accept**: */* +## test_body_with_binary + +> test_body_with_binary(body) + + + +For this test, the body has to be a binary file. + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +body = File.new('/path/to/some/file') # File | image to upload + +begin + + api_instance.test_body_with_binary(body) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_body_with_binary: #{e}" +end +``` + +#### Using the test_body_with_binary_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> test_body_with_binary_with_http_info(body) + +```ruby +begin + + data, status_code, headers = api_instance.test_body_with_binary_with_http_info(body) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_body_with_binary_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **body** | **File** | image to upload | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: image/png +- **Accept**: Not defined + + ## test_body_with_file_schema > test_body_with_file_schema(file_schema_test_class) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Examples diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index f9a198e1b3ae..2634c4d132ec 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/api/another_fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/another_fake_api.rb index 31f396bc6fff..6145ff7431c0 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/another_fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/another_fake_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/api/default_api.rb b/samples/client/petstore/ruby/lib/petstore/api/default_api.rb index 8ddf6417a454..9d3dc978d094 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/default_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/default_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb index cade25d18cea..50a336275d71 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end @@ -440,7 +440,64 @@ def fake_property_enum_integer_serialize_with_http_info(outer_object_with_enum_p return data, status_code, headers end - # For this test, the body for this request much reference a schema named `File`. + # For this test, the body has to be a binary file. + # @param body [File] image to upload + # @param [Hash] opts the optional parameters + # @return [nil] + def test_body_with_binary(body, opts = {}) + test_body_with_binary_with_http_info(body, opts) + nil + end + + # For this test, the body has to be a binary file. + # @param body [File] image to upload + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def test_body_with_binary_with_http_info(body, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_body_with_binary ...' + end + # resource path + local_var_path = '/fake/body-with-binary' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + header_params['Content-Type'] = @api_client.select_header_content_type(['image/png']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(body) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.test_body_with_binary", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:PUT, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_body_with_binary\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # For this test, the body for this request must reference a schema named `File`. # @param file_schema_test_class [FileSchemaTestClass] # @param [Hash] opts the optional parameters # @return [nil] @@ -449,7 +506,7 @@ def test_body_with_file_schema(file_schema_test_class, opts = {}) nil end - # For this test, the body for this request much reference a schema named `File`. + # For this test, the body for this request must reference a schema named `File`. # @param file_schema_test_class [FileSchemaTestClass] # @param [Hash] opts the optional parameters # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers @@ -1179,7 +1236,7 @@ def test_query_parameter_collection_format_with_http_info(pipe, ioutil, http, ur # query parameters query_params = opts[:query_params] || {} - query_params[:'pipe'] = @api_client.build_collection_param(pipe, :multi) + query_params[:'pipe'] = @api_client.build_collection_param(pipe, :pipes) query_params[:'ioutil'] = @api_client.build_collection_param(ioutil, :csv) query_params[:'http'] = @api_client.build_collection_param(http, :ssv) query_params[:'url'] = @api_client.build_collection_param(url, :csv) diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_classname_tags123_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_classname_tags123_api.rb index 2e79f8990631..fd68ab477734 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_classname_tags123_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_classname_tags123_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index 46fccf778e92..13b4b66578da 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index aaab20af2a47..df456319b41b 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index b42a3b3a7677..879e9eb4ad6a 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index d5cf46fd74ca..3a1bf4bd35d3 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/api_error.rb b/samples/client/petstore/ruby/lib/petstore/api_error.rb index 4d782c07943e..124c188d8d8d 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_error.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_error.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index 1bb52c50be18..cc5e1929d674 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb b/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb index 523e041be8f3..01b2eb58d7f3 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/animal.rb b/samples/client/petstore/ruby/lib/petstore/models/animal.rb index eba827e1c697..8e737d582c84 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/animal.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/animal.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/api_response.rb b/samples/client/petstore/ruby/lib/petstore/models/api_response.rb index 203ffa7b52be..2bbfba46c3f0 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/api_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/api_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb index 00aeb8af61b2..057c5b787b60 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb index ef39e5f498f5..9585dd80a6ba 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_test.rb b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb index a6ffbc5a783b..583ea424607c 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb b/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb index c27768d78d07..0d698fee60fd 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/cat.rb b/samples/client/petstore/ruby/lib/petstore/models/cat.rb index 56219265c257..984aee85a084 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/cat.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/cat.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/cat_all_of.rb b/samples/client/petstore/ruby/lib/petstore/models/cat_all_of.rb index c9277722620b..cca5e6828b35 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/cat_all_of.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/cat_all_of.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/category.rb b/samples/client/petstore/ruby/lib/petstore/models/category.rb index 622bc6faac92..3bdce1b83f3a 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/category.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/category.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/class_model.rb b/samples/client/petstore/ruby/lib/petstore/models/class_model.rb index 8fd250a74181..d185566668f1 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/class_model.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/class_model.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/client.rb b/samples/client/petstore/ruby/lib/petstore/models/client.rb index 124b4b82ed90..7f6d0947223d 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/client.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/dog.rb b/samples/client/petstore/ruby/lib/petstore/models/dog.rb index 82ba33c1257a..9874575bd0bb 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/dog.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/dog.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/dog_all_of.rb b/samples/client/petstore/ruby/lib/petstore/models/dog_all_of.rb index 3fadc430f4c8..62839a7cb131 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/dog_all_of.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/dog_all_of.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb index 29b4ca8c98d8..e281d2ddc469 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb index 4ecaa5b59314..6c44023fb2b2 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb index 28a3d7e15fca..d3416f495acf 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/file.rb b/samples/client/petstore/ruby/lib/petstore/models/file.rb index 6c94412ae1b2..76ee99558105 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/file.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/file.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/file_schema_test_class.rb b/samples/client/petstore/ruby/lib/petstore/models/file_schema_test_class.rb index b0766bb8b405..c07f1a43ea08 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/file_schema_test_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/file_schema_test_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/foo.rb b/samples/client/petstore/ruby/lib/petstore/models/foo.rb index f7912997098a..54eb0760f5e8 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/foo.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/foo.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb index dadf1b830250..0c57d78ac252 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb b/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb index efd7d13f25f2..3fe1977ba7d3 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/health_check_result.rb b/samples/client/petstore/ruby/lib/petstore/models/health_check_result.rb index a6ef81651a14..aebfc27084e6 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/health_check_result.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/health_check_result.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/inline_response_default.rb b/samples/client/petstore/ruby/lib/petstore/models/inline_response_default.rb index 7e16c669206f..2eb6b88a2242 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/inline_response_default.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/inline_response_default.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/list.rb b/samples/client/petstore/ruby/lib/petstore/models/list.rb index 7c7f31a3fbdb..f04fceff81b6 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/list.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/list.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/map_test.rb b/samples/client/petstore/ruby/lib/petstore/models/map_test.rb index 74b5bfe8f086..552d9ae330ac 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/map_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/map_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb b/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb index 142e6863ab89..bf90d3cd06f7 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/model200_response.rb b/samples/client/petstore/ruby/lib/petstore/models/model200_response.rb index ec5c0050ba37..bad3bfcce3a3 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/model200_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/model200_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/model_return.rb b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb index 9614b6d779d8..d33b1bf1dac4 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/model_return.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/name.rb b/samples/client/petstore/ruby/lib/petstore/models/name.rb index 56e27726a180..6a1777a426da 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/name.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/nullable_class.rb b/samples/client/petstore/ruby/lib/petstore/models/nullable_class.rb index 2e73715f8815..3d0d81a74442 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/nullable_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/nullable_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/number_only.rb index ed136aee1a5d..7359f1b1115b 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/order.rb b/samples/client/petstore/ruby/lib/petstore/models/order.rb index fed40c355d49..6778c4b97fb3 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/order.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/order.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_composite.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_composite.rb index 06989683169e..b6d4bd88ace7 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/outer_composite.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_composite.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb index 871c119cf872..92a7aac382b7 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_default_value.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_default_value.rb index 0da84d9c8908..7097f7d9fb95 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_default_value.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_default_value.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer.rb index 7d81f819acf4..30c26017cc75 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer_default_value.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer_default_value.rb index 7b42c137e3f0..a95eab63a6ee 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer_default_value.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer_default_value.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_object_with_enum_property.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_object_with_enum_property.rb index 142aea914503..6950269d9971 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/outer_object_with_enum_property.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_object_with_enum_property.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/pet.rb b/samples/client/petstore/ruby/lib/petstore/models/pet.rb index 6d28da4b86d0..c810bf54845f 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/pet.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/pet.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb b/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb index 522c0f0fbeb1..53774ce12d44 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb b/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb index 5101343d5f2e..06d53c68ff09 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/tag.rb b/samples/client/petstore/ruby/lib/petstore/models/tag.rb index 0f8faa295b43..b9a14f579744 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/tag.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/tag.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/user.rb b/samples/client/petstore/ruby/lib/petstore/models/user.rb index 7364a794f503..c1f7816f475b 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/user.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/user.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/version.rb b/samples/client/petstore/ruby/lib/petstore/version.rb index 5b0cca787bc5..ab3b0dfefbde 100644 --- a/samples/client/petstore/ruby/lib/petstore/version.rb +++ b/samples/client/petstore/ruby/lib/petstore/version.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/petstore.gemspec b/samples/client/petstore/ruby/petstore.gemspec index a3b6e8e06944..fca963ec152c 100644 --- a/samples/client/petstore/ruby/petstore.gemspec +++ b/samples/client/petstore/ruby/petstore.gemspec @@ -8,7 +8,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/spec/api_client_spec.rb b/samples/client/petstore/ruby/spec/api_client_spec.rb index 45a5468ae6e5..663b8081006c 100644 --- a/samples/client/petstore/ruby/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby/spec/api_client_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/spec/configuration_spec.rb b/samples/client/petstore/ruby/spec/configuration_spec.rb index 1770139baa3e..10c9510b2398 100644 --- a/samples/client/petstore/ruby/spec/configuration_spec.rb +++ b/samples/client/petstore/ruby/spec/configuration_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index 50cce9b05c77..86d92cda2b9f 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/rust/hyper/petstore/.openapi-generator/VERSION b/samples/client/petstore/rust/hyper/petstore/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/rust/hyper/petstore/.openapi-generator/VERSION +++ b/samples/client/petstore/rust/hyper/petstore/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/rust/reqwest/petstore-async/.openapi-generator/VERSION b/samples/client/petstore/rust/reqwest/petstore-async/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/.openapi-generator/VERSION +++ b/samples/client/petstore/rust/reqwest/petstore-async/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/VERSION b/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/VERSION +++ b/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/scala-akka/.openapi-generator/FILES b/samples/client/petstore/scala-akka/.openapi-generator/FILES index 8d22043b5a91..2cd9737cf183 100644 --- a/samples/client/petstore/scala-akka/.openapi-generator/FILES +++ b/samples/client/petstore/scala-akka/.openapi-generator/FILES @@ -1,5 +1,6 @@ README.md build.sbt +project/build.properties src/main/resources/reference.conf src/main/scala/org/openapitools/client/api/EnumsSerializers.scala src/main/scala/org/openapitools/client/api/PetApi.scala diff --git a/samples/client/petstore/scala-akka/.openapi-generator/VERSION b/samples/client/petstore/scala-akka/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/scala-akka/.openapi-generator/VERSION +++ b/samples/client/petstore/scala-akka/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/scala-akka/build.sbt b/samples/client/petstore/scala-akka/build.sbt index 038757790a5a..e9915b07f85f 100644 --- a/samples/client/petstore/scala-akka/build.sbt +++ b/samples/client/petstore/scala-akka/build.sbt @@ -1,19 +1,23 @@ version := "1.0.0" name := "scala-akka-petstore-client" organization := "org.openapitools" -scalaVersion := "2.12.8" + +scalaVersion := "2.12.13" +crossScalaVersions := Seq(scalaVersion.value, "2.13.4") + libraryDependencies ++= Seq( - "com.typesafe" % "config" % "1.3.3", - "com.typesafe.akka" %% "akka-actor" % "2.5.21", - "com.typesafe.akka" %% "akka-stream" % "2.5.21", - "com.typesafe.akka" %% "akka-http" % "10.1.7", - "org.json4s" %% "json4s-jackson" % "3.6.5", - "org.json4s" %% "json4s-ext" % "3.6.5", - "de.heikoseeberger" %% "akka-http-json4s" % "1.25.2", + "com.typesafe" % "config" % "1.4.1", + "com.typesafe.akka" %% "akka-actor" % "2.6.12", + "com.typesafe.akka" %% "akka-stream" % "2.6.12", + "com.typesafe.akka" %% "akka-http" % "10.2.3", + "org.json4s" %% "json4s-jackson" % "3.6.7", + "org.json4s" %% "json4s-ext" % "3.6.7", + "de.heikoseeberger" %% "akka-http-json4s" % "1.27.0", + "org.scala-lang.modules" %% "scala-collection-compat" % "2.4.1", // test dependencies - "org.scalatest" %% "scalatest" % "3.0.5" % "test", - "junit" % "junit" % "4.13.1" % "test" + "org.scalatest" %% "scalatest" % "3.2.3" % "test", + "org.scalatestplus" %% "junit-4-13" % "3.2.3.0" % "test" ) resolvers ++= Seq(Resolver.mavenLocal) diff --git a/samples/client/petstore/scala-akka/pom.xml b/samples/client/petstore/scala-akka/pom.xml index 42e08693b641..0f93bcb372b4 100644 --- a/samples/client/petstore/scala-akka/pom.xml +++ b/samples/client/petstore/scala-akka/pom.xml @@ -15,15 +15,16 @@ UTF-8 1.8 - 2.12.8 - 3.5.3 - 3.2.11 - 2.5.21 - 10.1.7 - 1.3.3 - 1.25.2 - 4.13 - 3.0.5 + 2.12.13 + 3.6.7 + 3.6.7 + 2.6.12 + 10.2.3 + 1.4.1 + 1.27.0 + 2.4.1 + 3.2.3 + 3.2.3.0 3.3.1 @@ -70,6 +71,11 @@ akka-http-json4s_2.12 ${akka.http.json4s.version} + + org.scala-lang.modules + scala-collection-compat_2.12 + ${scala.compat.version} + @@ -79,9 +85,9 @@ test - junit - junit - ${junit.version} + org.scalatestplus + junit-4-13_2.12 + ${scala.test.plus.version} test diff --git a/samples/client/petstore/scala-akka/project/build.properties b/samples/client/petstore/scala-akka/project/build.properties new file mode 100644 index 000000000000..dc07aed85e00 --- /dev/null +++ b/samples/client/petstore/scala-akka/project/build.properties @@ -0,0 +1 @@ +sbt.version=1.3.10 \ No newline at end of file diff --git a/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiInvoker.scala b/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiInvoker.scala index d3ff4cadb8ec..fe3910967139 100644 --- a/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiInvoker.scala +++ b/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiInvoker.scala @@ -28,6 +28,7 @@ import de.heikoseeberger.akkahttpjson4s.Json4sSupport import org.json4s._ import org.json4s.jackson.JsonMethods._ import org.json4s.jackson.Serialization +import scala.collection.compat._ import scala.collection.immutable import scala.concurrent.{ ExecutionContext, ExecutionContextExecutor, Future } @@ -96,7 +97,7 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC private val http = Http() - val CompressionFilter: HttpMessage ⇒ Boolean = (msg: HttpMessage) => + val CompressionFilter: HttpMessage => Boolean = (msg: HttpMessage) => Seq( { _: HttpMessage => settings.compressionEnabled }, Encoder.DefaultFilter, @@ -125,7 +126,7 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC private def headers(headers: Map[String, Any]): immutable.Seq[HttpHeader] = headers.asFormattedParams .map { case (name, value) => RawHeader(name, value.toString) } - .to[immutable.Seq] + .to(immutable.Seq) private def bodyPart(name: String, value: Any): BodyPart = { @@ -157,9 +158,9 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC case MediaTypes.`multipart/form-data` => Multipart.FormData(Source(params.toList.map { case (name, value) => bodyPart(name, value) })) case MediaTypes.`application/x-www-form-urlencoded` => - FormData(params.mapValues(_.toString)) + FormData(params.view.mapValues(_.toString).toMap) case _: MediaType => // Default : application/x-www-form-urlencoded. - FormData(params.mapValues(_.toString)) + FormData(params.view.mapValues(_.toString).toMap) } ) } @@ -197,7 +198,9 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC params + (keyName -> key.value) case (params, _) => params }.asFormattedParams + .view .mapValues(_.toString) + .toMap .foldRight[Query](Uri.Query.Empty) { case ((name, value), acc) => acc.+:(name, value) } @@ -206,7 +209,9 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC def makeUri(r: ApiRequest[_]): Uri = { val opPath = r.operationPath.replaceAll("\\{format\\}", "json") val opPathWithParams = r.pathParams.asFormattedParams + .view .mapValues(_.toString) + .toMap .foldLeft(opPath) { case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value) } @@ -223,13 +228,13 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC http .singleRequest(request) .map { response => - val decoder: Coder with StreamDecoder = response.encoding match { - case HttpEncodings.gzip ⇒ - Gzip - case HttpEncodings.deflate ⇒ - Deflate - case HttpEncodings.identity ⇒ - NoCoding + val decoder: Decoder with Decoder = response.encoding match { + case HttpEncodings.gzip => + Coders.Gzip + case HttpEncodings.deflate => + Coders.Deflate + case HttpEncodings.identity => + Coders.NoCoding case HttpEncoding(encoding) => throw new IllegalArgumentException(s"Unsupported encoding: $encoding") } @@ -257,13 +262,13 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC request .responseForCode(response.status.intValue) match { case Some((Manifest.Unit, state: ResponseState)) => - Future(responseForState(state, Unit).asInstanceOf[ApiResponse[T]]) + Future(responseForState(state, ()).asInstanceOf[ApiResponse[T]]) case Some((manifest, state: ResponseState)) if manifest == mf => implicit val m: Unmarshaller[HttpEntity, T] = unmarshaller[T](mf, serialization, formats) Unmarshal(response.entity) .to[T] .recoverWith { - case e ⇒ throw ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), e) + case e => throw ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), e) } .map(value => responseForState(state, value)) case None | Some(_) => diff --git a/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiSettings.scala b/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiSettings.scala index 2553aeb3c875..2c02c47c7bac 100644 --- a/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiSettings.scala +++ b/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiSettings.scala @@ -13,12 +13,12 @@ package org.openapitools.client.core import java.util.concurrent.TimeUnit -import akka.actor.{ ExtendedActorSystem, Extension, ExtensionKey } +import akka.actor.{ActorSystem, ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider} import akka.http.scaladsl.model.StatusCodes.CustomStatusCode import akka.http.scaladsl.model.headers.RawHeader import com.typesafe.config.Config -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import scala.concurrent.duration.FiniteDuration class ApiSettings(config: Config) extends Extension { @@ -42,4 +42,13 @@ class ApiSettings(config: Config) extends Extension { } } -object ApiSettings extends ExtensionKey[ApiSettings] +object ApiSettings extends ExtensionId[ApiSettings] with ExtensionIdProvider { + + override def lookup = ApiSettings + + override def createExtension(system: ExtendedActorSystem): ApiSettings = + new ApiSettings(system) + + // needed to get the type right when used from Java + override def get(system: ActorSystem): ApiSettings = super.get(system) +} diff --git a/samples/client/petstore/scala-akka/src/test/scala/PetApiTest.scala b/samples/client/petstore/scala-akka/src/test/scala/PetApiTest.scala index e6229fb05f3a..48c8d4c644fd 100644 --- a/samples/client/petstore/scala-akka/src/test/scala/PetApiTest.scala +++ b/samples/client/petstore/scala-akka/src/test/scala/PetApiTest.scala @@ -5,18 +5,19 @@ import org.openapitools.client.api._ import org.openapitools.client.core.{ApiInvoker, ApiKeyValue} import org.openapitools.client.model._ import org.scalatest.Inspectors._ -import org.scalatest._ -import org.scalatest.junit.JUnitRunner +import org.scalatest.flatspec.AsyncFlatSpec +import org.scalatest.matchers.should.Matchers +import org.scalatestplus.junit.JUnitRunner @RunWith(classOf[JUnitRunner]) class PetApiTest extends AsyncFlatSpec with Matchers { - private implicit val system: ActorSystem = ActorSystem() + implicit private val system: ActorSystem = ActorSystem() behavior of "PetApi" - val api: PetApi = PetApi() - val invoker: ApiInvoker = ApiInvoker(EnumsSerializers.all) - private implicit val apiKey: ApiKeyValue = ApiKeyValue("special-key") + val api: PetApi = PetApi() + val invoker: ApiInvoker = ApiInvoker(EnumsSerializers.all) + implicit private val apiKey: ApiKeyValue = ApiKeyValue("special-key") it should "add and fetch a pet" in { val petId = 1000 @@ -34,7 +35,7 @@ class PetApiTest extends AsyncFlatSpec with Matchers { for { addResponse <- invoker.execute(addPetRequest) - response <- invoker.execute(getPetRequest) + response <- invoker.execute(getPetRequest) } yield { addResponse.code should be(200) @@ -54,7 +55,7 @@ class PetApiTest extends AsyncFlatSpec with Matchers { } it should "update a pet" in { - val petId = (Math.random()*1000000000).toLong + val petId = (Math.random() * 1000000000).toLong val createdPet = Pet( Some(petId), Some(Category(Some(1), Some("sold"))), @@ -64,12 +65,12 @@ class PetApiTest extends AsyncFlatSpec with Matchers { Some(PetEnums.Status.Available) ) - for { - createdPet <- invoker.execute(api.addPet(createdPet)) + for { + createdPet <- invoker.execute(api.addPet(createdPet)) pet: core.ApiResponse[Pet] <- invoker.execute(api.getPetById(createdPet.content.id.get)) updatedPet = pet.content.copy(status = Some(PetEnums.Status.Sold), name = "developer") updatedPetResponse: core.ApiResponse[Pet] <- invoker.execute(api.updatePet(updatedPet)) - updatedRequested: core.ApiResponse[Pet] <- invoker.execute(api.getPetById(createdPet.content.id.get)) + updatedRequested: core.ApiResponse[Pet] <- invoker.execute(api.getPetById(createdPet.content.id.get)) } yield { pet.content.name should be("programmer") pet.content.status should be(Some(PetEnums.Status.Available)) @@ -120,4 +121,3 @@ class PetApiTest extends AsyncFlatSpec with Matchers { } */ } - diff --git a/samples/client/petstore/scala-sttp/.openapi-generator/VERSION b/samples/client/petstore/scala-sttp/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/scala-sttp/.openapi-generator/VERSION +++ b/samples/client/petstore/scala-sttp/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/scala-sttp/build.sbt b/samples/client/petstore/scala-sttp/build.sbt index e7d77cdd2dba..1b13385dba10 100644 --- a/samples/client/petstore/scala-sttp/build.sbt +++ b/samples/client/petstore/scala-sttp/build.sbt @@ -2,13 +2,13 @@ version := "1.0.0" name := "scala-sttp-petstore" organization := "org.openapitools" -scalaVersion := "2.13.2" -crossScalaVersions := Seq(scalaVersion.value, "2.12.10") +scalaVersion := "2.13.5" +crossScalaVersions := Seq(scalaVersion.value, "2.12.13") libraryDependencies ++= Seq( - "com.softwaremill.sttp.client" %% "core" % "2.2.0", - "com.softwaremill.sttp.client" %% "json4s" % "2.2.0", - "org.json4s" %% "json4s-jackson" % "3.6.8" + "com.softwaremill.sttp.client" %% "core" % "2.2.9", + "com.softwaremill.sttp.client" %% "json4s" % "2.2.9", + "org.json4s" %% "json4s-jackson" % "3.6.11" ) scalacOptions := Seq( diff --git a/samples/client/petstore/scala-sttp/project/build.properties b/samples/client/petstore/scala-sttp/project/build.properties index 654fe70c42c7..e67343ae796c 100644 --- a/samples/client/petstore/scala-sttp/project/build.properties +++ b/samples/client/petstore/scala-sttp/project/build.properties @@ -1 +1 @@ -sbt.version=1.3.12 +sbt.version=1.5.0 diff --git a/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/PetApi.scala b/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/PetApi.scala index 8f541ae7bfe4..7bed7d54f339 100644 --- a/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/PetApi.scala +++ b/samples/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/PetApi.scala @@ -139,7 +139,7 @@ class PetApi(baseUrl: String) { .method(Method.POST, uri"$baseUrl/pet/${petId}") .contentType("application/x-www-form-urlencoded") .body(Map( - "name" -> name, + "name" -> name, "status" -> status )) .response(asJson[Unit]) diff --git a/samples/client/petstore/spring-cloud-async/.openapi-generator/VERSION b/samples/client/petstore/spring-cloud-async/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/spring-cloud-async/.openapi-generator/VERSION +++ b/samples/client/petstore/spring-cloud-async/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/PetApi.java b/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/PetApi.java index 99022f109cb1..6dc5d09f0c8a 100644 --- a/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/StoreApi.java b/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/StoreApi.java index e45f9f5326ad..0c181e59ee37 100644 --- a/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/UserApi.java b/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/UserApi.java index 868fe7fb79ec..f62f460d1213 100644 --- a/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-no-nullable/.openapi-generator/VERSION b/samples/client/petstore/spring-cloud-no-nullable/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/spring-cloud-no-nullable/.openapi-generator/VERSION +++ b/samples/client/petstore/spring-cloud-no-nullable/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/PetApi.java b/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/PetApi.java index 8d98ace26836..f77fdf21de24 100644 --- a/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/StoreApi.java b/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/StoreApi.java index 3fa561593964..241a82690b1e 100644 --- a/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/UserApi.java b/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/UserApi.java index 9028712a4e70..ad21d7b81059 100644 --- a/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-spring-pageable/.openapi-generator/VERSION b/samples/client/petstore/spring-cloud-spring-pageable/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/spring-cloud-spring-pageable/.openapi-generator/VERSION +++ b/samples/client/petstore/spring-cloud-spring-pageable/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/PetApi.java b/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/PetApi.java index d5038a0b69c9..8b6ead39e2c7 100644 --- a/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java b/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java index d36fad83e9d8..83d5530deb79 100644 --- a/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/UserApi.java b/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/UserApi.java index 71663c22f23d..683cff0ce64b 100644 --- a/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud/.openapi-generator/VERSION b/samples/client/petstore/spring-cloud/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/spring-cloud/.openapi-generator/VERSION +++ b/samples/client/petstore/spring-cloud/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/PetApi.java b/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/PetApi.java index 8d98ace26836..f77fdf21de24 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/StoreApi.java b/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/StoreApi.java index 3fa561593964..241a82690b1e 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/UserApi.java b/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/UserApi.java index 9028712a4e70..ad21d7b81059 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-stubs/.openapi-generator/VERSION b/samples/client/petstore/spring-stubs/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/spring-stubs/.openapi-generator/VERSION +++ b/samples/client/petstore/spring-stubs/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java index 851efbab912f..08660cdaac36 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java index 25101f4d05da..229a0ba4240a 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java index d46665a11815..e2d924590ee8 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/alamofireLibrary/Cartfile b/samples/client/petstore/swift5/alamofireLibrary/Cartfile index 7d30a6849b12..01ae988a6d4f 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/Cartfile +++ b/samples/client/petstore/swift5/alamofireLibrary/Cartfile @@ -1 +1,2 @@ github "Alamofire/Alamofire" ~> 4.9.1 +github "Flight-School/AnyCodable" ~> 0.6.0 diff --git a/samples/client/petstore/swift5/alamofireLibrary/Package.resolved b/samples/client/petstore/swift5/alamofireLibrary/Package.resolved index ca6137050ebc..4c8626cac13e 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/Package.resolved +++ b/samples/client/petstore/swift5/alamofireLibrary/Package.resolved @@ -9,6 +9,15 @@ "revision": "747c8db8d57b68d5e35275f10c92d55f982adbd4", "version": "4.9.1" } + }, + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } } ] }, diff --git a/samples/client/petstore/swift5/alamofireLibrary/Package.swift b/samples/client/petstore/swift5/alamofireLibrary/Package.swift index 1bf8d9cfdd26..153013e9e935 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/Package.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.0 +// swift-tools-version:5.1 import PackageDescription @@ -19,6 +19,7 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.6.0")), .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.1"), ], targets: [ @@ -26,7 +27,7 @@ let package = Package( // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "PetstoreClient", - dependencies: ["Alamofire", ], + dependencies: ["AnyCodable", "Alamofire", ], path: "PetstoreClient/Classes" ), ] diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient.podspec b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient.podspec index 00711c531254..dbe8000cc21b 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient.podspec @@ -12,4 +12,5 @@ Pod::Spec.new do |s| s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' s.dependency 'Alamofire', '~> 4.9.1' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.0' end diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index c6beeedf9a4b..85346c2896e9 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,7 +6,10 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] @@ -30,7 +33,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -39,7 +42,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -49,7 +52,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 24b0015a270d..542fb6f69ba8 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -15,7 +15,7 @@ open class AnotherFakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -35,10 +35,10 @@ open class AnotherFakeAPI { */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -46,9 +46,9 @@ open class AnotherFakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 58c4b8a093ce..9b75edc92ee6 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -14,7 +14,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -33,10 +33,10 @@ open class FakeAPI { */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -44,9 +44,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -55,7 +55,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -74,10 +74,10 @@ open class FakeAPI { */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -85,9 +85,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -96,7 +96,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -115,10 +115,10 @@ open class FakeAPI { */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -126,9 +126,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -137,7 +137,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -156,10 +156,10 @@ open class FakeAPI { */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -167,9 +167,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -178,7 +178,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -197,10 +197,10 @@ open class FakeAPI { */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -208,9 +208,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -220,7 +220,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -239,11 +239,11 @@ open class FakeAPI { */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) @@ -253,9 +253,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -265,7 +265,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -285,10 +285,10 @@ open class FakeAPI { */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -296,9 +296,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -321,7 +321,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -357,7 +357,7 @@ open class FakeAPI { */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), @@ -378,7 +378,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -386,9 +386,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -472,7 +472,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -499,7 +499,7 @@ open class FakeAPI { */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), @@ -508,8 +508,8 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), @@ -524,9 +524,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -541,7 +541,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -566,11 +566,11 @@ open class FakeAPI { */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), @@ -584,9 +584,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -596,7 +596,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -615,10 +615,10 @@ open class FakeAPI { */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -626,9 +626,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -639,7 +639,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -659,7 +659,7 @@ open class FakeAPI { */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), @@ -668,7 +668,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -676,9 +676,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index fb3bb8ce00a7..fd7d845d3406 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -15,7 +15,7 @@ open class FakeClassnameTags123API { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -38,10 +38,10 @@ open class FakeClassnameTags123API { */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ open class FakeClassnameTags123API { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 5cd3629127bf..d7d5bdfa2eaa 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -15,7 +15,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -37,10 +37,10 @@ open class PetAPI { */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -48,9 +48,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -61,7 +61,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -87,10 +87,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), @@ -98,9 +98,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -119,7 +119,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -142,11 +142,11 @@ open class PetAPI { */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) @@ -156,9 +156,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -169,7 +169,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -193,11 +193,11 @@ open class PetAPI { @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) @@ -207,9 +207,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -219,7 +219,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -245,10 +245,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -256,9 +256,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -268,7 +268,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -290,10 +290,10 @@ open class PetAPI { */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -301,9 +301,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -315,7 +315,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -342,7 +342,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), @@ -351,7 +351,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -359,9 +359,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -373,7 +373,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -400,7 +400,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), @@ -409,7 +409,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -417,9 +417,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -431,7 +431,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -458,7 +458,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), @@ -467,7 +467,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -475,9 +475,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 95adcc200ae0..c80d4286b536 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -15,7 +15,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -38,10 +38,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -60,7 +60,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -82,10 +82,10 @@ open class StoreAPI { */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -93,9 +93,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -105,7 +105,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -128,10 +128,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -139,9 +139,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -151,7 +151,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -170,10 +170,10 @@ open class StoreAPI { */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -181,9 +181,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index cfd30068a9db..542dc212bd1b 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -15,7 +15,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -35,10 +35,10 @@ open class UserAPI { */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { let path = "/user" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -46,9 +46,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -58,7 +58,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -77,10 +77,10 @@ open class UserAPI { */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -88,9 +88,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -100,7 +100,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -119,10 +119,10 @@ open class UserAPI { */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -130,9 +130,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -142,7 +142,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -165,10 +165,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -176,9 +176,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -188,7 +188,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -210,10 +210,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -221,9 +221,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -234,7 +234,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -255,11 +255,11 @@ open class UserAPI { */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) @@ -270,9 +270,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -281,7 +281,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -299,10 +299,10 @@ open class UserAPI { */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -310,9 +310,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -323,7 +323,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -347,10 +347,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -358,9 +358,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift index f26fae21f710..c5bab793d7bb 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift @@ -76,7 +76,7 @@ open class AlamofireRequestBuilder: RequestBuilder { return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: headers) } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let managerId = UUID().uuidString // Create a new manager for each request to customize its request header let manager = createSessionManager() @@ -190,16 +190,18 @@ open class AlamofireRequestBuilder: RequestBuilder { let fileManager = FileManager.default let urlRequest = try request.asURLRequest() - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try self.getURL(from: urlRequest) var requestPath = try self.getPath(from: requestURL) if let headerFileName = self.getFileName(fromContentDisposition: dataResponse.response?.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -225,6 +227,18 @@ open class AlamofireRequestBuilder: RequestBuilder { completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.response, error))) } + }) + case is Data.Type: + validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in + cleanupRequest() + + switch dataResponse.result { + case .success: + completion(.success(Response(response: dataResponse.response!, body: dataResponse.data as? T))) + case let .failure(error): + completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.response, error))) + } + }) default: validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in @@ -328,6 +342,52 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuild } }) + case is URL.Type: + validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in + cleanupRequest() + + do { + + guard !dataResponse.result.isFailure else { + throw DownloadException.responseFailed + } + + guard let data = dataResponse.data else { + throw DownloadException.responseDataMissing + } + + guard let request = request.request else { + throw DownloadException.requestMissing + } + + let fileManager = FileManager.default + let urlRequest = try request.asURLRequest() + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try self.getURL(from: urlRequest) + + var requestPath = try self.getPath(from: requestURL) + + if let headerFileName = self.getFileName(fromContentDisposition: dataResponse.response?.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: dataResponse.response!, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, error))) + } + return + }) case is Void.Type: validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { voidResponse in cleanupRequest() diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 93ed6b90b376..e23035dde30e 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,6 +5,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -52,6 +55,12 @@ extension Array: JSONEncodable { } } +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + extension Dictionary: JSONEncodable { func encodeToJSON() -> Any { var dictionary = [AnyHashable: Any]() diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 733b7bc51594..61a478de142b 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct AdditionalPropertiesClass: Codable, Hashable { @@ -22,4 +25,11 @@ public struct AdditionalPropertiesClass: Codable, Hashable { case mapMapString = "map_map_string" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapString, forKey: .mapString) + try container.encodeIfPresent(mapMapString, forKey: .mapMapString) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index e57c8b471765..157cca1d227b 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Animal: Codable, Hashable { @@ -17,4 +20,16 @@ public struct Animal: Codable, Hashable { self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index e09b0e9efdc8..a0b09cb97615 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,5 +6,8 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 630992f6231e..8607cbef1a33 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ApiResponse: Codable, Hashable { @@ -19,4 +22,18 @@ public struct ApiResponse: Codable, Hashable { self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { + case code + case type + case message + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(code, forKey: .code) + try container.encodeIfPresent(type, forKey: .type) + try container.encodeIfPresent(message, forKey: .message) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 4710793fc9a6..f3f161b44c1c 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { case arrayArrayNumber = "ArrayArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index a41968d9b199..d62de957472a 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayOfNumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct ArrayOfNumberOnly: Codable, Hashable { case arrayNumber = "ArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index f442ea725451..360d50d027f1 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayTest: Codable, Hashable { @@ -25,4 +28,12 @@ public struct ArrayTest: Codable, Hashable { case arrayArrayOfModel = "array_array_of_model" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayOfString, forKey: .arrayOfString) + try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) + try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index 44b50bbe0063..f0781a9cb738 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Capitalization: Codable, Hashable { @@ -35,4 +38,15 @@ public struct Capitalization: Codable, Hashable { case ATT_NAME } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(smallCamel, forKey: .smallCamel) + try container.encodeIfPresent(capitalCamel, forKey: .capitalCamel) + try container.encodeIfPresent(smallSnake, forKey: .smallSnake) + try container.encodeIfPresent(capitalSnake, forKey: .capitalSnake) + try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) + try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index c6bf4460da6e..d5519760387a 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Cat: Codable, Hashable { @@ -19,4 +22,18 @@ public struct Cat: Codable, Hashable { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index f9484f9bc8fd..8312680deb37 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct CatAllOf: Codable, Hashable { @@ -15,4 +18,14 @@ public struct CatAllOf: Codable, Hashable { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 6a19bb02d0df..398da60aa73b 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,15 +6,30 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Category: Codable, Hashable { public var id: Int64? - public var name: String = "default-name" + public var name: String? = "default-name" - public init(id: Int64? = nil, name: String = "default-name") { + public init(id: Int64? = nil, name: String? = "default-name") { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encode(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index 5c8e8882831f..03bf63e4cad1 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model with \"_class\" property */ public struct ClassModel: Codable, Hashable { @@ -16,4 +19,14 @@ public struct ClassModel: Codable, Hashable { self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { + case _class + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_class, forKey: ._class) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 1464b047c06a..596048780439 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Client: Codable, Hashable { @@ -15,4 +18,14 @@ public struct Client: Codable, Hashable { self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { + case client + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(client, forKey: .client) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index 5aed7834d537..4ada3ceb605a 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Dog: Codable, Hashable { @@ -19,4 +22,18 @@ public struct Dog: Codable, Hashable { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 716776261d30..f6c3d287301d 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct DogAllOf: Codable, Hashable { @@ -15,4 +18,14 @@ public struct DogAllOf: Codable, Hashable { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index aa13aa59f86a..0e0aad42abe6 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct EnumArrays: Codable, Hashable { @@ -30,4 +33,11 @@ public struct EnumArrays: Codable, Hashable { case arrayEnum = "array_enum" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justSymbol, forKey: .justSymbol) + try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index d4029d73f8af..6ea2895aee53 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 8b62febdc959..9e44926be9b8 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct EnumTest: Codable, Hashable { @@ -49,4 +52,14 @@ public struct EnumTest: Codable, Hashable { case outerEnum } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(enumString, forKey: .enumString) + try container.encode(enumStringRequired, forKey: .enumStringRequired) + try container.encodeIfPresent(enumInteger, forKey: .enumInteger) + try container.encodeIfPresent(enumNumber, forKey: .enumNumber) + try container.encodeIfPresent(outerEnum, forKey: .outerEnum) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift index aa14d762394d..11694b2ca59b 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Must be named `File` for test. */ public struct File: Codable, Hashable { @@ -17,4 +20,14 @@ public struct File: Codable, Hashable { self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { + case sourceURI + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(sourceURI, forKey: .sourceURI) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index 85987709776e..6aa85d8eecf9 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FileSchemaTestClass: Codable, Hashable { @@ -17,4 +20,16 @@ public struct FileSchemaTestClass: Codable, Hashable { self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { + case file + case files + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(file, forKey: .file) + try container.encodeIfPresent(files, forKey: .files) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index f09cb471b360..114c884efc5e 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FormatTest: Codable, Hashable { @@ -39,4 +42,38 @@ public struct FormatTest: Codable, Hashable { self.password = password } + public enum CodingKeys: String, CodingKey, CaseIterable { + case integer + case int32 + case int64 + case number + case float + case double + case string + case byte + case binary + case date + case dateTime + case uuid + case password + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(integer, forKey: .integer) + try container.encodeIfPresent(int32, forKey: .int32) + try container.encodeIfPresent(int64, forKey: .int64) + try container.encode(number, forKey: .number) + try container.encodeIfPresent(float, forKey: .float) + try container.encodeIfPresent(double, forKey: .double) + try container.encodeIfPresent(string, forKey: .string) + try container.encode(byte, forKey: .byte) + try container.encodeIfPresent(binary, forKey: .binary) + try container.encode(date, forKey: .date) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encode(password, forKey: .password) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index 03d35274a4ee..cb1a7456a7df 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct HasOnlyReadOnly: Codable, Hashable { @@ -17,4 +20,16 @@ public struct HasOnlyReadOnly: Codable, Hashable { self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case foo + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(foo, forKey: .foo) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift index f8f08e4c6c44..8ecdd3b02339 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct List: Codable, Hashable { @@ -19,4 +22,10 @@ public struct List: Codable, Hashable { case _123list = "123-list" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_123list, forKey: ._123list) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index bd4e7b97e81b..0ff74ed8400e 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct MapTest: Codable, Hashable { @@ -32,4 +35,13 @@ public struct MapTest: Codable, Hashable { case indirectMap = "indirect_map" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapMapOfString, forKey: .mapMapOfString) + try container.encodeIfPresent(mapOfEnumString, forKey: .mapOfEnumString) + try container.encodeIfPresent(directMap, forKey: .directMap) + try container.encodeIfPresent(indirectMap, forKey: .indirectMap) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index 80c1781a2bfc..58a0a54ca090 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { @@ -19,4 +22,18 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { + case uuid + case dateTime + case map + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(map, forKey: .map) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index d36d4e27352a..0f59769954f1 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name starting with number */ public struct Model200Response: Codable, Hashable { @@ -23,4 +26,11 @@ public struct Model200Response: Codable, Hashable { case _class = "class" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(_class, forKey: ._class) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 49cc57544179..d88c94f05c95 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name same as property name */ public struct Name: Codable, Hashable { @@ -29,4 +32,13 @@ public struct Name: Codable, Hashable { case _123number = "123Number" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encodeIfPresent(snakeCase, forKey: .snakeCase) + try container.encodeIfPresent(property, forKey: .property) + try container.encodeIfPresent(_123number, forKey: ._123number) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 6b024294e288..0f05482b9b7c 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct NumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct NumberOnly: Codable, Hashable { case justNumber = "JustNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justNumber, forKey: .justNumber) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 8ef7cb79e2c8..100d6b71fed4 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Order: Codable, Hashable { @@ -31,4 +34,24 @@ public struct Order: Codable, Hashable { self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case petId + case quantity + case shipDate + case status + case complete + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(petId, forKey: .petId) + try container.encodeIfPresent(quantity, forKey: .quantity) + try container.encodeIfPresent(shipDate, forKey: .shipDate) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(complete, forKey: .complete) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 9865764ff9bb..15a4e4a15b6e 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct OuterComposite: Codable, Hashable { @@ -25,4 +28,12 @@ public struct OuterComposite: Codable, Hashable { case myBoolean = "my_boolean" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(myNumber, forKey: .myNumber) + try container.encodeIfPresent(myString, forKey: .myString) + try container.encodeIfPresent(myBoolean, forKey: .myBoolean) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index c3b778cbbed4..76c34b3c2ce6 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 1bc823d3e960..a87ab825ea0b 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Pet: Codable, Hashable { @@ -31,4 +34,24 @@ public struct Pet: Codable, Hashable { self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case category + case name + case photoUrls + case tags + case status + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(category, forKey: .category) + try container.encode(name, forKey: .name) + try container.encode(photoUrls, forKey: .photoUrls) + try container.encodeIfPresent(tags, forKey: .tags) + try container.encodeIfPresent(status, forKey: .status) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 03b5b0dbf02b..6426deedf637 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ReadOnlyFirst: Codable, Hashable { @@ -17,4 +20,16 @@ public struct ReadOnlyFirst: Codable, Hashable { self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case baz + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(baz, forKey: .baz) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 5f539f461843..777c241bc0c0 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing reserved words */ public struct Return: Codable, Hashable { @@ -20,4 +23,10 @@ public struct Return: Codable, Hashable { case _return = "return" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_return, forKey: ._return) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index cb82d2ae3adc..b677523a7491 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct SpecialModelName: Codable, Hashable { @@ -19,4 +22,10 @@ public struct SpecialModelName: Codable, Hashable { case specialPropertyName = "$special[property.name]" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 77ab81f5f341..f575c9df65ca 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,9 +6,16 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct StringBooleanMap: Codable, Hashable { + + public enum CodingKeys: CodingKey, CaseIterable { + } + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -27,19 +34,18 @@ public struct StringBooleanMap: Codable, Hashable { // Encodable protocol methods public func encode(to encoder: Encoder) throws { - - var container = encoder.container(keyedBy: String.self) - - try container.encodeMap(additionalProperties) + var container = encoder.container(keyedBy: CodingKeys.self) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) } // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 8b8e24fc39c0..cd5acc827db7 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Tag: Codable, Hashable { @@ -17,4 +20,16 @@ public struct Tag: Codable, Hashable { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index f1920ef37788..341c9b4b8c2e 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct TypeHolderDefault: Codable, Hashable { @@ -31,4 +34,14 @@ public struct TypeHolderDefault: Codable, Hashable { case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index 1a23c1b486b8..04166af0895f 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct TypeHolderExample: Codable, Hashable { @@ -31,4 +34,14 @@ public struct TypeHolderExample: Codable, Hashable { case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift index f3b4f6bb958a..9f3ded8fcd93 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct User: Codable, Hashable { @@ -30,4 +33,28 @@ public struct User: Codable, Hashable { self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case username + case firstName + case lastName + case email + case password + case phone + case userStatus + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(username, forKey: .username) + try container.encodeIfPresent(firstName, forKey: .firstName) + try container.encodeIfPresent(lastName, forKey: .lastName) + try container.encodeIfPresent(email, forKey: .email) + try container.encodeIfPresent(password, forKey: .password) + try container.encodeIfPresent(phone, forKey: .phone) + try container.encodeIfPresent(userStatus, forKey: .userStatus) + } } diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/Podfile b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/Podfile deleted file mode 100644 index 77432f9eee92..000000000000 --- a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/Podfile +++ /dev/null @@ -1,13 +0,0 @@ -platform :ios, '9.0' - -source 'https://cdn.cocoapods.org/' - -use_frameworks! - -target 'SwaggerClient' do - pod "PetstoreClient", :path => "../" - - target 'SwaggerClientTests' do - inherit! :search_paths - end -end diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/Podfile.lock deleted file mode 100644 index 30f84a6b9c3a..000000000000 --- a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/Podfile.lock +++ /dev/null @@ -1,23 +0,0 @@ -PODS: - - Alamofire (4.9.1) - - PetstoreClient (1.0.0): - - Alamofire (~> 4.9.1) - -DEPENDENCIES: - - PetstoreClient (from `../`) - -SPEC REPOS: - trunk: - - Alamofire - -EXTERNAL SOURCES: - PetstoreClient: - :path: "../" - -SPEC CHECKSUMS: - Alamofire: 85e8a02c69d6020a0d734f6054870d7ecb75cf18 - PetstoreClient: bc687d8c4d0c762098d72690e220cae37e281311 - -PODFILE CHECKSUM: 509bec696cc1d8641751b52e4fe4bef04ac4542c - -COCOAPODS: 1.10.0 diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 901182fb107a..03aed8e5f82c 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -3,11 +3,10 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 52; objects = { /* Begin PBXBuildFile section */ - 198019EEC6E3CB01FC884C7A /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D829DFE4E137D91D6174D75A /* Pods_SwaggerClientTests.framework */; }; 1A501F48219C3DC600F372F6 /* DateFormatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A501F47219C3DC600F372F6 /* DateFormatTests.swift */; }; 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */; }; 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB961C692C6300B96B06 /* ViewController.swift */; }; @@ -18,9 +17,9 @@ 6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */; }; 6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */; }; A5465873259E306E00C3929B /* BearerDecodableRequestBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5465872259E306E00C3929B /* BearerDecodableRequestBuilder.swift */; }; + A5782C6D2664F91D00CAA106 /* PetstoreClient in Frameworks */ = {isa = PBXBuildFile; productRef = A5782C6C2664F91D00CAA106 /* PetstoreClient */; }; A5EA12542419387200E30FC3 /* FileUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA12522419387100E30FC3 /* FileUtils.swift */; }; A5EA12552419387200E30FC3 /* UIImage+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA12532419387100E30FC3 /* UIImage+Extras.swift */; }; - B68489033454646C60C16C88 /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79549D5237E5E83F567030EC /* Pods_SwaggerClient.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -35,7 +34,6 @@ /* Begin PBXFileReference section */ 1A501F47219C3DC600F372F6 /* DateFormatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateFormatTests.swift; sourceTree = ""; }; - 32ED0E88E0B89A537075D9C9 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwaggerClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 6D4EFB961C692C6300B96B06 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; @@ -48,15 +46,9 @@ 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = ""; }; 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = ""; }; 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; - 74246FD63841F7C179AD697F /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; - 79549D5237E5E83F567030EC /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 8ABA6AE59F792DAA1F79C48F /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; A5465872259E306E00C3929B /* BearerDecodableRequestBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BearerDecodableRequestBuilder.swift; sourceTree = ""; }; A5EA12522419387100E30FC3 /* FileUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileUtils.swift; sourceTree = ""; }; A5EA12532419387100E30FC3 /* UIImage+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIImage+Extras.swift"; sourceTree = ""; }; - C07EC0A94AA0F86D60668B32 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - D829DFE4E137D91D6174D75A /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - FB503FF47F354A87D697DD0A /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -64,7 +56,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - B68489033454646C60C16C88 /* Pods_SwaggerClient.framework in Frameworks */, + A5782C6D2664F91D00CAA106 /* PetstoreClient in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -72,7 +64,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 198019EEC6E3CB01FC884C7A /* Pods_SwaggerClientTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -82,9 +73,6 @@ 3FABC56EC0BA84CBF4F99564 /* Frameworks */ = { isa = PBXGroup; children = ( - C07EC0A94AA0F86D60668B32 /* Pods.framework */, - 79549D5237E5E83F567030EC /* Pods_SwaggerClient.framework */, - D829DFE4E137D91D6174D75A /* Pods_SwaggerClientTests.framework */, ); name = Frameworks; sourceTree = ""; @@ -96,7 +84,6 @@ 6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */, 6D4EFB921C692C6300B96B06 /* Products */, 3FABC56EC0BA84CBF4F99564 /* Frameworks */, - AC485EA5DC51CA28F3F7FECF /* Pods */, ); sourceTree = ""; }; @@ -137,18 +124,6 @@ path = SwaggerClientTests; sourceTree = ""; }; - AC485EA5DC51CA28F3F7FECF /* Pods */ = { - isa = PBXGroup; - children = ( - 32ED0E88E0B89A537075D9C9 /* Pods-SwaggerClient.debug.xcconfig */, - FB503FF47F354A87D697DD0A /* Pods-SwaggerClient.release.xcconfig */, - 74246FD63841F7C179AD697F /* Pods-SwaggerClientTests.debug.xcconfig */, - 8ABA6AE59F792DAA1F79C48F /* Pods-SwaggerClientTests.release.xcconfig */, - ); - name = Pods; - path = Pods; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -156,17 +131,18 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 53EC90CFFB0E0FABA75F972D /* [CP] Check Pods Manifest.lock */, 6D4EFB8D1C692C6300B96B06 /* Sources */, 6D4EFB8E1C692C6300B96B06 /* Frameworks */, 6D4EFB8F1C692C6300B96B06 /* Resources */, - 3E0F8DF721D95AAFC75864D4 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( ); name = SwaggerClient; + packageProductDependencies = ( + A5782C6C2664F91D00CAA106 /* PetstoreClient */, + ); productName = SwaggerClient; productReference = 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */; productType = "com.apple.product-type.application"; @@ -175,7 +151,6 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - 89F684025365A60C007C7DA9 /* [CP] Check Pods Manifest.lock */, 6D4EFBA11C692C6300B96B06 /* Sources */, 6D4EFBA21C692C6300B96B06 /* Frameworks */, 6D4EFBA31C692C6300B96B06 /* Resources */, @@ -250,73 +225,6 @@ }; /* End PBXResourcesBuildPhase section */ -/* Begin PBXShellScriptBuildPhase section */ - 3E0F8DF721D95AAFC75864D4 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework", - "${BUILT_PRODUCTS_DIR}/PetstoreClient/PetstoreClient.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PetstoreClient.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - 53EC90CFFB0E0FABA75F972D /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClient-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 89F684025365A60C007C7DA9 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClientTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - /* Begin PBXSourcesBuildPhase section */ 6D4EFB8D1C692C6300B96B06 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -481,11 +389,13 @@ }; 6D4EFBAF1C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 32ED0E88E0B89A537075D9C9 /* Pods-SwaggerClient.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -494,11 +404,13 @@ }; 6D4EFBB01C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = FB503FF47F354A87D697DD0A /* Pods-SwaggerClient.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -507,11 +419,14 @@ }; 6D4EFBB21C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 74246FD63841F7C179AD697F /* Pods-SwaggerClientTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -521,11 +436,14 @@ }; 6D4EFBB31C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 8ABA6AE59F792DAA1F79C48F /* Pods-SwaggerClientTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -564,6 +482,13 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCSwiftPackageProductDependency section */ + A5782C6C2664F91D00CAA106 /* PetstoreClient */ = { + isa = XCSwiftPackageProductDependency; + productName = PetstoreClient; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 6D4EFB891C692C6300B96B06 /* Project object */; } diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata index 9b3fa18954f7..00ec9b53a7f1 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata +++ b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata @@ -2,9 +2,9 @@ + location = "group:.."> + location = "group:SwaggerClient.xcodeproj"> diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 000000000000..4c8626cac13e --- /dev/null +++ b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,25 @@ +{ + "object": { + "pins": [ + { + "package": "Alamofire", + "repositoryURL": "https://github.com/Alamofire/Alamofire.git", + "state": { + "branch": null, + "revision": "747c8db8d57b68d5e35275f10c92d55f982adbd4", + "version": "4.9.1" + } + }, + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md index 543869c0d2e0..553a46281aa0 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md @@ -379,7 +379,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) diff --git a/samples/client/petstore/swift5/alamofireLibrary/project.yml b/samples/client/petstore/swift5/alamofireLibrary/project.yml index 08035907b99e..29a682f44780 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/project.yml +++ b/samples/client/petstore/swift5/alamofireLibrary/project.yml @@ -12,4 +12,5 @@ targets: APPLICATION_EXTENSION_API_ONLY: true scheme: {} dependencies: + - carthage: AnyCodable - carthage: Alamofire diff --git a/samples/client/petstore/swift5/combineLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/combineLibrary/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/swift5/combineLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/combineLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/combineLibrary/Cartfile b/samples/client/petstore/swift5/combineLibrary/Cartfile index 8b137891791f..843f7adc7794 100644 --- a/samples/client/petstore/swift5/combineLibrary/Cartfile +++ b/samples/client/petstore/swift5/combineLibrary/Cartfile @@ -1 +1,2 @@ +github "Flight-School/AnyCodable" ~> 0.6.0 diff --git a/samples/client/petstore/swift5/combineLibrary/Package.resolved b/samples/client/petstore/swift5/combineLibrary/Package.resolved new file mode 100644 index 000000000000..d384b276b4bc --- /dev/null +++ b/samples/client/petstore/swift5/combineLibrary/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/combineLibrary/Package.swift b/samples/client/petstore/swift5/combineLibrary/Package.swift index b7fe4734aa8a..5cde507bdcf9 100644 --- a/samples/client/petstore/swift5/combineLibrary/Package.swift +++ b/samples/client/petstore/swift5/combineLibrary/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.0 +// swift-tools-version:5.1 import PackageDescription @@ -19,13 +19,14 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.6.0")), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "PetstoreClient", - dependencies: [], + dependencies: ["AnyCodable", ], path: "PetstoreClient/Classes" ), ] diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient.podspec b/samples/client/petstore/swift5/combineLibrary/PetstoreClient.podspec index b61285f6b25e..60f05891b241 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient.podspec @@ -11,4 +11,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.0' end diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index dbdab491ff7d..01bc6ff0d8d0 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,7 +6,10 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 62f1ed590426..f7f14df25d33 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -20,7 +20,7 @@ open class AnotherFakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -43,10 +43,10 @@ open class AnotherFakeAPI { */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -54,9 +54,9 @@ open class AnotherFakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index b90460ea41ac..c25873363548 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -19,7 +19,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -41,10 +41,10 @@ open class FakeAPI { */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -52,9 +52,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -65,7 +65,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -87,10 +87,10 @@ open class FakeAPI { */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -98,9 +98,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -111,7 +111,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -133,10 +133,10 @@ open class FakeAPI { */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -144,9 +144,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -157,7 +157,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -179,10 +179,10 @@ open class FakeAPI { */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -190,9 +190,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -203,7 +203,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -225,10 +225,10 @@ open class FakeAPI { */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -236,9 +236,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -250,7 +250,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -272,11 +272,11 @@ open class FakeAPI { */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) @@ -286,9 +286,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -300,7 +300,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -323,10 +323,10 @@ open class FakeAPI { */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -334,9 +334,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -361,7 +361,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute(apiResponseQueue) { result -> Void in switch result { @@ -400,7 +400,7 @@ open class FakeAPI { */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), @@ -421,7 +421,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -429,9 +429,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -517,7 +517,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { @@ -547,7 +547,7 @@ open class FakeAPI { */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), @@ -556,8 +556,8 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), @@ -572,9 +572,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -591,7 +591,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { @@ -619,11 +619,11 @@ open class FakeAPI { */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), @@ -637,9 +637,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -651,7 +651,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { @@ -673,10 +673,10 @@ open class FakeAPI { */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -684,9 +684,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -699,7 +699,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { @@ -722,7 +722,7 @@ open class FakeAPI { */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), @@ -731,7 +731,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -739,9 +739,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 42d6ea597b4b..094b75647ae6 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -20,7 +20,7 @@ open class FakeClassnameTags123API { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -46,10 +46,10 @@ open class FakeClassnameTags123API { */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -57,9 +57,9 @@ open class FakeClassnameTags123API { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index b4226ff4aa1d..b1d495832c66 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -20,7 +20,7 @@ open class PetAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -45,10 +45,10 @@ open class PetAPI { */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -56,9 +56,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -71,7 +71,7 @@ open class PetAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { @@ -100,10 +100,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), @@ -111,9 +111,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -134,7 +134,7 @@ open class PetAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher<[Pet], Error> { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher<[Pet], Error> { return Future<[Pet], Error>.init { promise in findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { @@ -160,11 +160,11 @@ open class PetAPI { */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) @@ -174,9 +174,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -189,7 +189,7 @@ open class PetAPI { #if canImport(Combine) @available(*, deprecated, message: "This operation is deprecated.") @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher<[Pet], Error> { + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher<[Pet], Error> { return Future<[Pet], Error>.init { promise in findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { @@ -216,11 +216,11 @@ open class PetAPI { @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) @@ -230,9 +230,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -244,7 +244,7 @@ open class PetAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { @@ -273,10 +273,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -284,9 +284,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -298,7 +298,7 @@ open class PetAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -323,10 +323,10 @@ open class PetAPI { */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -334,9 +334,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -350,7 +350,7 @@ open class PetAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { @@ -380,7 +380,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), @@ -389,7 +389,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -397,9 +397,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -413,7 +413,7 @@ open class PetAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { @@ -443,7 +443,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), @@ -452,7 +452,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -460,9 +460,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -476,7 +476,7 @@ open class PetAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { @@ -506,7 +506,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), @@ -515,7 +515,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -523,9 +523,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index b50dcb0193c8..9e4aa781716d 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -20,7 +20,7 @@ open class StoreAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { @@ -46,10 +46,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -57,9 +57,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -70,7 +70,7 @@ open class StoreAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher<[String: Int], Error> { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher<[String: Int], Error> { return Future<[String: Int], Error>.init { promise in getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { @@ -95,10 +95,10 @@ open class StoreAPI { */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -106,9 +106,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -120,7 +120,7 @@ open class StoreAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { @@ -146,10 +146,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -157,9 +157,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -171,7 +171,7 @@ open class StoreAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -193,10 +193,10 @@ open class StoreAPI { */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -204,9 +204,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index f678057ceaf9..fa260d3e83a8 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -20,7 +20,7 @@ open class UserAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -43,10 +43,10 @@ open class UserAPI { */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { let path = "/user" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -54,9 +54,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -68,7 +68,7 @@ open class UserAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -90,10 +90,10 @@ open class UserAPI { */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -101,9 +101,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -115,7 +115,7 @@ open class UserAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -137,10 +137,10 @@ open class UserAPI { */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -148,9 +148,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -162,7 +162,7 @@ open class UserAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { @@ -188,10 +188,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -199,9 +199,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -213,7 +213,7 @@ open class UserAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { @@ -238,10 +238,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -249,9 +249,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -264,7 +264,7 @@ open class UserAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { @@ -288,11 +288,11 @@ open class UserAPI { */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) @@ -303,9 +303,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -316,7 +316,7 @@ open class UserAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { @@ -337,10 +337,10 @@ open class UserAPI { */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -348,9 +348,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -363,7 +363,7 @@ open class UserAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -390,10 +390,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -401,9 +401,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 93ed6b90b376..e23035dde30e 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,6 +5,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -52,6 +55,12 @@ extension Array: JSONEncodable { } } +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + extension Dictionary: JSONEncodable { func encodeToJSON() -> Any { var dictionary = [AnyHashable: Any]() diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 733b7bc51594..61a478de142b 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct AdditionalPropertiesClass: Codable, Hashable { @@ -22,4 +25,11 @@ public struct AdditionalPropertiesClass: Codable, Hashable { case mapMapString = "map_map_string" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapString, forKey: .mapString) + try container.encodeIfPresent(mapMapString, forKey: .mapMapString) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index e57c8b471765..157cca1d227b 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Animal: Codable, Hashable { @@ -17,4 +20,16 @@ public struct Animal: Codable, Hashable { self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index e09b0e9efdc8..a0b09cb97615 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,5 +6,8 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 630992f6231e..8607cbef1a33 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ApiResponse: Codable, Hashable { @@ -19,4 +22,18 @@ public struct ApiResponse: Codable, Hashable { self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { + case code + case type + case message + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(code, forKey: .code) + try container.encodeIfPresent(type, forKey: .type) + try container.encodeIfPresent(message, forKey: .message) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 4710793fc9a6..f3f161b44c1c 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { case arrayArrayNumber = "ArrayArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index a41968d9b199..d62de957472a 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayOfNumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct ArrayOfNumberOnly: Codable, Hashable { case arrayNumber = "ArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index f442ea725451..360d50d027f1 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayTest: Codable, Hashable { @@ -25,4 +28,12 @@ public struct ArrayTest: Codable, Hashable { case arrayArrayOfModel = "array_array_of_model" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayOfString, forKey: .arrayOfString) + try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) + try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index 44b50bbe0063..f0781a9cb738 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Capitalization: Codable, Hashable { @@ -35,4 +38,15 @@ public struct Capitalization: Codable, Hashable { case ATT_NAME } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(smallCamel, forKey: .smallCamel) + try container.encodeIfPresent(capitalCamel, forKey: .capitalCamel) + try container.encodeIfPresent(smallSnake, forKey: .smallSnake) + try container.encodeIfPresent(capitalSnake, forKey: .capitalSnake) + try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) + try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index c6bf4460da6e..d5519760387a 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Cat: Codable, Hashable { @@ -19,4 +22,18 @@ public struct Cat: Codable, Hashable { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index f9484f9bc8fd..8312680deb37 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct CatAllOf: Codable, Hashable { @@ -15,4 +18,14 @@ public struct CatAllOf: Codable, Hashable { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 6a19bb02d0df..398da60aa73b 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,15 +6,30 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Category: Codable, Hashable { public var id: Int64? - public var name: String = "default-name" + public var name: String? = "default-name" - public init(id: Int64? = nil, name: String = "default-name") { + public init(id: Int64? = nil, name: String? = "default-name") { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encode(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index 5c8e8882831f..03bf63e4cad1 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model with \"_class\" property */ public struct ClassModel: Codable, Hashable { @@ -16,4 +19,14 @@ public struct ClassModel: Codable, Hashable { self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { + case _class + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_class, forKey: ._class) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 1464b047c06a..596048780439 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Client: Codable, Hashable { @@ -15,4 +18,14 @@ public struct Client: Codable, Hashable { self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { + case client + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(client, forKey: .client) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index 5aed7834d537..4ada3ceb605a 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Dog: Codable, Hashable { @@ -19,4 +22,18 @@ public struct Dog: Codable, Hashable { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 716776261d30..f6c3d287301d 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct DogAllOf: Codable, Hashable { @@ -15,4 +18,14 @@ public struct DogAllOf: Codable, Hashable { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index aa13aa59f86a..0e0aad42abe6 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct EnumArrays: Codable, Hashable { @@ -30,4 +33,11 @@ public struct EnumArrays: Codable, Hashable { case arrayEnum = "array_enum" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justSymbol, forKey: .justSymbol) + try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index d4029d73f8af..6ea2895aee53 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 8b62febdc959..9e44926be9b8 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct EnumTest: Codable, Hashable { @@ -49,4 +52,14 @@ public struct EnumTest: Codable, Hashable { case outerEnum } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(enumString, forKey: .enumString) + try container.encode(enumStringRequired, forKey: .enumStringRequired) + try container.encodeIfPresent(enumInteger, forKey: .enumInteger) + try container.encodeIfPresent(enumNumber, forKey: .enumNumber) + try container.encodeIfPresent(outerEnum, forKey: .outerEnum) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift index aa14d762394d..11694b2ca59b 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Must be named `File` for test. */ public struct File: Codable, Hashable { @@ -17,4 +20,14 @@ public struct File: Codable, Hashable { self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { + case sourceURI + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(sourceURI, forKey: .sourceURI) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index 85987709776e..6aa85d8eecf9 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FileSchemaTestClass: Codable, Hashable { @@ -17,4 +20,16 @@ public struct FileSchemaTestClass: Codable, Hashable { self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { + case file + case files + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(file, forKey: .file) + try container.encodeIfPresent(files, forKey: .files) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index f09cb471b360..114c884efc5e 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FormatTest: Codable, Hashable { @@ -39,4 +42,38 @@ public struct FormatTest: Codable, Hashable { self.password = password } + public enum CodingKeys: String, CodingKey, CaseIterable { + case integer + case int32 + case int64 + case number + case float + case double + case string + case byte + case binary + case date + case dateTime + case uuid + case password + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(integer, forKey: .integer) + try container.encodeIfPresent(int32, forKey: .int32) + try container.encodeIfPresent(int64, forKey: .int64) + try container.encode(number, forKey: .number) + try container.encodeIfPresent(float, forKey: .float) + try container.encodeIfPresent(double, forKey: .double) + try container.encodeIfPresent(string, forKey: .string) + try container.encode(byte, forKey: .byte) + try container.encodeIfPresent(binary, forKey: .binary) + try container.encode(date, forKey: .date) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encode(password, forKey: .password) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index 03d35274a4ee..cb1a7456a7df 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct HasOnlyReadOnly: Codable, Hashable { @@ -17,4 +20,16 @@ public struct HasOnlyReadOnly: Codable, Hashable { self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case foo + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(foo, forKey: .foo) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift index f8f08e4c6c44..8ecdd3b02339 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct List: Codable, Hashable { @@ -19,4 +22,10 @@ public struct List: Codable, Hashable { case _123list = "123-list" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_123list, forKey: ._123list) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index bd4e7b97e81b..0ff74ed8400e 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct MapTest: Codable, Hashable { @@ -32,4 +35,13 @@ public struct MapTest: Codable, Hashable { case indirectMap = "indirect_map" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapMapOfString, forKey: .mapMapOfString) + try container.encodeIfPresent(mapOfEnumString, forKey: .mapOfEnumString) + try container.encodeIfPresent(directMap, forKey: .directMap) + try container.encodeIfPresent(indirectMap, forKey: .indirectMap) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index 80c1781a2bfc..58a0a54ca090 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { @@ -19,4 +22,18 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { + case uuid + case dateTime + case map + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(map, forKey: .map) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index d36d4e27352a..0f59769954f1 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name starting with number */ public struct Model200Response: Codable, Hashable { @@ -23,4 +26,11 @@ public struct Model200Response: Codable, Hashable { case _class = "class" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(_class, forKey: ._class) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 49cc57544179..d88c94f05c95 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name same as property name */ public struct Name: Codable, Hashable { @@ -29,4 +32,13 @@ public struct Name: Codable, Hashable { case _123number = "123Number" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encodeIfPresent(snakeCase, forKey: .snakeCase) + try container.encodeIfPresent(property, forKey: .property) + try container.encodeIfPresent(_123number, forKey: ._123number) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 6b024294e288..0f05482b9b7c 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct NumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct NumberOnly: Codable, Hashable { case justNumber = "JustNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justNumber, forKey: .justNumber) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 8ef7cb79e2c8..100d6b71fed4 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Order: Codable, Hashable { @@ -31,4 +34,24 @@ public struct Order: Codable, Hashable { self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case petId + case quantity + case shipDate + case status + case complete + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(petId, forKey: .petId) + try container.encodeIfPresent(quantity, forKey: .quantity) + try container.encodeIfPresent(shipDate, forKey: .shipDate) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(complete, forKey: .complete) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 9865764ff9bb..15a4e4a15b6e 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct OuterComposite: Codable, Hashable { @@ -25,4 +28,12 @@ public struct OuterComposite: Codable, Hashable { case myBoolean = "my_boolean" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(myNumber, forKey: .myNumber) + try container.encodeIfPresent(myString, forKey: .myString) + try container.encodeIfPresent(myBoolean, forKey: .myBoolean) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index c3b778cbbed4..76c34b3c2ce6 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 1bc823d3e960..a87ab825ea0b 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Pet: Codable, Hashable { @@ -31,4 +34,24 @@ public struct Pet: Codable, Hashable { self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case category + case name + case photoUrls + case tags + case status + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(category, forKey: .category) + try container.encode(name, forKey: .name) + try container.encode(photoUrls, forKey: .photoUrls) + try container.encodeIfPresent(tags, forKey: .tags) + try container.encodeIfPresent(status, forKey: .status) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 03b5b0dbf02b..6426deedf637 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ReadOnlyFirst: Codable, Hashable { @@ -17,4 +20,16 @@ public struct ReadOnlyFirst: Codable, Hashable { self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case baz + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(baz, forKey: .baz) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 5f539f461843..777c241bc0c0 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing reserved words */ public struct Return: Codable, Hashable { @@ -20,4 +23,10 @@ public struct Return: Codable, Hashable { case _return = "return" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_return, forKey: ._return) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index cb82d2ae3adc..b677523a7491 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct SpecialModelName: Codable, Hashable { @@ -19,4 +22,10 @@ public struct SpecialModelName: Codable, Hashable { case specialPropertyName = "$special[property.name]" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 77ab81f5f341..f575c9df65ca 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,9 +6,16 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct StringBooleanMap: Codable, Hashable { + + public enum CodingKeys: CodingKey, CaseIterable { + } + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -27,19 +34,18 @@ public struct StringBooleanMap: Codable, Hashable { // Encodable protocol methods public func encode(to encoder: Encoder) throws { - - var container = encoder.container(keyedBy: String.self) - - try container.encodeMap(additionalProperties) + var container = encoder.container(keyedBy: CodingKeys.self) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) } // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 8b8e24fc39c0..cd5acc827db7 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Tag: Codable, Hashable { @@ -17,4 +20,16 @@ public struct Tag: Codable, Hashable { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index f1920ef37788..341c9b4b8c2e 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct TypeHolderDefault: Codable, Hashable { @@ -31,4 +34,14 @@ public struct TypeHolderDefault: Codable, Hashable { case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index 1a23c1b486b8..04166af0895f 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct TypeHolderExample: Codable, Hashable { @@ -31,4 +34,14 @@ public struct TypeHolderExample: Codable, Hashable { case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift index f3b4f6bb958a..9f3ded8fcd93 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct User: Codable, Hashable { @@ -30,4 +33,28 @@ public struct User: Codable, Hashable { self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case username + case firstName + case lastName + case email + case password + case phone + case userStatus + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(username, forKey: .username) + try container.encodeIfPresent(firstName, forKey: .firstName) + try container.encodeIfPresent(lastName, forKey: .lastName) + try container.encodeIfPresent(email, forKey: .email) + try container.encodeIfPresent(password, forKey: .password) + try container.encodeIfPresent(phone, forKey: .phone) + try container.encodeIfPresent(userStatus, forKey: .userStatus) + } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 52b2071ec1aa..774c0427eaa2 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,7 +93,7 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/Podfile b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/Podfile deleted file mode 100644 index 77432f9eee92..000000000000 --- a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/Podfile +++ /dev/null @@ -1,13 +0,0 @@ -platform :ios, '9.0' - -source 'https://cdn.cocoapods.org/' - -use_frameworks! - -target 'SwaggerClient' do - pod "PetstoreClient", :path => "../" - - target 'SwaggerClientTests' do - inherit! :search_paths - end -end diff --git a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/Podfile.lock deleted file mode 100644 index a621fdeec885..000000000000 --- a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/Podfile.lock +++ /dev/null @@ -1,16 +0,0 @@ -PODS: - - PetstoreClient (1.0.0) - -DEPENDENCIES: - - PetstoreClient (from `../`) - -EXTERNAL SOURCES: - PetstoreClient: - :path: "../" - -SPEC CHECKSUMS: - PetstoreClient: b26b235a3ece06dbf1da99dc67e48aa201659f21 - -PODFILE CHECKSUM: 509bec696cc1d8641751b52e4fe4bef04ac4542c - -COCOAPODS: 1.9.0 diff --git a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 0be50e9f6f19..84e7599d4d34 100644 --- a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -3,14 +3,13 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 52; objects = { /* Begin PBXBuildFile section */ + A5782C732664FABF00CAA106 /* PetstoreClient in Frameworks */ = {isa = PBXBuildFile; productRef = A5782C722664FABF00CAA106 /* PetstoreClient */; }; A5EA12582419390400E30FC3 /* FileUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA12562419390400E30FC3 /* FileUtils.swift */; }; A5EA12592419390400E30FC3 /* UIImage+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA12572419390400E30FC3 /* UIImage+Extras.swift */; }; - B024164FBFF71BF644D4419A /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 177A58DD5CF63F2989335DCC /* Pods_SwaggerClient.framework */; }; - B1D0246C8960F47A60098F37 /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6F96A0131101344CC5406CB3 /* Pods_SwaggerClientTests.framework */; }; B596E4BD205657A500B46F03 /* APIHelperTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B596E4BC205657A500B46F03 /* APIHelperTests.swift */; }; EAEC0BC21D4E30CE00C908A3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAEC0BC11D4E30CE00C908A3 /* AppDelegate.swift */; }; EAEC0BC41D4E30CE00C908A3 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAEC0BC31D4E30CE00C908A3 /* ViewController.swift */; }; @@ -33,11 +32,6 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 177A58DD5CF63F2989335DCC /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 2DEFA8828BD4E38FA5262F53 /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; - 4EF2021609D112A6F5AE0F55 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; - 6F96A0131101344CC5406CB3 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 8D99518E8E05FD856A952698 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; A5EA12562419390400E30FC3 /* FileUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileUtils.swift; sourceTree = ""; }; A5EA12572419390400E30FC3 /* UIImage+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIImage+Extras.swift"; sourceTree = ""; }; B596E4BC205657A500B46F03 /* APIHelperTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APIHelperTests.swift; sourceTree = ""; }; @@ -53,7 +47,6 @@ EAEC0BE31D4E330700C908A3 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = ""; }; EAEC0BE51D4E379000C908A3 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = ""; }; EAEC0BE71D4E38CB00C908A3 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; - EFD8AB05F53C74985527D117 /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -61,7 +54,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - B024164FBFF71BF644D4419A /* Pods_SwaggerClient.framework in Frameworks */, + A5782C732664FABF00CAA106 /* PetstoreClient in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -69,41 +62,26 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - B1D0246C8960F47A60098F37 /* Pods_SwaggerClientTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 55DC454FF5FFEF8A9CBC1CA3 /* Frameworks */ = { + A5782C712664FABE00CAA106 /* Frameworks */ = { isa = PBXGroup; children = ( - 177A58DD5CF63F2989335DCC /* Pods_SwaggerClient.framework */, - 6F96A0131101344CC5406CB3 /* Pods_SwaggerClientTests.framework */, ); name = Frameworks; sourceTree = ""; }; - CB19142D951AB5DD885404A8 /* Pods */ = { - isa = PBXGroup; - children = ( - 8D99518E8E05FD856A952698 /* Pods-SwaggerClient.debug.xcconfig */, - 2DEFA8828BD4E38FA5262F53 /* Pods-SwaggerClient.release.xcconfig */, - 4EF2021609D112A6F5AE0F55 /* Pods-SwaggerClientTests.debug.xcconfig */, - EFD8AB05F53C74985527D117 /* Pods-SwaggerClientTests.release.xcconfig */, - ); - name = Pods; - sourceTree = ""; - }; EAEC0BB51D4E30CE00C908A3 = { isa = PBXGroup; children = ( EAEC0BC01D4E30CE00C908A3 /* SwaggerClient */, EAEC0BD51D4E30CE00C908A3 /* SwaggerClientTests */, EAEC0BBF1D4E30CE00C908A3 /* Products */, - CB19142D951AB5DD885404A8 /* Pods */, - 55DC454FF5FFEF8A9CBC1CA3 /* Frameworks */, + A5782C712664FABE00CAA106 /* Frameworks */, ); sourceTree = ""; }; @@ -150,17 +128,18 @@ isa = PBXNativeTarget; buildConfigurationList = EAEC0BDB1D4E30CE00C908A3 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 898E536ECC2C4811DDDF67C1 /* [CP] Check Pods Manifest.lock */, EAEC0BBA1D4E30CE00C908A3 /* Sources */, EAEC0BBB1D4E30CE00C908A3 /* Frameworks */, EAEC0BBC1D4E30CE00C908A3 /* Resources */, - 8A7961360961F06AADAF17C9 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( ); name = SwaggerClient; + packageProductDependencies = ( + A5782C722664FABF00CAA106 /* PetstoreClient */, + ); productName = SwaggerClient; productReference = EAEC0BBE1D4E30CE00C908A3 /* SwaggerClient.app */; productType = "com.apple.product-type.application"; @@ -169,7 +148,6 @@ isa = PBXNativeTarget; buildConfigurationList = EAEC0BDE1D4E30CE00C908A3 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - 82CB35D52E274C6177DAC0DD /* [CP] Check Pods Manifest.lock */, EAEC0BCE1D4E30CE00C908A3 /* Sources */, EAEC0BCF1D4E30CE00C908A3 /* Frameworks */, EAEC0BD01D4E30CE00C908A3 /* Resources */, @@ -244,63 +222,6 @@ }; /* End PBXResourcesBuildPhase section */ -/* Begin PBXShellScriptBuildPhase section */ - 82CB35D52E274C6177DAC0DD /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClientTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 898E536ECC2C4811DDDF67C1 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClient-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 8A7961360961F06AADAF17C9 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/PetstoreClient/PetstoreClient.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PetstoreClient.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - /* Begin PBXSourcesBuildPhase section */ EAEC0BBA1D4E30CE00C908A3 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -456,7 +377,8 @@ IPHONEOS_DEPLOYMENT_TARGET = 9.3; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; SWIFT_VERSION = 4.2; VALIDATE_PRODUCT = YES; }; @@ -464,11 +386,13 @@ }; EAEC0BDC1D4E30CE00C908A3 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 8D99518E8E05FD856A952698 /* Pods-SwaggerClient.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -478,11 +402,13 @@ }; EAEC0BDD1D4E30CE00C908A3 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 2DEFA8828BD4E38FA5262F53 /* Pods-SwaggerClient.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -492,12 +418,15 @@ }; EAEC0BDF1D4E30CE00C908A3 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 4EF2021609D112A6F5AE0F55 /* Pods-SwaggerClientTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CLANG_ENABLE_MODULES = YES; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -508,12 +437,15 @@ }; EAEC0BE01D4E30CE00C908A3 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = EFD8AB05F53C74985527D117 /* Pods-SwaggerClientTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CLANG_ENABLE_MODULES = YES; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -552,6 +484,13 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCSwiftPackageProductDependency section */ + A5782C722664FABF00CAA106 /* PetstoreClient */ = { + isa = XCSwiftPackageProductDependency; + productName = PetstoreClient; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = EAEC0BB61D4E30CE00C908A3 /* Project object */; } diff --git a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata index 9b3fa18954f7..00ec9b53a7f1 100644 --- a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata +++ b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata @@ -2,9 +2,9 @@ + location = "group:.."> + location = "group:SwaggerClient.xcodeproj"> diff --git a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 000000000000..d384b276b4bc --- /dev/null +++ b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md index 543869c0d2e0..553a46281aa0 100644 --- a/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md @@ -379,7 +379,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) diff --git a/samples/client/petstore/swift5/combineLibrary/project.yml b/samples/client/petstore/swift5/combineLibrary/project.yml index 8e7102001b8d..0493cf65896e 100644 --- a/samples/client/petstore/swift5/combineLibrary/project.yml +++ b/samples/client/petstore/swift5/combineLibrary/project.yml @@ -11,4 +11,5 @@ targets: settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - + dependencies: + - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/default/.openapi-generator/FILES b/samples/client/petstore/swift5/default/.openapi-generator/FILES index c81943baf2af..205dadc060a1 100644 --- a/samples/client/petstore/swift5/default/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/default/.openapi-generator/FILES @@ -16,13 +16,22 @@ PetstoreClient/Classes/OpenAPIs/Extensions.swift PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift PetstoreClient/Classes/OpenAPIs/Models.swift +PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesAnyType.swift +PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesArray.swift +PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesBoolean.swift PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesInteger.swift +PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesNumber.swift +PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesObject.swift +PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesString.swift PetstoreClient/Classes/OpenAPIs/Models/Animal.swift PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +PetstoreClient/Classes/OpenAPIs/Models/BigCat.swift +PetstoreClient/Classes/OpenAPIs/Models/BigCatAllOf.swift PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift PetstoreClient/Classes/OpenAPIs/Models/Cat.swift PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -56,11 +65,19 @@ PetstoreClient/Classes/OpenAPIs/Models/Tag.swift PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift PetstoreClient/Classes/OpenAPIs/Models/User.swift +PetstoreClient/Classes/OpenAPIs/Models/XmlItem.swift PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift README.md +docs/AdditionalPropertiesAnyType.md +docs/AdditionalPropertiesArray.md +docs/AdditionalPropertiesBoolean.md docs/AdditionalPropertiesClass.md +docs/AdditionalPropertiesInteger.md +docs/AdditionalPropertiesNumber.md +docs/AdditionalPropertiesObject.md +docs/AdditionalPropertiesString.md docs/Animal.md docs/AnimalFarm.md docs/AnotherFakeAPI.md @@ -68,6 +85,8 @@ docs/ApiResponse.md docs/ArrayOfArrayOfNumberOnly.md docs/ArrayOfNumberOnly.md docs/ArrayTest.md +docs/BigCat.md +docs/BigCatAllOf.md docs/Capitalization.md docs/Cat.md docs/CatAllOf.md @@ -106,5 +125,6 @@ docs/TypeHolderDefault.md docs/TypeHolderExample.md docs/User.md docs/UserAPI.md +docs/XmlItem.md git_push.sh project.yml diff --git a/samples/client/petstore/swift5/default/.openapi-generator/VERSION b/samples/client/petstore/swift5/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/swift5/default/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/default/Cartfile b/samples/client/petstore/swift5/default/Cartfile index 8b137891791f..843f7adc7794 100644 --- a/samples/client/petstore/swift5/default/Cartfile +++ b/samples/client/petstore/swift5/default/Cartfile @@ -1 +1,2 @@ +github "Flight-School/AnyCodable" ~> 0.6.0 diff --git a/samples/client/petstore/swift5/default/Package.resolved b/samples/client/petstore/swift5/default/Package.resolved new file mode 100644 index 000000000000..d384b276b4bc --- /dev/null +++ b/samples/client/petstore/swift5/default/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/default/Package.swift b/samples/client/petstore/swift5/default/Package.swift index b7fe4734aa8a..5cde507bdcf9 100644 --- a/samples/client/petstore/swift5/default/Package.swift +++ b/samples/client/petstore/swift5/default/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.0 +// swift-tools-version:5.1 import PackageDescription @@ -19,13 +19,14 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.6.0")), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "PetstoreClient", - dependencies: [], + dependencies: ["AnyCodable", ], path: "PetstoreClient/Classes" ), ] diff --git a/samples/client/petstore/swift5/default/PetstoreClient.podspec b/samples/client/petstore/swift5/default/PetstoreClient.podspec index b61285f6b25e..60f05891b241 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/default/PetstoreClient.podspec @@ -11,4 +11,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.0' end diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs.swift index dbdab491ff7d..01bc6ff0d8d0 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,7 +6,10 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 24b0015a270d..542fb6f69ba8 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -15,7 +15,7 @@ open class AnotherFakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -35,10 +35,10 @@ open class AnotherFakeAPI { */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -46,9 +46,9 @@ open class AnotherFakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 58c4b8a093ce..eb6d1e67c4f5 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -8,13 +8,56 @@ import Foundation open class FakeAPI { + /** + creates an XmlItem + + - parameter xmlItem: (body) XmlItem Body + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func createXmlItem(xmlItem: XmlItem, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createXmlItemWithRequestBuilder(xmlItem: xmlItem).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + creates an XmlItem + - POST /fake/create_xml_item + - this route creates an XmlItem + - parameter xmlItem: (body) XmlItem Body + - returns: RequestBuilder + */ + open class func createXmlItemWithRequestBuilder(xmlItem: XmlItem) -> RequestBuilder { + let path = "/fake/create_xml_item" + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: xmlItem) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + /** - parameter body: (body) Input boolean as post body (optional) - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -33,10 +76,10 @@ open class FakeAPI { */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -44,9 +87,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -55,7 +98,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -74,10 +117,10 @@ open class FakeAPI { */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -85,9 +128,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -96,7 +139,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -115,10 +158,10 @@ open class FakeAPI { */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -126,9 +169,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -137,7 +180,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -156,10 +199,10 @@ open class FakeAPI { */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -167,9 +210,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -178,7 +221,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -197,10 +240,10 @@ open class FakeAPI { */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -208,9 +251,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -220,7 +263,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -239,11 +282,11 @@ open class FakeAPI { */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) @@ -253,9 +296,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -265,7 +308,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -285,10 +328,10 @@ open class FakeAPI { */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -296,9 +339,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -321,7 +364,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -357,7 +400,7 @@ open class FakeAPI { */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), @@ -378,7 +421,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -386,9 +429,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -472,7 +515,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -499,7 +542,7 @@ open class FakeAPI { */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), @@ -508,8 +551,8 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), @@ -524,9 +567,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -541,7 +584,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -566,11 +609,11 @@ open class FakeAPI { */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), @@ -584,9 +627,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -596,7 +639,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -615,10 +658,10 @@ open class FakeAPI { */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -626,9 +669,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -639,7 +682,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -659,7 +702,7 @@ open class FakeAPI { */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), @@ -668,7 +711,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -676,9 +719,65 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + + - parameter pipe: (query) + - parameter ioutil: (query) + - parameter http: (query) + - parameter url: (query) + - parameter context: (query) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testQueryParameterCollectionFormat(pipe: [String], ioutil: [String], http: [String], url: [String], context: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testQueryParameterCollectionFormatWithRequestBuilder(pipe: pipe, ioutil: ioutil, http: http, url: url, context: context).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - PUT /fake/test-query-paramters + - To test the collection format in query parameters + - parameter pipe: (query) + - parameter ioutil: (query) + - parameter http: (query) + - parameter url: (query) + - parameter context: (query) + - returns: RequestBuilder + */ + open class func testQueryParameterCollectionFormatWithRequestBuilder(pipe: [String], ioutil: [String], http: [String], url: [String], context: [String]) -> RequestBuilder { + let path = "/fake/test-query-paramters" + let URLString = PetstoreClient.basePath + path + let parameters: [String: Any]? = nil + + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "pipe": pipe.encodeToJSON(), + "ioutil": ioutil.encodeToJSON(), + "http": http.encodeToJSON(), + "url": url.encodeToJSON(), + "context": context.encodeToJSON(), + ]) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index fb3bb8ce00a7..fd7d845d3406 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -15,7 +15,7 @@ open class FakeClassnameTags123API { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -38,10 +38,10 @@ open class FakeClassnameTags123API { */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ open class FakeClassnameTags123API { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 5cd3629127bf..fa8620ba081c 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -15,7 +15,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -37,10 +37,10 @@ open class PetAPI { */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -48,9 +48,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -61,7 +61,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -87,10 +87,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), @@ -98,9 +98,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -119,7 +119,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -142,11 +142,11 @@ open class PetAPI { */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) @@ -156,9 +156,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -169,7 +169,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByTags(tags: Set, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Set?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -188,16 +188,16 @@ open class PetAPI { - type: oauth2 - name: petstore_auth - parameter tags: (query) Tags to filter by - - returns: RequestBuilder<[Pet]> + - returns: RequestBuilder> */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByTagsWithRequestBuilder(tags: Set) -> RequestBuilder> { let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) @@ -207,9 +207,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -219,7 +219,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -245,10 +245,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -256,9 +256,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -268,7 +268,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -290,10 +290,10 @@ open class PetAPI { */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -301,9 +301,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -315,7 +315,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -342,7 +342,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), @@ -351,7 +351,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -359,9 +359,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -373,7 +373,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -400,7 +400,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), @@ -409,7 +409,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -417,9 +417,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -431,7 +431,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -458,7 +458,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), @@ -467,7 +467,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -475,9 +475,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 95adcc200ae0..c80d4286b536 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -15,7 +15,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -38,10 +38,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -60,7 +60,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -82,10 +82,10 @@ open class StoreAPI { */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -93,9 +93,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -105,7 +105,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -128,10 +128,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -139,9 +139,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -151,7 +151,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -170,10 +170,10 @@ open class StoreAPI { */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -181,9 +181,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index cfd30068a9db..542dc212bd1b 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -15,7 +15,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -35,10 +35,10 @@ open class UserAPI { */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { let path = "/user" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -46,9 +46,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -58,7 +58,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -77,10 +77,10 @@ open class UserAPI { */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -88,9 +88,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -100,7 +100,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -119,10 +119,10 @@ open class UserAPI { */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -130,9 +130,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -142,7 +142,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -165,10 +165,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -176,9 +176,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -188,7 +188,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -210,10 +210,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -221,9 +221,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -234,7 +234,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -255,11 +255,11 @@ open class UserAPI { */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) @@ -270,9 +270,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -281,7 +281,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -299,10 +299,10 @@ open class UserAPI { */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -310,9 +310,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -323,7 +323,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -347,10 +347,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -358,9 +358,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 93ed6b90b376..e23035dde30e 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,6 +5,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -52,6 +55,12 @@ extension Array: JSONEncodable { } } +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + extension Dictionary: JSONEncodable { func encodeToJSON() -> Any { var dictionary = [AnyHashable: Any]() diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesAnyType.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesAnyType.swift new file mode 100644 index 000000000000..96d07d1ef30c --- /dev/null +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesAnyType.swift @@ -0,0 +1,60 @@ +// +// AdditionalPropertiesAnyType.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AdditionalPropertiesAnyType: Codable, Hashable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + + public var additionalProperties: [String: AnyCodable] = [:] + + public subscript(key: String) -> AnyCodable? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + name = try container.decodeIfPresent(String.self, forKey: .name) + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(AnyCodable.self, excludedKeys: nonAdditionalPropertyKeys) + } +} diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesArray.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesArray.swift new file mode 100644 index 000000000000..106e4dd6de18 --- /dev/null +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesArray.swift @@ -0,0 +1,60 @@ +// +// AdditionalPropertiesArray.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AdditionalPropertiesArray: Codable, Hashable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + + public var additionalProperties: [String: [AnyCodable]] = [:] + + public subscript(key: String) -> [AnyCodable]? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + name = try container.decodeIfPresent(String.self, forKey: .name) + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap([AnyCodable].self, excludedKeys: nonAdditionalPropertyKeys) + } +} diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesBoolean.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesBoolean.swift new file mode 100644 index 000000000000..bfbd7a5f20d8 --- /dev/null +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesBoolean.swift @@ -0,0 +1,60 @@ +// +// AdditionalPropertiesBoolean.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AdditionalPropertiesBoolean: Codable, Hashable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + + public var additionalProperties: [String: Bool] = [:] + + public subscript(key: String) -> Bool? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + name = try container.decodeIfPresent(String.self, forKey: .name) + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + } +} diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 733b7bc51594..614e09633539 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,20 +6,66 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct AdditionalPropertiesClass: Codable, Hashable { public var mapString: [String: String]? + public var mapNumber: [String: Double]? + public var mapInteger: [String: Int]? + public var mapBoolean: [String: Bool]? + public var mapArrayInteger: [String: [Int]]? + public var mapArrayAnytype: [String: [AnyCodable]]? public var mapMapString: [String: [String: String]]? + public var mapMapAnytype: [String: [String: AnyCodable]]? + public var anytype1: AnyCodable? + public var anytype2: AnyCodable? + public var anytype3: AnyCodable? - public init(mapString: [String: String]? = nil, mapMapString: [String: [String: String]]? = nil) { + public init(mapString: [String: String]? = nil, mapNumber: [String: Double]? = nil, mapInteger: [String: Int]? = nil, mapBoolean: [String: Bool]? = nil, mapArrayInteger: [String: [Int]]? = nil, mapArrayAnytype: [String: [AnyCodable]]? = nil, mapMapString: [String: [String: String]]? = nil, mapMapAnytype: [String: [String: AnyCodable]]? = nil, anytype1: AnyCodable? = nil, anytype2: AnyCodable? = nil, anytype3: AnyCodable? = nil) { self.mapString = mapString + self.mapNumber = mapNumber + self.mapInteger = mapInteger + self.mapBoolean = mapBoolean + self.mapArrayInteger = mapArrayInteger + self.mapArrayAnytype = mapArrayAnytype self.mapMapString = mapMapString + self.mapMapAnytype = mapMapAnytype + self.anytype1 = anytype1 + self.anytype2 = anytype2 + self.anytype3 = anytype3 } public enum CodingKeys: String, CodingKey, CaseIterable { case mapString = "map_string" + case mapNumber = "map_number" + case mapInteger = "map_integer" + case mapBoolean = "map_boolean" + case mapArrayInteger = "map_array_integer" + case mapArrayAnytype = "map_array_anytype" case mapMapString = "map_map_string" + case mapMapAnytype = "map_map_anytype" + case anytype1 = "anytype_1" + case anytype2 = "anytype_2" + case anytype3 = "anytype_3" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapString, forKey: .mapString) + try container.encodeIfPresent(mapNumber, forKey: .mapNumber) + try container.encodeIfPresent(mapInteger, forKey: .mapInteger) + try container.encodeIfPresent(mapBoolean, forKey: .mapBoolean) + try container.encodeIfPresent(mapArrayInteger, forKey: .mapArrayInteger) + try container.encodeIfPresent(mapArrayAnytype, forKey: .mapArrayAnytype) + try container.encodeIfPresent(mapMapString, forKey: .mapMapString) + try container.encodeIfPresent(mapMapAnytype, forKey: .mapMapAnytype) + try container.encodeIfPresent(anytype1, forKey: .anytype1) + try container.encodeIfPresent(anytype2, forKey: .anytype2) + try container.encodeIfPresent(anytype3, forKey: .anytype3) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesInteger.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesInteger.swift new file mode 100644 index 000000000000..b57691746cad --- /dev/null +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesInteger.swift @@ -0,0 +1,60 @@ +// +// AdditionalPropertiesInteger.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AdditionalPropertiesInteger: Codable, Hashable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + + public var additionalProperties: [String: Int] = [:] + + public subscript(key: String) -> Int? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + name = try container.decodeIfPresent(String.self, forKey: .name) + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Int.self, excludedKeys: nonAdditionalPropertyKeys) + } +} diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesNumber.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesNumber.swift new file mode 100644 index 000000000000..fd6a6a52d064 --- /dev/null +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesNumber.swift @@ -0,0 +1,60 @@ +// +// AdditionalPropertiesNumber.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AdditionalPropertiesNumber: Codable, Hashable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + + public var additionalProperties: [String: Double] = [:] + + public subscript(key: String) -> Double? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + name = try container.decodeIfPresent(String.self, forKey: .name) + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Double.self, excludedKeys: nonAdditionalPropertyKeys) + } +} diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesObject.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesObject.swift new file mode 100644 index 000000000000..675a07ca0c1e --- /dev/null +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesObject.swift @@ -0,0 +1,60 @@ +// +// AdditionalPropertiesObject.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AdditionalPropertiesObject: Codable, Hashable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + + public var additionalProperties: [String: [String: AnyCodable]] = [:] + + public subscript(key: String) -> [String: AnyCodable]? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + name = try container.decodeIfPresent(String.self, forKey: .name) + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap([String: AnyCodable].self, excludedKeys: nonAdditionalPropertyKeys) + } +} diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesString.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesString.swift new file mode 100644 index 000000000000..df5aa8b69533 --- /dev/null +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesString.swift @@ -0,0 +1,60 @@ +// +// AdditionalPropertiesString.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AdditionalPropertiesString: Codable, Hashable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + + public var additionalProperties: [String: String] = [:] + + public subscript(key: String) -> String? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + name = try container.decodeIfPresent(String.self, forKey: .name) + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(String.self, excludedKeys: nonAdditionalPropertyKeys) + } +} diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index e57c8b471765..157cca1d227b 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Animal: Codable, Hashable { @@ -17,4 +20,16 @@ public struct Animal: Codable, Hashable { self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index e09b0e9efdc8..a0b09cb97615 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,5 +6,8 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 630992f6231e..8607cbef1a33 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ApiResponse: Codable, Hashable { @@ -19,4 +22,18 @@ public struct ApiResponse: Codable, Hashable { self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { + case code + case type + case message + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(code, forKey: .code) + try container.encodeIfPresent(type, forKey: .type) + try container.encodeIfPresent(message, forKey: .message) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 4710793fc9a6..f3f161b44c1c 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { case arrayArrayNumber = "ArrayArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index a41968d9b199..d62de957472a 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayOfNumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct ArrayOfNumberOnly: Codable, Hashable { case arrayNumber = "ArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index f442ea725451..360d50d027f1 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayTest: Codable, Hashable { @@ -25,4 +28,12 @@ public struct ArrayTest: Codable, Hashable { case arrayArrayOfModel = "array_array_of_model" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayOfString, forKey: .arrayOfString) + try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) + try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/BigCat.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/BigCat.swift new file mode 100644 index 000000000000..3284de5040e7 --- /dev/null +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/BigCat.swift @@ -0,0 +1,37 @@ +// +// BigCat.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct BigCat: Codable, Hashable { + + public enum Kind: String, Codable, CaseIterable { + case lions = "lions" + case tigers = "tigers" + case leopards = "leopards" + case jaguars = "jaguars" + } + public var kind: Kind? + + public init(kind: Kind? = nil) { + self.kind = kind + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case kind + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(kind, forKey: .kind) + } +} diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/BigCatAllOf.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/BigCatAllOf.swift new file mode 100644 index 000000000000..7d2d24898493 --- /dev/null +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/BigCatAllOf.swift @@ -0,0 +1,37 @@ +// +// BigCatAllOf.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct BigCatAllOf: Codable, Hashable { + + public enum Kind: String, Codable, CaseIterable { + case lions = "lions" + case tigers = "tigers" + case leopards = "leopards" + case jaguars = "jaguars" + } + public var kind: Kind? + + public init(kind: Kind? = nil) { + self.kind = kind + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case kind + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(kind, forKey: .kind) + } +} diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index 44b50bbe0063..f0781a9cb738 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Capitalization: Codable, Hashable { @@ -35,4 +38,15 @@ public struct Capitalization: Codable, Hashable { case ATT_NAME } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(smallCamel, forKey: .smallCamel) + try container.encodeIfPresent(capitalCamel, forKey: .capitalCamel) + try container.encodeIfPresent(smallSnake, forKey: .smallSnake) + try container.encodeIfPresent(capitalSnake, forKey: .capitalSnake) + try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) + try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index c6bf4460da6e..d5519760387a 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Cat: Codable, Hashable { @@ -19,4 +22,18 @@ public struct Cat: Codable, Hashable { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index f9484f9bc8fd..8312680deb37 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct CatAllOf: Codable, Hashable { @@ -15,4 +18,14 @@ public struct CatAllOf: Codable, Hashable { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 6a19bb02d0df..24dd89221d0c 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Category: Codable, Hashable { @@ -17,4 +20,16 @@ public struct Category: Codable, Hashable { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encode(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index 5c8e8882831f..03bf63e4cad1 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model with \"_class\" property */ public struct ClassModel: Codable, Hashable { @@ -16,4 +19,14 @@ public struct ClassModel: Codable, Hashable { self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { + case _class + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_class, forKey: ._class) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 1464b047c06a..596048780439 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Client: Codable, Hashable { @@ -15,4 +18,14 @@ public struct Client: Codable, Hashable { self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { + case client + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(client, forKey: .client) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index 5aed7834d537..4ada3ceb605a 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Dog: Codable, Hashable { @@ -19,4 +22,18 @@ public struct Dog: Codable, Hashable { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 716776261d30..f6c3d287301d 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct DogAllOf: Codable, Hashable { @@ -15,4 +18,14 @@ public struct DogAllOf: Codable, Hashable { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index aa13aa59f86a..0e0aad42abe6 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct EnumArrays: Codable, Hashable { @@ -30,4 +33,11 @@ public struct EnumArrays: Codable, Hashable { case arrayEnum = "array_enum" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justSymbol, forKey: .justSymbol) + try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index d4029d73f8af..6ea2895aee53 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 8b62febdc959..9e44926be9b8 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct EnumTest: Codable, Hashable { @@ -49,4 +52,14 @@ public struct EnumTest: Codable, Hashable { case outerEnum } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(enumString, forKey: .enumString) + try container.encode(enumStringRequired, forKey: .enumStringRequired) + try container.encodeIfPresent(enumInteger, forKey: .enumInteger) + try container.encodeIfPresent(enumNumber, forKey: .enumNumber) + try container.encodeIfPresent(outerEnum, forKey: .outerEnum) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/File.swift index aa14d762394d..11694b2ca59b 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Must be named `File` for test. */ public struct File: Codable, Hashable { @@ -17,4 +20,14 @@ public struct File: Codable, Hashable { self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { + case sourceURI + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(sourceURI, forKey: .sourceURI) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index 85987709776e..6aa85d8eecf9 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FileSchemaTestClass: Codable, Hashable { @@ -17,4 +20,16 @@ public struct FileSchemaTestClass: Codable, Hashable { self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { + case file + case files + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(file, forKey: .file) + try container.encodeIfPresent(files, forKey: .files) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index f09cb471b360..60eafb2febe1 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FormatTest: Codable, Hashable { @@ -22,8 +25,9 @@ public struct FormatTest: Codable, Hashable { public var dateTime: Date? public var uuid: UUID? public var password: String + public var bigDecimal: Decimal? - public init(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double? = nil, string: String? = nil, byte: Data, binary: URL? = nil, date: Date, dateTime: Date? = nil, uuid: UUID? = nil, password: String) { + public init(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double? = nil, string: String? = nil, byte: Data, binary: URL? = nil, date: Date, dateTime: Date? = nil, uuid: UUID? = nil, password: String, bigDecimal: Decimal? = nil) { self.integer = integer self.int32 = int32 self.int64 = int64 @@ -37,6 +41,43 @@ public struct FormatTest: Codable, Hashable { self.dateTime = dateTime self.uuid = uuid self.password = password + self.bigDecimal = bigDecimal } + public enum CodingKeys: String, CodingKey, CaseIterable { + case integer + case int32 + case int64 + case number + case float + case double + case string + case byte + case binary + case date + case dateTime + case uuid + case password + case bigDecimal = "BigDecimal" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(integer, forKey: .integer) + try container.encodeIfPresent(int32, forKey: .int32) + try container.encodeIfPresent(int64, forKey: .int64) + try container.encode(number, forKey: .number) + try container.encodeIfPresent(float, forKey: .float) + try container.encodeIfPresent(double, forKey: .double) + try container.encodeIfPresent(string, forKey: .string) + try container.encode(byte, forKey: .byte) + try container.encodeIfPresent(binary, forKey: .binary) + try container.encode(date, forKey: .date) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encode(password, forKey: .password) + try container.encodeIfPresent(bigDecimal, forKey: .bigDecimal) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index 03d35274a4ee..cb1a7456a7df 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct HasOnlyReadOnly: Codable, Hashable { @@ -17,4 +20,16 @@ public struct HasOnlyReadOnly: Codable, Hashable { self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case foo + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(foo, forKey: .foo) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/List.swift index f8f08e4c6c44..8ecdd3b02339 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct List: Codable, Hashable { @@ -19,4 +22,10 @@ public struct List: Codable, Hashable { case _123list = "123-list" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_123list, forKey: ._123list) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index bd4e7b97e81b..0ff74ed8400e 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct MapTest: Codable, Hashable { @@ -32,4 +35,13 @@ public struct MapTest: Codable, Hashable { case indirectMap = "indirect_map" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapMapOfString, forKey: .mapMapOfString) + try container.encodeIfPresent(mapOfEnumString, forKey: .mapOfEnumString) + try container.encodeIfPresent(directMap, forKey: .directMap) + try container.encodeIfPresent(indirectMap, forKey: .indirectMap) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index 80c1781a2bfc..58a0a54ca090 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { @@ -19,4 +22,18 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { + case uuid + case dateTime + case map + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(map, forKey: .map) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index d36d4e27352a..0f59769954f1 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name starting with number */ public struct Model200Response: Codable, Hashable { @@ -23,4 +26,11 @@ public struct Model200Response: Codable, Hashable { case _class = "class" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(_class, forKey: ._class) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 49cc57544179..d88c94f05c95 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name same as property name */ public struct Name: Codable, Hashable { @@ -29,4 +32,13 @@ public struct Name: Codable, Hashable { case _123number = "123Number" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encodeIfPresent(snakeCase, forKey: .snakeCase) + try container.encodeIfPresent(property, forKey: .property) + try container.encodeIfPresent(_123number, forKey: ._123number) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 6b024294e288..0f05482b9b7c 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct NumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct NumberOnly: Codable, Hashable { case justNumber = "JustNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justNumber, forKey: .justNumber) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 8ef7cb79e2c8..100d6b71fed4 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Order: Codable, Hashable { @@ -31,4 +34,24 @@ public struct Order: Codable, Hashable { self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case petId + case quantity + case shipDate + case status + case complete + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(petId, forKey: .petId) + try container.encodeIfPresent(quantity, forKey: .quantity) + try container.encodeIfPresent(shipDate, forKey: .shipDate) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(complete, forKey: .complete) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 9865764ff9bb..15a4e4a15b6e 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct OuterComposite: Codable, Hashable { @@ -25,4 +28,12 @@ public struct OuterComposite: Codable, Hashable { case myBoolean = "my_boolean" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(myNumber, forKey: .myNumber) + try container.encodeIfPresent(myString, forKey: .myString) + try container.encodeIfPresent(myBoolean, forKey: .myBoolean) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index c3b778cbbed4..76c34b3c2ce6 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 1bc823d3e960..63b32ba8f11b 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Pet: Codable, Hashable { @@ -17,12 +20,12 @@ public struct Pet: Codable, Hashable { public var id: Int64? public var category: Category? public var name: String - public var photoUrls: [String] + public var photoUrls: Set public var tags: [Tag]? /** pet status in the store */ public var status: Status? - public init(id: Int64? = nil, category: Category? = nil, name: String, photoUrls: [String], tags: [Tag]? = nil, status: Status? = nil) { + public init(id: Int64? = nil, category: Category? = nil, name: String, photoUrls: Set, tags: [Tag]? = nil, status: Status? = nil) { self.id = id self.category = category self.name = name @@ -31,4 +34,24 @@ public struct Pet: Codable, Hashable { self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case category + case name + case photoUrls + case tags + case status + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(category, forKey: .category) + try container.encode(name, forKey: .name) + try container.encode(photoUrls, forKey: .photoUrls) + try container.encodeIfPresent(tags, forKey: .tags) + try container.encodeIfPresent(status, forKey: .status) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 03b5b0dbf02b..6426deedf637 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ReadOnlyFirst: Codable, Hashable { @@ -17,4 +20,16 @@ public struct ReadOnlyFirst: Codable, Hashable { self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case baz + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(baz, forKey: .baz) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 5f539f461843..777c241bc0c0 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing reserved words */ public struct Return: Codable, Hashable { @@ -20,4 +23,10 @@ public struct Return: Codable, Hashable { case _return = "return" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_return, forKey: ._return) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index cb82d2ae3adc..b677523a7491 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct SpecialModelName: Codable, Hashable { @@ -19,4 +22,10 @@ public struct SpecialModelName: Codable, Hashable { case specialPropertyName = "$special[property.name]" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 77ab81f5f341..f575c9df65ca 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,9 +6,16 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct StringBooleanMap: Codable, Hashable { + + public enum CodingKeys: CodingKey, CaseIterable { + } + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -27,19 +34,18 @@ public struct StringBooleanMap: Codable, Hashable { // Encodable protocol methods public func encode(to encoder: Encoder) throws { - - var container = encoder.container(keyedBy: String.self) - - try container.encodeMap(additionalProperties) + var container = encoder.container(keyedBy: CodingKeys.self) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) } // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 8b8e24fc39c0..cd5acc827db7 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Tag: Codable, Hashable { @@ -17,4 +20,16 @@ public struct Tag: Codable, Hashable { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index f1920ef37788..341c9b4b8c2e 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct TypeHolderDefault: Codable, Hashable { @@ -31,4 +34,14 @@ public struct TypeHolderDefault: Codable, Hashable { case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index 1a23c1b486b8..7a0b4dda2a59 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,18 +6,23 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct TypeHolderExample: Codable, Hashable { public var stringItem: String public var numberItem: Double + public var floatItem: Float public var integerItem: Int public var boolItem: Bool public var arrayItem: [Int] - public init(stringItem: String, numberItem: Double, integerItem: Int, boolItem: Bool, arrayItem: [Int]) { + public init(stringItem: String, numberItem: Double, floatItem: Float, integerItem: Int, boolItem: Bool, arrayItem: [Int]) { self.stringItem = stringItem self.numberItem = numberItem + self.floatItem = floatItem self.integerItem = integerItem self.boolItem = boolItem self.arrayItem = arrayItem @@ -26,9 +31,21 @@ public struct TypeHolderExample: Codable, Hashable { public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" + case floatItem = "float_item" case integerItem = "integer_item" case boolItem = "bool_item" case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(floatItem, forKey: .floatItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/User.swift index f3b4f6bb958a..9f3ded8fcd93 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct User: Codable, Hashable { @@ -30,4 +33,28 @@ public struct User: Codable, Hashable { self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case username + case firstName + case lastName + case email + case password + case phone + case userStatus + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(username, forKey: .username) + try container.encodeIfPresent(firstName, forKey: .firstName) + try container.encodeIfPresent(lastName, forKey: .lastName) + try container.encodeIfPresent(email, forKey: .email) + try container.encodeIfPresent(password, forKey: .password) + try container.encodeIfPresent(phone, forKey: .phone) + try container.encodeIfPresent(userStatus, forKey: .userStatus) + } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/XmlItem.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/XmlItem.swift new file mode 100644 index 000000000000..997e2eebce5d --- /dev/null +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/XmlItem.swift @@ -0,0 +1,143 @@ +// +// XmlItem.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct XmlItem: Codable, Hashable { + + public var attributeString: String? + public var attributeNumber: Double? + public var attributeInteger: Int? + public var attributeBoolean: Bool? + public var wrappedArray: [Int]? + public var nameString: String? + public var nameNumber: Double? + public var nameInteger: Int? + public var nameBoolean: Bool? + public var nameArray: [Int]? + public var nameWrappedArray: [Int]? + public var prefixString: String? + public var prefixNumber: Double? + public var prefixInteger: Int? + public var prefixBoolean: Bool? + public var prefixArray: [Int]? + public var prefixWrappedArray: [Int]? + public var namespaceString: String? + public var namespaceNumber: Double? + public var namespaceInteger: Int? + public var namespaceBoolean: Bool? + public var namespaceArray: [Int]? + public var namespaceWrappedArray: [Int]? + public var prefixNsString: String? + public var prefixNsNumber: Double? + public var prefixNsInteger: Int? + public var prefixNsBoolean: Bool? + public var prefixNsArray: [Int]? + public var prefixNsWrappedArray: [Int]? + + public init(attributeString: String? = nil, attributeNumber: Double? = nil, attributeInteger: Int? = nil, attributeBoolean: Bool? = nil, wrappedArray: [Int]? = nil, nameString: String? = nil, nameNumber: Double? = nil, nameInteger: Int? = nil, nameBoolean: Bool? = nil, nameArray: [Int]? = nil, nameWrappedArray: [Int]? = nil, prefixString: String? = nil, prefixNumber: Double? = nil, prefixInteger: Int? = nil, prefixBoolean: Bool? = nil, prefixArray: [Int]? = nil, prefixWrappedArray: [Int]? = nil, namespaceString: String? = nil, namespaceNumber: Double? = nil, namespaceInteger: Int? = nil, namespaceBoolean: Bool? = nil, namespaceArray: [Int]? = nil, namespaceWrappedArray: [Int]? = nil, prefixNsString: String? = nil, prefixNsNumber: Double? = nil, prefixNsInteger: Int? = nil, prefixNsBoolean: Bool? = nil, prefixNsArray: [Int]? = nil, prefixNsWrappedArray: [Int]? = nil) { + self.attributeString = attributeString + self.attributeNumber = attributeNumber + self.attributeInteger = attributeInteger + self.attributeBoolean = attributeBoolean + self.wrappedArray = wrappedArray + self.nameString = nameString + self.nameNumber = nameNumber + self.nameInteger = nameInteger + self.nameBoolean = nameBoolean + self.nameArray = nameArray + self.nameWrappedArray = nameWrappedArray + self.prefixString = prefixString + self.prefixNumber = prefixNumber + self.prefixInteger = prefixInteger + self.prefixBoolean = prefixBoolean + self.prefixArray = prefixArray + self.prefixWrappedArray = prefixWrappedArray + self.namespaceString = namespaceString + self.namespaceNumber = namespaceNumber + self.namespaceInteger = namespaceInteger + self.namespaceBoolean = namespaceBoolean + self.namespaceArray = namespaceArray + self.namespaceWrappedArray = namespaceWrappedArray + self.prefixNsString = prefixNsString + self.prefixNsNumber = prefixNsNumber + self.prefixNsInteger = prefixNsInteger + self.prefixNsBoolean = prefixNsBoolean + self.prefixNsArray = prefixNsArray + self.prefixNsWrappedArray = prefixNsWrappedArray + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case attributeString = "attribute_string" + case attributeNumber = "attribute_number" + case attributeInteger = "attribute_integer" + case attributeBoolean = "attribute_boolean" + case wrappedArray = "wrapped_array" + case nameString = "name_string" + case nameNumber = "name_number" + case nameInteger = "name_integer" + case nameBoolean = "name_boolean" + case nameArray = "name_array" + case nameWrappedArray = "name_wrapped_array" + case prefixString = "prefix_string" + case prefixNumber = "prefix_number" + case prefixInteger = "prefix_integer" + case prefixBoolean = "prefix_boolean" + case prefixArray = "prefix_array" + case prefixWrappedArray = "prefix_wrapped_array" + case namespaceString = "namespace_string" + case namespaceNumber = "namespace_number" + case namespaceInteger = "namespace_integer" + case namespaceBoolean = "namespace_boolean" + case namespaceArray = "namespace_array" + case namespaceWrappedArray = "namespace_wrapped_array" + case prefixNsString = "prefix_ns_string" + case prefixNsNumber = "prefix_ns_number" + case prefixNsInteger = "prefix_ns_integer" + case prefixNsBoolean = "prefix_ns_boolean" + case prefixNsArray = "prefix_ns_array" + case prefixNsWrappedArray = "prefix_ns_wrapped_array" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(attributeString, forKey: .attributeString) + try container.encodeIfPresent(attributeNumber, forKey: .attributeNumber) + try container.encodeIfPresent(attributeInteger, forKey: .attributeInteger) + try container.encodeIfPresent(attributeBoolean, forKey: .attributeBoolean) + try container.encodeIfPresent(wrappedArray, forKey: .wrappedArray) + try container.encodeIfPresent(nameString, forKey: .nameString) + try container.encodeIfPresent(nameNumber, forKey: .nameNumber) + try container.encodeIfPresent(nameInteger, forKey: .nameInteger) + try container.encodeIfPresent(nameBoolean, forKey: .nameBoolean) + try container.encodeIfPresent(nameArray, forKey: .nameArray) + try container.encodeIfPresent(nameWrappedArray, forKey: .nameWrappedArray) + try container.encodeIfPresent(prefixString, forKey: .prefixString) + try container.encodeIfPresent(prefixNumber, forKey: .prefixNumber) + try container.encodeIfPresent(prefixInteger, forKey: .prefixInteger) + try container.encodeIfPresent(prefixBoolean, forKey: .prefixBoolean) + try container.encodeIfPresent(prefixArray, forKey: .prefixArray) + try container.encodeIfPresent(prefixWrappedArray, forKey: .prefixWrappedArray) + try container.encodeIfPresent(namespaceString, forKey: .namespaceString) + try container.encodeIfPresent(namespaceNumber, forKey: .namespaceNumber) + try container.encodeIfPresent(namespaceInteger, forKey: .namespaceInteger) + try container.encodeIfPresent(namespaceBoolean, forKey: .namespaceBoolean) + try container.encodeIfPresent(namespaceArray, forKey: .namespaceArray) + try container.encodeIfPresent(namespaceWrappedArray, forKey: .namespaceWrappedArray) + try container.encodeIfPresent(prefixNsString, forKey: .prefixNsString) + try container.encodeIfPresent(prefixNsNumber, forKey: .prefixNsNumber) + try container.encodeIfPresent(prefixNsInteger, forKey: .prefixNsInteger) + try container.encodeIfPresent(prefixNsBoolean, forKey: .prefixNsBoolean) + try container.encodeIfPresent(prefixNsArray, forKey: .prefixNsArray) + try container.encodeIfPresent(prefixNsWrappedArray, forKey: .prefixNsWrappedArray) + } +} diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 52b2071ec1aa..774c0427eaa2 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,7 +93,7 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/default/README.md b/samples/client/petstore/swift5/default/README.md index 1725415f7e04..a8c7405dd3eb 100644 --- a/samples/client/petstore/swift5/default/README.md +++ b/samples/client/petstore/swift5/default/README.md @@ -26,6 +26,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *AnotherFakeAPI* | [**call123testSpecialTags**](docs/AnotherFakeAPI.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags +*FakeAPI* | [**createXmlItem**](docs/FakeAPI.md#createxmlitem) | **POST** /fake/create_xml_item | creates an XmlItem *FakeAPI* | [**fakeOuterBooleanSerialize**](docs/FakeAPI.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | *FakeAPI* | [**fakeOuterCompositeSerialize**](docs/FakeAPI.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | *FakeAPI* | [**fakeOuterNumberSerialize**](docs/FakeAPI.md#fakeouternumberserialize) | **POST** /fake/outer/number | @@ -38,6 +39,7 @@ Class | Method | HTTP request | Description *FakeAPI* | [**testGroupParameters**](docs/FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) *FakeAPI* | [**testInlineAdditionalProperties**](docs/FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties *FakeAPI* | [**testJsonFormData**](docs/FakeAPI.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeAPI* | [**testQueryParameterCollectionFormat**](docs/FakeAPI.md#testqueryparametercollectionformat) | **PUT** /fake/test-query-paramters | *FakeClassnameTags123API* | [**testClassname**](docs/FakeClassnameTags123API.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case *PetAPI* | [**addPet**](docs/PetAPI.md#addpet) | **POST** /pet | Add a new pet to the store *PetAPI* | [**deletePet**](docs/PetAPI.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet @@ -64,13 +66,22 @@ Class | Method | HTTP request | Description ## Documentation For Models + - [AdditionalPropertiesAnyType](docs/AdditionalPropertiesAnyType.md) + - [AdditionalPropertiesArray](docs/AdditionalPropertiesArray.md) + - [AdditionalPropertiesBoolean](docs/AdditionalPropertiesBoolean.md) - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [AdditionalPropertiesInteger](docs/AdditionalPropertiesInteger.md) + - [AdditionalPropertiesNumber](docs/AdditionalPropertiesNumber.md) + - [AdditionalPropertiesObject](docs/AdditionalPropertiesObject.md) + - [AdditionalPropertiesString](docs/AdditionalPropertiesString.md) - [Animal](docs/Animal.md) - [AnimalFarm](docs/AnimalFarm.md) - [ApiResponse](docs/ApiResponse.md) - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [ArrayTest](docs/ArrayTest.md) + - [BigCat](docs/BigCat.md) + - [BigCatAllOf](docs/BigCatAllOf.md) - [Capitalization](docs/Capitalization.md) - [Cat](docs/Cat.md) - [CatAllOf](docs/CatAllOf.md) @@ -104,6 +115,7 @@ Class | Method | HTTP request | Description - [TypeHolderDefault](docs/TypeHolderDefault.md) - [TypeHolderExample](docs/TypeHolderExample.md) - [User](docs/User.md) + - [XmlItem](docs/XmlItem.md) ## Documentation For Authorization diff --git a/samples/client/petstore/swift5/default/SwaggerClientTests/Podfile b/samples/client/petstore/swift5/default/SwaggerClientTests/Podfile deleted file mode 100644 index 77432f9eee92..000000000000 --- a/samples/client/petstore/swift5/default/SwaggerClientTests/Podfile +++ /dev/null @@ -1,13 +0,0 @@ -platform :ios, '9.0' - -source 'https://cdn.cocoapods.org/' - -use_frameworks! - -target 'SwaggerClient' do - pod "PetstoreClient", :path => "../" - - target 'SwaggerClientTests' do - inherit! :search_paths - end -end diff --git a/samples/client/petstore/swift5/default/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift5/default/SwaggerClientTests/Podfile.lock deleted file mode 100644 index 11d11529e9e4..000000000000 --- a/samples/client/petstore/swift5/default/SwaggerClientTests/Podfile.lock +++ /dev/null @@ -1,16 +0,0 @@ -PODS: - - PetstoreClient (1.0.0) - -DEPENDENCIES: - - PetstoreClient (from `../`) - -EXTERNAL SOURCES: - PetstoreClient: - :path: "../" - -SPEC CHECKSUMS: - PetstoreClient: b26b235a3ece06dbf1da99dc67e48aa201659f21 - -PODFILE CHECKSUM: 509bec696cc1d8641751b52e4fe4bef04ac4542c - -COCOAPODS: 1.10.0 diff --git a/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index ca2ec05d5dca..7d9d50e1fff6 100644 --- a/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -3,12 +3,11 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 52; objects = { /* Begin PBXBuildFile section */ 1A501F48219C3DC600F372F6 /* DateFormatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A501F47219C3DC600F372F6 /* DateFormatTests.swift */; }; - 23B2E76564651097BE2FE501 /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7F98CC8B18E5FA9213F6A68D /* Pods_SwaggerClient.framework */; }; 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */; }; 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB961C692C6300B96B06 /* ViewController.swift */; }; 6D4EFB9A1C692C6300B96B06 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB981C692C6300B96B06 /* Main.storyboard */; }; @@ -17,9 +16,9 @@ 6D4EFBB51C693BE200B96B06 /* PetAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */; }; 6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */; }; 6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */; }; + A5782C752664FB6500CAA106 /* PetstoreClient in Frameworks */ = {isa = PBXBuildFile; productRef = A5782C742664FB6500CAA106 /* PetstoreClient */; }; A5EA124F241901AA00E30FC3 /* UIImage+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA124E241901AA00E30FC3 /* UIImage+Extras.swift */; }; A5EA1251241905F000E30FC3 /* FileUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA1250241905F000E30FC3 /* FileUtils.swift */; }; - FB5CCC7EFA680BB2746B695B /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 83FDC034BBA2A07AE9975250 /* Pods_SwaggerClientTests.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -33,7 +32,6 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 081E9B893DEB1589CB807EA7 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; 1A501F47219C3DC600F372F6 /* DateFormatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateFormatTests.swift; sourceTree = ""; }; 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwaggerClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -47,14 +45,8 @@ 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = ""; }; 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = ""; }; 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; - 7F98CC8B18E5FA9213F6A68D /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 83FDC034BBA2A07AE9975250 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A5EA124E241901AA00E30FC3 /* UIImage+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIImage+Extras.swift"; sourceTree = ""; }; A5EA1250241905F000E30FC3 /* FileUtils.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileUtils.swift; sourceTree = ""; }; - ACB80AC61FA8D8916D4559AA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; - C07EC0A94AA0F86D60668B32 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - E43FC34A9681D65ED44EE914 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; - ED8576754DBB828CAE63EA87 /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -62,7 +54,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 23B2E76564651097BE2FE501 /* Pods_SwaggerClient.framework in Frameworks */, + A5782C752664FB6500CAA106 /* PetstoreClient in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -70,30 +62,15 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - FB5CCC7EFA680BB2746B695B /* Pods_SwaggerClientTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 203D4495376E4EB72474B091 /* Pods */ = { - isa = PBXGroup; - children = ( - 081E9B893DEB1589CB807EA7 /* Pods-SwaggerClient.debug.xcconfig */, - ACB80AC61FA8D8916D4559AA /* Pods-SwaggerClient.release.xcconfig */, - E43FC34A9681D65ED44EE914 /* Pods-SwaggerClientTests.debug.xcconfig */, - ED8576754DBB828CAE63EA87 /* Pods-SwaggerClientTests.release.xcconfig */, - ); - name = Pods; - sourceTree = ""; - }; 3FABC56EC0BA84CBF4F99564 /* Frameworks */ = { isa = PBXGroup; children = ( - C07EC0A94AA0F86D60668B32 /* Pods.framework */, - 7F98CC8B18E5FA9213F6A68D /* Pods_SwaggerClient.framework */, - 83FDC034BBA2A07AE9975250 /* Pods_SwaggerClientTests.framework */, ); name = Frameworks; sourceTree = ""; @@ -105,7 +82,6 @@ 6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */, 6D4EFB921C692C6300B96B06 /* Products */, 3FABC56EC0BA84CBF4F99564 /* Frameworks */, - 203D4495376E4EB72474B091 /* Pods */, ); sourceTree = ""; }; @@ -152,17 +128,18 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 5BC9214E8D9BA5A427A3775B /* [CP] Check Pods Manifest.lock */, 6D4EFB8D1C692C6300B96B06 /* Sources */, 6D4EFB8E1C692C6300B96B06 /* Frameworks */, 6D4EFB8F1C692C6300B96B06 /* Resources */, - FDCA0F14611FE114BFEBA8BB /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( ); name = SwaggerClient; + packageProductDependencies = ( + A5782C742664FB6500CAA106 /* PetstoreClient */, + ); productName = SwaggerClient; productReference = 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */; productType = "com.apple.product-type.application"; @@ -171,7 +148,6 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - EEDC5E683F9569976B7C1192 /* [CP] Check Pods Manifest.lock */, 6D4EFBA11C692C6300B96B06 /* Sources */, 6D4EFBA21C692C6300B96B06 /* Frameworks */, 6D4EFBA31C692C6300B96B06 /* Resources */, @@ -246,71 +222,6 @@ }; /* End PBXResourcesBuildPhase section */ -/* Begin PBXShellScriptBuildPhase section */ - 5BC9214E8D9BA5A427A3775B /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClient-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - EEDC5E683F9569976B7C1192 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClientTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - FDCA0F14611FE114BFEBA8BB /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/PetstoreClient/PetstoreClient.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PetstoreClient.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - /* Begin PBXSourcesBuildPhase section */ 6D4EFB8D1C692C6300B96B06 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -474,11 +385,13 @@ }; 6D4EFBAF1C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 081E9B893DEB1589CB807EA7 /* Pods-SwaggerClient.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -487,11 +400,13 @@ }; 6D4EFBB01C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = ACB80AC61FA8D8916D4559AA /* Pods-SwaggerClient.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -500,11 +415,14 @@ }; 6D4EFBB21C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = E43FC34A9681D65ED44EE914 /* Pods-SwaggerClientTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -514,11 +432,14 @@ }; 6D4EFBB31C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = ED8576754DBB828CAE63EA87 /* Pods-SwaggerClientTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -557,6 +478,13 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCSwiftPackageProductDependency section */ + A5782C742664FB6500CAA106 /* PetstoreClient */ = { + isa = XCSwiftPackageProductDependency; + productName = PetstoreClient; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 6D4EFB891C692C6300B96B06 /* Project object */; } diff --git a/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata index 9b3fa18954f7..00ec9b53a7f1 100644 --- a/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata +++ b/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata @@ -2,9 +2,9 @@ + location = "group:.."> + location = "group:SwaggerClient.xcodeproj"> diff --git a/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved b/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 000000000000..d384b276b4bc --- /dev/null +++ b/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/default/docs/AdditionalPropertiesAnyType.md b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesAnyType.md new file mode 100644 index 000000000000..bae60ab148f2 --- /dev/null +++ b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesAnyType.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesAnyType + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/default/docs/AdditionalPropertiesArray.md b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesArray.md new file mode 100644 index 000000000000..a371b5e28f32 --- /dev/null +++ b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesArray.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesArray + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/default/docs/AdditionalPropertiesBoolean.md b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesBoolean.md new file mode 100644 index 000000000000..d5f0d6da11ee --- /dev/null +++ b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesBoolean.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesBoolean + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/default/docs/AdditionalPropertiesClass.md b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesClass.md index 1f222244134e..1cffcdd84841 100644 --- a/samples/client/petstore/swift5/default/docs/AdditionalPropertiesClass.md +++ b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesClass.md @@ -4,7 +4,16 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **mapString** | **[String: String]** | | [optional] +**mapNumber** | **[String: Double]** | | [optional] +**mapInteger** | **[String: Int]** | | [optional] +**mapBoolean** | **[String: Bool]** | | [optional] +**mapArrayInteger** | [String: [Int]] | | [optional] +**mapArrayAnytype** | [String: [AnyCodable]] | | [optional] **mapMapString** | [String: [String: String]] | | [optional] +**mapMapAnytype** | [String: [String: AnyCodable]] | | [optional] +**anytype1** | [**AnyCodable**](.md) | | [optional] +**anytype2** | [**AnyCodable**](.md) | | [optional] +**anytype3** | [**AnyCodable**](.md) | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/swift5/default/docs/AdditionalPropertiesInteger.md b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesInteger.md new file mode 100644 index 000000000000..629293abdfe9 --- /dev/null +++ b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesInteger.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesInteger + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/default/docs/AdditionalPropertiesNumber.md b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesNumber.md new file mode 100644 index 000000000000..65adfe78137c --- /dev/null +++ b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesNumber.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesNumber + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/default/docs/AdditionalPropertiesObject.md b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesObject.md new file mode 100644 index 000000000000..99d69b7aae6a --- /dev/null +++ b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesObject.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesObject + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/default/docs/AdditionalPropertiesString.md b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesString.md new file mode 100644 index 000000000000..5bb8122887c4 --- /dev/null +++ b/samples/client/petstore/swift5/default/docs/AdditionalPropertiesString.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesString + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/default/docs/BigCat.md b/samples/client/petstore/swift5/default/docs/BigCat.md new file mode 100644 index 000000000000..cd904c7381a2 --- /dev/null +++ b/samples/client/petstore/swift5/default/docs/BigCat.md @@ -0,0 +1,10 @@ +# BigCat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/default/docs/BigCatAllOf.md b/samples/client/petstore/swift5/default/docs/BigCatAllOf.md new file mode 100644 index 000000000000..20da4caf5d01 --- /dev/null +++ b/samples/client/petstore/swift5/default/docs/BigCatAllOf.md @@ -0,0 +1,10 @@ +# BigCatAllOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/default/docs/FakeAPI.md b/samples/client/petstore/swift5/default/docs/FakeAPI.md index 543869c0d2e0..01d7c662e3c6 100644 --- a/samples/client/petstore/swift5/default/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/default/docs/FakeAPI.md @@ -4,6 +4,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- +[**createXmlItem**](FakeAPI.md#createxmlitem) | **POST** /fake/create_xml_item | creates an XmlItem [**fakeOuterBooleanSerialize**](FakeAPI.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | [**fakeOuterCompositeSerialize**](FakeAPI.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | [**fakeOuterNumberSerialize**](FakeAPI.md#fakeouternumberserialize) | **POST** /fake/outer/number | @@ -16,8 +17,59 @@ Method | HTTP request | Description [**testGroupParameters**](FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) [**testInlineAdditionalProperties**](FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**testJsonFormData**](FakeAPI.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +[**testQueryParameterCollectionFormat**](FakeAPI.md#testqueryparametercollectionformat) | **PUT** /fake/test-query-paramters | +# **createXmlItem** +```swift + open class func createXmlItem(xmlItem: XmlItem, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +creates an XmlItem + +this route creates an XmlItem + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let xmlItem = XmlItem(attributeString: "attributeString_example", attributeNumber: 123, attributeInteger: 123, attributeBoolean: true, wrappedArray: [123], nameString: "nameString_example", nameNumber: 123, nameInteger: 123, nameBoolean: true, nameArray: [123], nameWrappedArray: [123], prefixString: "prefixString_example", prefixNumber: 123, prefixInteger: 123, prefixBoolean: true, prefixArray: [123], prefixWrappedArray: [123], namespaceString: "namespaceString_example", namespaceNumber: 123, namespaceInteger: 123, namespaceBoolean: true, namespaceArray: [123], namespaceWrappedArray: [123], prefixNsString: "prefixNsString_example", prefixNsNumber: 123, prefixNsInteger: 123, prefixNsBoolean: true, prefixNsArray: [123], prefixNsWrappedArray: [123]) // XmlItem | XmlItem Body + +// creates an XmlItem +FakeAPI.createXmlItem(xmlItem: xmlItem) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **xmlItem** | [**XmlItem**](XmlItem.md) | XmlItem Body | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml, application/xml; charset=utf-8, application/xml; charset=utf-16, text/xml, text/xml; charset=utf-8, text/xml; charset=utf-16 + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **fakeOuterBooleanSerialize** ```swift open class func fakeOuterBooleanSerialize(body: Bool? = nil, completion: @escaping (_ data: Bool?, _ error: Error?) -> Void) @@ -379,7 +431,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) @@ -660,3 +712,60 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **testQueryParameterCollectionFormat** +```swift + open class func testQueryParameterCollectionFormat(pipe: [String], ioutil: [String], http: [String], url: [String], context: [String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + + + +To test the collection format in query parameters + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let pipe = ["inner_example"] // [String] | +let ioutil = ["inner_example"] // [String] | +let http = ["inner_example"] // [String] | +let url = ["inner_example"] // [String] | +let context = ["inner_example"] // [String] | + +FakeAPI.testQueryParameterCollectionFormat(pipe: pipe, ioutil: ioutil, http: http, url: url, context: context) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pipe** | [**[String]**](String.md) | | + **ioutil** | [**[String]**](String.md) | | + **http** | [**[String]**](String.md) | | + **url** | [**[String]**](String.md) | | + **context** | [**[String]**](String.md) | | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/swift5/default/docs/FormatTest.md b/samples/client/petstore/swift5/default/docs/FormatTest.md index f74d94f6c46a..55de2e05ecd9 100644 --- a/samples/client/petstore/swift5/default/docs/FormatTest.md +++ b/samples/client/petstore/swift5/default/docs/FormatTest.md @@ -16,6 +16,7 @@ Name | Type | Description | Notes **dateTime** | **Date** | | [optional] **uuid** | **UUID** | | [optional] **password** | **String** | | +**bigDecimal** | **Decimal** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/swift5/default/docs/Pet.md b/samples/client/petstore/swift5/default/docs/Pet.md index 5c05f98fad4a..36e8e4884394 100644 --- a/samples/client/petstore/swift5/default/docs/Pet.md +++ b/samples/client/petstore/swift5/default/docs/Pet.md @@ -6,7 +6,7 @@ Name | Type | Description | Notes **id** | **Int64** | | [optional] **category** | [**Category**](Category.md) | | [optional] **name** | **String** | | -**photoUrls** | **[String]** | | +**photoUrls** | **Set** | | **tags** | [Tag] | | [optional] **status** | **String** | pet status in the store | [optional] diff --git a/samples/client/petstore/swift5/default/docs/PetAPI.md b/samples/client/petstore/swift5/default/docs/PetAPI.md index 27efe0833476..1daf96285825 100644 --- a/samples/client/petstore/swift5/default/docs/PetAPI.md +++ b/samples/client/petstore/swift5/default/docs/PetAPI.md @@ -165,7 +165,7 @@ Name | Type | Description | Notes # **findPetsByTags** ```swift - open class func findPetsByTags(tags: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByTags(tags: Set, completion: @escaping (_ data: Set?, _ error: Error?) -> Void) ``` Finds Pets by tags @@ -177,7 +177,7 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let tags = ["inner_example"] // [String] | Tags to filter by +let tags = ["inner_example"] // Set | Tags to filter by // Finds Pets by tags PetAPI.findPetsByTags(tags: tags) { (response, error) in @@ -196,11 +196,11 @@ PetAPI.findPetsByTags(tags: tags) { (response, error) in Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **tags** | [**[String]**](String.md) | Tags to filter by | + **tags** | [**Set<String>**](String.md) | Tags to filter by | ### Return type -[**[Pet]**](Pet.md) +[**Set**](Pet.md) ### Authorization diff --git a/samples/client/petstore/swift5/default/docs/TypeHolderExample.md b/samples/client/petstore/swift5/default/docs/TypeHolderExample.md index 46d0471cd71a..c0530dc0e5b6 100644 --- a/samples/client/petstore/swift5/default/docs/TypeHolderExample.md +++ b/samples/client/petstore/swift5/default/docs/TypeHolderExample.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **stringItem** | **String** | | **numberItem** | **Double** | | +**floatItem** | **Float** | | **integerItem** | **Int** | | **boolItem** | **Bool** | | **arrayItem** | **[Int]** | | diff --git a/samples/client/petstore/swift5/default/docs/XmlItem.md b/samples/client/petstore/swift5/default/docs/XmlItem.md new file mode 100644 index 000000000000..1a4eb4e9c836 --- /dev/null +++ b/samples/client/petstore/swift5/default/docs/XmlItem.md @@ -0,0 +1,38 @@ +# XmlItem + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**attributeString** | **String** | | [optional] +**attributeNumber** | **Double** | | [optional] +**attributeInteger** | **Int** | | [optional] +**attributeBoolean** | **Bool** | | [optional] +**wrappedArray** | **[Int]** | | [optional] +**nameString** | **String** | | [optional] +**nameNumber** | **Double** | | [optional] +**nameInteger** | **Int** | | [optional] +**nameBoolean** | **Bool** | | [optional] +**nameArray** | **[Int]** | | [optional] +**nameWrappedArray** | **[Int]** | | [optional] +**prefixString** | **String** | | [optional] +**prefixNumber** | **Double** | | [optional] +**prefixInteger** | **Int** | | [optional] +**prefixBoolean** | **Bool** | | [optional] +**prefixArray** | **[Int]** | | [optional] +**prefixWrappedArray** | **[Int]** | | [optional] +**namespaceString** | **String** | | [optional] +**namespaceNumber** | **Double** | | [optional] +**namespaceInteger** | **Int** | | [optional] +**namespaceBoolean** | **Bool** | | [optional] +**namespaceArray** | **[Int]** | | [optional] +**namespaceWrappedArray** | **[Int]** | | [optional] +**prefixNsString** | **String** | | [optional] +**prefixNsNumber** | **Double** | | [optional] +**prefixNsInteger** | **Int** | | [optional] +**prefixNsBoolean** | **Bool** | | [optional] +**prefixNsArray** | **[Int]** | | [optional] +**prefixNsWrappedArray** | **[Int]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/default/project.yml b/samples/client/petstore/swift5/default/project.yml index 8e7102001b8d..0493cf65896e 100644 --- a/samples/client/petstore/swift5/default/project.yml +++ b/samples/client/petstore/swift5/default/project.yml @@ -11,4 +11,5 @@ targets: settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - + dependencies: + - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/deprecated/.openapi-generator/VERSION b/samples/client/petstore/swift5/deprecated/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/swift5/deprecated/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/deprecated/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/deprecated/Cartfile b/samples/client/petstore/swift5/deprecated/Cartfile index 8b137891791f..843f7adc7794 100644 --- a/samples/client/petstore/swift5/deprecated/Cartfile +++ b/samples/client/petstore/swift5/deprecated/Cartfile @@ -1 +1,2 @@ +github "Flight-School/AnyCodable" ~> 0.6.0 diff --git a/samples/client/petstore/swift5/deprecated/Package.resolved b/samples/client/petstore/swift5/deprecated/Package.resolved new file mode 100644 index 000000000000..d384b276b4bc --- /dev/null +++ b/samples/client/petstore/swift5/deprecated/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/deprecated/Package.swift b/samples/client/petstore/swift5/deprecated/Package.swift index b7fe4734aa8a..5cde507bdcf9 100644 --- a/samples/client/petstore/swift5/deprecated/Package.swift +++ b/samples/client/petstore/swift5/deprecated/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.0 +// swift-tools-version:5.1 import PackageDescription @@ -19,13 +19,14 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.6.0")), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "PetstoreClient", - dependencies: [], + dependencies: ["AnyCodable", ], path: "PetstoreClient/Classes" ), ] diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient.podspec b/samples/client/petstore/swift5/deprecated/PetstoreClient.podspec index b61285f6b25e..60f05891b241 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient.podspec @@ -11,4 +11,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.0' end diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs.swift index 57308c82f8ed..850c8fc43833 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,7 +6,10 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io/v2" public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index f46c7ac57ea3..bf00a6fa7412 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -15,7 +15,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(pet: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func addPet(pet: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { addPetWithRequestBuilder(pet: pet).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -37,10 +37,10 @@ open class PetAPI { */ open class func addPetWithRequestBuilder(pet: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: pet) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -48,9 +48,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -61,7 +61,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -87,10 +87,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), @@ -98,9 +98,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -119,7 +119,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -142,11 +142,11 @@ open class PetAPI { */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) @@ -156,9 +156,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -169,7 +169,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -193,11 +193,11 @@ open class PetAPI { @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) @@ -207,9 +207,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -219,7 +219,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -245,10 +245,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -256,9 +256,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -268,7 +268,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(pet: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePet(pet: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithRequestBuilder(pet: pet).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -290,10 +290,10 @@ open class PetAPI { */ open class func updatePetWithRequestBuilder(pet: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: pet) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -301,9 +301,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -315,7 +315,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -342,7 +342,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), @@ -351,7 +351,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -359,9 +359,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -373,7 +373,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -400,7 +400,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), @@ -409,7 +409,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -417,9 +417,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index c34e83325514..9d68c2def6ed 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -15,7 +15,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -38,10 +38,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{orderId}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -60,7 +60,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -82,10 +82,10 @@ open class StoreAPI { */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -93,9 +93,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -105,7 +105,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -128,10 +128,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{orderId}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -139,9 +139,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -151,7 +151,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func placeOrder(order: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func placeOrder(order: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(order: order).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -170,10 +170,10 @@ open class StoreAPI { */ open class func placeOrderWithRequestBuilder(order: Order) -> RequestBuilder { let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: order) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -181,9 +181,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 255ffb0cb55b..106277bbe05e 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -15,7 +15,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(user: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUser(user: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUserWithRequestBuilder(user: user).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -38,10 +38,10 @@ open class UserAPI { */ open class func createUserWithRequestBuilder(user: User) -> RequestBuilder { let path = "/user" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: user) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -61,7 +61,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(user: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithArrayInput(user: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(user: user).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -83,10 +83,10 @@ open class UserAPI { */ open class func createUsersWithArrayInputWithRequestBuilder(user: [User]) -> RequestBuilder { let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: user) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -94,9 +94,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -106,7 +106,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(user: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithListInput(user: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(user: user).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -128,10 +128,10 @@ open class UserAPI { */ open class func createUsersWithListInputWithRequestBuilder(user: [User]) -> RequestBuilder { let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: user) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -139,9 +139,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -151,7 +151,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -177,10 +177,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -188,9 +188,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -200,7 +200,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -222,10 +222,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -233,9 +233,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -246,7 +246,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -267,11 +267,11 @@ open class UserAPI { */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) @@ -282,9 +282,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -293,7 +293,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -314,10 +314,10 @@ open class UserAPI { */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -325,9 +325,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -338,7 +338,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, user: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updateUser(username: String, user: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, user: user).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -365,10 +365,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: user) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -376,9 +376,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 93ed6b90b376..e23035dde30e 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,6 +5,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -52,6 +55,12 @@ extension Array: JSONEncodable { } } +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + extension Dictionary: JSONEncodable { func encodeToJSON() -> Any { var dictionary = [AnyHashable: Any]() diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index c8058e8db2a4..619a45e20bb1 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Describes the result of uploading an image resource */ public struct ApiResponse: Codable, Hashable { @@ -20,4 +23,18 @@ public struct ApiResponse: Codable, Hashable { self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { + case code + case type + case message + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(code, forKey: .code) + try container.encodeIfPresent(type, forKey: .type) + try container.encodeIfPresent(message, forKey: .message) + } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index bbf2ef73f2cb..26ba10c456e3 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** A category for a pet */ public struct Category: Codable, Hashable { @@ -18,4 +21,16 @@ public struct Category: Codable, Hashable { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 4401234cb337..81d122defdf2 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** An order for a pets from the pet store */ @available(*, deprecated, message: "This schema is deprecated.") @@ -33,4 +36,24 @@ public struct Order: Codable, Hashable { self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case petId + case quantity + case shipDate + case status + case complete + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(petId, forKey: .petId) + try container.encodeIfPresent(quantity, forKey: .quantity) + try container.encodeIfPresent(shipDate, forKey: .shipDate) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(complete, forKey: .complete) + } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index ab283fe48852..475b1d7e546b 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** A pet for sale in the pet store */ public struct Pet: Codable, Hashable { @@ -33,4 +36,24 @@ public struct Pet: Codable, Hashable { self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case category + case name + case photoUrls + case tags + case status + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(category, forKey: .category) + try container.encode(name, forKey: .name) + try container.encode(photoUrls, forKey: .photoUrls) + try container.encodeIfPresent(tags, forKey: .tags) + try container.encodeIfPresent(status, forKey: .status) + } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index a3a488b13f63..6f008baf7262 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** A tag for a pet */ public struct Tag: Codable, Hashable { @@ -18,4 +21,16 @@ public struct Tag: Codable, Hashable { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/User.swift index 566bb545dbf9..f46bd7741311 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** A User who is purchasing from the pet store */ public struct User: Codable, Hashable { @@ -31,4 +34,28 @@ public struct User: Codable, Hashable { self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case username + case firstName + case lastName + case email + case password + case phone + case userStatus + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(username, forKey: .username) + try container.encodeIfPresent(firstName, forKey: .firstName) + try container.encodeIfPresent(lastName, forKey: .lastName) + try container.encodeIfPresent(email, forKey: .email) + try container.encodeIfPresent(password, forKey: .password) + try container.encodeIfPresent(phone, forKey: .phone) + try container.encodeIfPresent(userStatus, forKey: .userStatus) + } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 52b2071ec1aa..774c0427eaa2 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,7 +93,7 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/deprecated/project.yml b/samples/client/petstore/swift5/deprecated/project.yml index 8e7102001b8d..0493cf65896e 100644 --- a/samples/client/petstore/swift5/deprecated/project.yml +++ b/samples/client/petstore/swift5/deprecated/project.yml @@ -11,4 +11,5 @@ targets: settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - + dependencies: + - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/VERSION b/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/nonPublicApi/Cartfile b/samples/client/petstore/swift5/nonPublicApi/Cartfile index 8b137891791f..843f7adc7794 100644 --- a/samples/client/petstore/swift5/nonPublicApi/Cartfile +++ b/samples/client/petstore/swift5/nonPublicApi/Cartfile @@ -1 +1,2 @@ +github "Flight-School/AnyCodable" ~> 0.6.0 diff --git a/samples/client/petstore/swift5/nonPublicApi/Package.resolved b/samples/client/petstore/swift5/nonPublicApi/Package.resolved new file mode 100644 index 000000000000..d384b276b4bc --- /dev/null +++ b/samples/client/petstore/swift5/nonPublicApi/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/nonPublicApi/Package.swift b/samples/client/petstore/swift5/nonPublicApi/Package.swift index b7fe4734aa8a..5cde507bdcf9 100644 --- a/samples/client/petstore/swift5/nonPublicApi/Package.swift +++ b/samples/client/petstore/swift5/nonPublicApi/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.0 +// swift-tools-version:5.1 import PackageDescription @@ -19,13 +19,14 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.6.0")), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "PetstoreClient", - dependencies: [], + dependencies: ["AnyCodable", ], path: "PetstoreClient/Classes" ), ] diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient.podspec b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient.podspec index b61285f6b25e..60f05891b241 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient.podspec @@ -11,4 +11,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.0' end diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift index 026f2295d319..e98c4bb0fbe7 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,7 +6,10 @@ import Foundation -internal class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +internal typealias PetstoreClientAPI = PetstoreClient + +internal class PetstoreClient { internal static var basePath = "http://petstore.swagger.io:80/v2" internal static var credential: URLCredential? internal static var customHeaders: [String: String] = [:] @@ -32,7 +35,7 @@ internal class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } internal func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ internal class RequestBuilder { } } - internal func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + internal func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } internal func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ internal class RequestBuilder { } internal func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 537dacc4c1af..3962e550ac49 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -15,7 +15,7 @@ internal class AnotherFakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + internal class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -35,10 +35,10 @@ internal class AnotherFakeAPI { */ internal class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -46,9 +46,9 @@ internal class AnotherFakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 03fd8a8ca150..b38a586bd0f2 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -14,7 +14,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { + internal class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -33,10 +33,10 @@ internal class FakeAPI { */ internal class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -44,9 +44,9 @@ internal class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -55,7 +55,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { + internal class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -74,10 +74,10 @@ internal class FakeAPI { */ internal class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -85,9 +85,9 @@ internal class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -96,7 +96,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { + internal class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -115,10 +115,10 @@ internal class FakeAPI { */ internal class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -126,9 +126,9 @@ internal class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -137,7 +137,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + internal class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -156,10 +156,10 @@ internal class FakeAPI { */ internal class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -167,9 +167,9 @@ internal class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -178,7 +178,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -197,10 +197,10 @@ internal class FakeAPI { */ internal class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -208,9 +208,9 @@ internal class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -220,7 +220,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -239,11 +239,11 @@ internal class FakeAPI { */ internal class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) @@ -253,9 +253,9 @@ internal class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -265,7 +265,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + internal class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -285,10 +285,10 @@ internal class FakeAPI { */ internal class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -296,9 +296,9 @@ internal class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -321,7 +321,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testEndpointParameters(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double, string: String? = nil, patternWithoutDelimiter: String, byte: Data, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func testEndpointParameters(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double, string: String? = nil, patternWithoutDelimiter: String, byte: Data, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEndpointParametersWithRequestBuilder(integer: integer, int32: int32, int64: int64, number: number, float: float, double: double, string: string, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -357,7 +357,7 @@ internal class FakeAPI { */ internal class func testEndpointParametersWithRequestBuilder(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double, string: String? = nil, patternWithoutDelimiter: String, byte: Data, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), @@ -378,7 +378,7 @@ internal class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -386,9 +386,9 @@ internal class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -472,7 +472,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -499,7 +499,7 @@ internal class FakeAPI { */ internal class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), @@ -508,8 +508,8 @@ internal class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), @@ -524,9 +524,9 @@ internal class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -541,7 +541,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -566,11 +566,11 @@ internal class FakeAPI { */ internal class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), @@ -584,9 +584,9 @@ internal class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -596,7 +596,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -615,10 +615,10 @@ internal class FakeAPI { */ internal class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -626,9 +626,9 @@ internal class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -639,7 +639,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -659,7 +659,7 @@ internal class FakeAPI { */ internal class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), @@ -668,7 +668,7 @@ internal class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -676,9 +676,9 @@ internal class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 76f1b99ed1c9..f746118089c4 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -15,7 +15,7 @@ internal class FakeClassnameTags123API { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + internal class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -38,10 +38,10 @@ internal class FakeClassnameTags123API { */ internal class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ internal class FakeClassnameTags123API { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 658ef61ddc07..67a5a95b72b2 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -15,7 +15,7 @@ internal class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -37,10 +37,10 @@ internal class PetAPI { */ internal class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -48,9 +48,9 @@ internal class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -61,7 +61,7 @@ internal class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func deletePet(apiKey: String? = nil, petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func deletePet(apiKey: String? = nil, petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deletePetWithRequestBuilder(apiKey: apiKey, petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -87,10 +87,10 @@ internal class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), @@ -98,9 +98,9 @@ internal class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -119,7 +119,7 @@ internal class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + internal class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -142,11 +142,11 @@ internal class PetAPI { */ internal class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) @@ -156,9 +156,9 @@ internal class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -169,7 +169,7 @@ internal class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @available(*, deprecated, message: "This operation is deprecated.") - internal class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + internal class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -193,11 +193,11 @@ internal class PetAPI { @available(*, deprecated, message: "This operation is deprecated.") internal class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) @@ -207,9 +207,9 @@ internal class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -219,7 +219,7 @@ internal class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { + internal class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -245,10 +245,10 @@ internal class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -256,9 +256,9 @@ internal class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -268,7 +268,7 @@ internal class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -290,10 +290,10 @@ internal class PetAPI { */ internal class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -301,9 +301,9 @@ internal class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -315,7 +315,7 @@ internal class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -342,7 +342,7 @@ internal class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), @@ -351,7 +351,7 @@ internal class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -359,9 +359,9 @@ internal class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -373,7 +373,7 @@ internal class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + internal class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -400,7 +400,7 @@ internal class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), @@ -409,7 +409,7 @@ internal class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -417,9 +417,9 @@ internal class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -431,7 +431,7 @@ internal class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func uploadFileWithRequiredFile(petId: Int64, additionalMetadata: String? = nil, requiredFile: URL, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + internal class func uploadFileWithRequiredFile(petId: Int64, additionalMetadata: String? = nil, requiredFile: URL, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, requiredFile: requiredFile).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -458,7 +458,7 @@ internal class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), @@ -467,7 +467,7 @@ internal class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -475,9 +475,9 @@ internal class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 3f0f902ccd87..4b57f341494c 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -15,7 +15,7 @@ internal class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -38,10 +38,10 @@ internal class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ internal class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -60,7 +60,7 @@ internal class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { + internal class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -82,10 +82,10 @@ internal class StoreAPI { */ internal class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -93,9 +93,9 @@ internal class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -105,7 +105,7 @@ internal class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + internal class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -128,10 +128,10 @@ internal class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -139,9 +139,9 @@ internal class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -151,7 +151,7 @@ internal class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + internal class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -170,10 +170,10 @@ internal class StoreAPI { */ internal class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -181,9 +181,9 @@ internal class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index f4a787ff486c..01b5c8c07924 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -15,7 +15,7 @@ internal class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -35,10 +35,10 @@ internal class UserAPI { */ internal class func createUserWithRequestBuilder(body: User) -> RequestBuilder { let path = "/user" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -46,9 +46,9 @@ internal class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -58,7 +58,7 @@ internal class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -77,10 +77,10 @@ internal class UserAPI { */ internal class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -88,9 +88,9 @@ internal class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -100,7 +100,7 @@ internal class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -119,10 +119,10 @@ internal class UserAPI { */ internal class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -130,9 +130,9 @@ internal class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -142,7 +142,7 @@ internal class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -165,10 +165,10 @@ internal class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -176,9 +176,9 @@ internal class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -188,7 +188,7 @@ internal class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { + internal class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -210,10 +210,10 @@ internal class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -221,9 +221,9 @@ internal class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -234,7 +234,7 @@ internal class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + internal class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -255,11 +255,11 @@ internal class UserAPI { */ internal class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) @@ -270,9 +270,9 @@ internal class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -281,7 +281,7 @@ internal class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -299,10 +299,10 @@ internal class UserAPI { */ internal class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -310,9 +310,9 @@ internal class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -323,7 +323,7 @@ internal class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -347,10 +347,10 @@ internal class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -358,9 +358,9 @@ internal class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift index e5511b3aa373..65ae1c6c6425 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,6 +5,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -52,6 +55,12 @@ extension Array: JSONEncodable { } } +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + extension Dictionary: JSONEncodable { func encodeToJSON() -> Any { var dictionary = [AnyHashable: Any]() diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 34e7b0fd4e9c..048d2223b464 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct AdditionalPropertiesClass: Codable, Hashable { @@ -22,4 +25,11 @@ internal struct AdditionalPropertiesClass: Codable, Hashable { case mapMapString = "map_map_string" } + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapString, forKey: .mapString) + try container.encodeIfPresent(mapMapString, forKey: .mapMapString) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 80422aa94a31..cf3022b7a592 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct Animal: Codable, Hashable { @@ -17,4 +20,16 @@ internal struct Animal: Codable, Hashable { self.color = color } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index 3ebe9e9a5dea..58d2309771e9 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,5 +6,8 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index b117aad7133b..3bba5d0f051b 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct ApiResponse: Codable, Hashable { @@ -19,4 +22,18 @@ internal struct ApiResponse: Codable, Hashable { self.message = message } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case code + case type + case message + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(code, forKey: .code) + try container.encodeIfPresent(type, forKey: .type) + try container.encodeIfPresent(message, forKey: .message) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index d5ce23fb27a0..6600b567f54a 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct ArrayOfArrayOfNumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ internal struct ArrayOfArrayOfNumberOnly: Codable, Hashable { case arrayArrayNumber = "ArrayArrayNumber" } + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index fa96400f7a63..b9bb366249b4 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct ArrayOfNumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ internal struct ArrayOfNumberOnly: Codable, Hashable { case arrayNumber = "ArrayNumber" } + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index c731155e26de..5aab5e0237f9 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct ArrayTest: Codable, Hashable { @@ -25,4 +28,12 @@ internal struct ArrayTest: Codable, Hashable { case arrayArrayOfModel = "array_array_of_model" } + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayOfString, forKey: .arrayOfString) + try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) + try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index a55eef8975b4..cc75d775764c 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct Capitalization: Codable, Hashable { @@ -35,4 +38,15 @@ internal struct Capitalization: Codable, Hashable { case ATT_NAME } + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(smallCamel, forKey: .smallCamel) + try container.encodeIfPresent(capitalCamel, forKey: .capitalCamel) + try container.encodeIfPresent(smallSnake, forKey: .smallSnake) + try container.encodeIfPresent(capitalSnake, forKey: .capitalSnake) + try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) + try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 081244637a51..e1d59e33c663 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct Cat: Codable, Hashable { @@ -19,4 +22,18 @@ internal struct Cat: Codable, Hashable { self.declawed = declawed } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case declawed + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index a7fc1f24827a..8a3358a747ab 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct CatAllOf: Codable, Hashable { @@ -15,4 +18,14 @@ internal struct CatAllOf: Codable, Hashable { self.declawed = declawed } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case declawed + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 3b4f6c149fad..cdd51a8ffbaf 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,15 +6,30 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct Category: Codable, Hashable { internal var id: Int64? - internal var name: String = "default-name" + internal var name: String? = "default-name" - internal init(id: Int64? = nil, name: String = "default-name") { + internal init(id: Int64? = nil, name: String? = "default-name") { self.id = id self.name = name } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encode(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index 33b54fdd4e80..c5561f409fca 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model with \"_class\" property */ internal struct ClassModel: Codable, Hashable { @@ -16,4 +19,14 @@ internal struct ClassModel: Codable, Hashable { self._class = _class } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case _class + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_class, forKey: ._class) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index de09406d53cf..a5640b27b268 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct Client: Codable, Hashable { @@ -15,4 +18,14 @@ internal struct Client: Codable, Hashable { self.client = client } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case client + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(client, forKey: .client) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index 161bead82270..fcf4077c0b13 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct Dog: Codable, Hashable { @@ -19,4 +22,18 @@ internal struct Dog: Codable, Hashable { self.breed = breed } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case breed + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 5957070689e7..f5cb2649406b 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct DogAllOf: Codable, Hashable { @@ -15,4 +18,14 @@ internal struct DogAllOf: Codable, Hashable { self.breed = breed } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case breed + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 8a8f61af5890..502b7f16fd27 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct EnumArrays: Codable, Hashable { @@ -30,4 +33,11 @@ internal struct EnumArrays: Codable, Hashable { case arrayEnum = "array_enum" } + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justSymbol, forKey: .justSymbol) + try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index 71fd29e0d2a5..7b5fa846ca11 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 27ed6bce5571..6ab42303c451 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct EnumTest: Codable, Hashable { @@ -49,4 +52,14 @@ internal struct EnumTest: Codable, Hashable { case outerEnum } + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(enumString, forKey: .enumString) + try container.encode(enumStringRequired, forKey: .enumStringRequired) + try container.encodeIfPresent(enumInteger, forKey: .enumInteger) + try container.encodeIfPresent(enumNumber, forKey: .enumNumber) + try container.encodeIfPresent(outerEnum, forKey: .outerEnum) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/File.swift index f0d615b5912b..c4843091f8d4 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Must be named `File` for test. */ internal struct File: Codable, Hashable { @@ -17,4 +20,14 @@ internal struct File: Codable, Hashable { self.sourceURI = sourceURI } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case sourceURI + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(sourceURI, forKey: .sourceURI) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index bfa1e9e6c04c..52bea1373b04 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct FileSchemaTestClass: Codable, Hashable { @@ -17,4 +20,16 @@ internal struct FileSchemaTestClass: Codable, Hashable { self.files = files } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case file + case files + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(file, forKey: .file) + try container.encodeIfPresent(files, forKey: .files) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index 1f5b70fc6c0a..c1eff9ffd18a 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct FormatTest: Codable, Hashable { @@ -39,4 +42,38 @@ internal struct FormatTest: Codable, Hashable { self.password = password } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case integer + case int32 + case int64 + case number + case float + case double + case string + case byte + case binary + case date + case dateTime + case uuid + case password + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(integer, forKey: .integer) + try container.encodeIfPresent(int32, forKey: .int32) + try container.encodeIfPresent(int64, forKey: .int64) + try container.encode(number, forKey: .number) + try container.encodeIfPresent(float, forKey: .float) + try container.encodeIfPresent(double, forKey: .double) + try container.encodeIfPresent(string, forKey: .string) + try container.encode(byte, forKey: .byte) + try container.encodeIfPresent(binary, forKey: .binary) + try container.encode(date, forKey: .date) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encode(password, forKey: .password) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index 7346dd89f4b9..df1e18887c52 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct HasOnlyReadOnly: Codable, Hashable { @@ -17,4 +20,16 @@ internal struct HasOnlyReadOnly: Codable, Hashable { self.foo = foo } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case foo + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(foo, forKey: .foo) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/List.swift index 37298aa93a6e..10956a8bf61f 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct List: Codable, Hashable { @@ -19,4 +22,10 @@ internal struct List: Codable, Hashable { case _123list = "123-list" } + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_123list, forKey: ._123list) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index 959c1b6132fd..cee2c1dc24f5 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct MapTest: Codable, Hashable { @@ -32,4 +35,13 @@ internal struct MapTest: Codable, Hashable { case indirectMap = "indirect_map" } + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapMapOfString, forKey: .mapMapOfString) + try container.encodeIfPresent(mapOfEnumString, forKey: .mapOfEnumString) + try container.encodeIfPresent(directMap, forKey: .directMap) + try container.encodeIfPresent(indirectMap, forKey: .indirectMap) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index 725d0ff947b1..ef916b0d8775 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { @@ -19,4 +22,18 @@ internal struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { self.map = map } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case uuid + case dateTime + case map + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(map, forKey: .map) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index e0353da8f215..6a6ff7664b9c 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name starting with number */ internal struct Model200Response: Codable, Hashable { @@ -23,4 +26,11 @@ internal struct Model200Response: Codable, Hashable { case _class = "class" } + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(_class, forKey: ._class) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index af6cb19d7da1..5e4345bb54a1 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name same as property name */ internal struct Name: Codable, Hashable { @@ -29,4 +32,13 @@ internal struct Name: Codable, Hashable { case _123number = "123Number" } + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encodeIfPresent(snakeCase, forKey: .snakeCase) + try container.encodeIfPresent(property, forKey: .property) + try container.encodeIfPresent(_123number, forKey: ._123number) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 37c113960383..0a36afc7855a 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct NumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ internal struct NumberOnly: Codable, Hashable { case justNumber = "JustNumber" } + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justNumber, forKey: .justNumber) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 0c886ae0fc8f..bb0eb5c601fe 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct Order: Codable, Hashable { @@ -31,4 +34,24 @@ internal struct Order: Codable, Hashable { self.complete = complete } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case id + case petId + case quantity + case shipDate + case status + case complete + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(petId, forKey: .petId) + try container.encodeIfPresent(quantity, forKey: .quantity) + try container.encodeIfPresent(shipDate, forKey: .shipDate) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(complete, forKey: .complete) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index b11cacc9d9b3..3b41213b30f5 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct OuterComposite: Codable, Hashable { @@ -25,4 +28,12 @@ internal struct OuterComposite: Codable, Hashable { case myBoolean = "my_boolean" } + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(myNumber, forKey: .myNumber) + try container.encodeIfPresent(myString, forKey: .myString) + try container.encodeIfPresent(myBoolean, forKey: .myBoolean) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index e0cdcbea0558..e947654ad729 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index c388433da77b..833730ac896b 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct Pet: Codable, Hashable { @@ -31,4 +34,24 @@ internal struct Pet: Codable, Hashable { self.status = status } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case id + case category + case name + case photoUrls + case tags + case status + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(category, forKey: .category) + try container.encode(name, forKey: .name) + try container.encode(photoUrls, forKey: .photoUrls) + try container.encodeIfPresent(tags, forKey: .tags) + try container.encodeIfPresent(status, forKey: .status) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index cc134ec6af64..d0a73f836f78 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct ReadOnlyFirst: Codable, Hashable { @@ -17,4 +20,16 @@ internal struct ReadOnlyFirst: Codable, Hashable { self.baz = baz } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case baz + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(baz, forKey: .baz) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 998123e37e24..9b2e502be391 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing reserved words */ internal struct Return: Codable, Hashable { @@ -20,4 +23,10 @@ internal struct Return: Codable, Hashable { case _return = "return" } + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_return, forKey: ._return) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index c29097c092b3..f77f26ce88c8 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct SpecialModelName: Codable, Hashable { @@ -19,4 +22,10 @@ internal struct SpecialModelName: Codable, Hashable { case specialPropertyName = "$special[property.name]" } + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 6d5719e4395c..a0f5dc1082eb 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,9 +6,16 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct StringBooleanMap: Codable, Hashable { + + internal enum CodingKeys: CodingKey, CaseIterable { + } + internal var additionalProperties: [String: Bool] = [:] internal subscript(key: String) -> Bool? { @@ -27,19 +34,18 @@ internal struct StringBooleanMap: Codable, Hashable { // Encodable protocol methods internal func encode(to encoder: Encoder) throws { - - var container = encoder.container(keyedBy: String.self) - - try container.encodeMap(additionalProperties) + var container = encoder.container(keyedBy: CodingKeys.self) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) } // Decodable protocol methods internal init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 8b4501e67aa6..866911641d00 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct Tag: Codable, Hashable { @@ -17,4 +20,16 @@ internal struct Tag: Codable, Hashable { self.name = name } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index 52500e04b432..3b3d4c7387a0 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct TypeHolderDefault: Codable, Hashable { @@ -31,4 +34,14 @@ internal struct TypeHolderDefault: Codable, Hashable { case arrayItem = "array_item" } + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index a1408b0bd1b0..2ca47db911d6 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct TypeHolderExample: Codable, Hashable { @@ -31,4 +34,14 @@ internal struct TypeHolderExample: Codable, Hashable { case arrayItem = "array_item" } + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/User.swift index afbd9f12349b..4f1504516baf 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal struct User: Codable, Hashable { @@ -30,4 +33,28 @@ internal struct User: Codable, Hashable { self.userStatus = userStatus } + internal enum CodingKeys: String, CodingKey, CaseIterable { + case id + case username + case firstName + case lastName + case email + case password + case phone + case userStatus + } + + // Encodable protocol methods + + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(username, forKey: .username) + try container.encodeIfPresent(firstName, forKey: .firstName) + try container.encodeIfPresent(lastName, forKey: .lastName) + try container.encodeIfPresent(email, forKey: .email) + try container.encodeIfPresent(password, forKey: .password) + try container.encodeIfPresent(phone, forKey: .phone) + try container.encodeIfPresent(userStatus, forKey: .userStatus) + } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index c8ac98f20266..05391a8fe6b9 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,7 +93,7 @@ internal class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override internal func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override internal func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() @@ -205,16 +205,18 @@ internal class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ internal class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ internal class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ internal class URLSessionDecodableRequestBuilder: URLSessionReques completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md b/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md index 3b14781480ff..b922f6ff7061 100644 --- a/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md @@ -384,7 +384,7 @@ let float = 987 // Float | None (optional) let double = 987 // Double | None let string = "string_example" // String | None (optional) let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let binary = URL(string: "https://example.com")! // URL | None (optional) let date = Date() // Date | None (optional) let dateTime = Date() // Date | None (optional) diff --git a/samples/client/petstore/swift5/nonPublicApi/project.yml b/samples/client/petstore/swift5/nonPublicApi/project.yml index 8e7102001b8d..0493cf65896e 100644 --- a/samples/client/petstore/swift5/nonPublicApi/project.yml +++ b/samples/client/petstore/swift5/nonPublicApi/project.yml @@ -11,4 +11,5 @@ targets: settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - + dependencies: + - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/objcCompatible/.openapi-generator/VERSION b/samples/client/petstore/swift5/objcCompatible/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/swift5/objcCompatible/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/objcCompatible/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/objcCompatible/Cartfile b/samples/client/petstore/swift5/objcCompatible/Cartfile index 8b137891791f..843f7adc7794 100644 --- a/samples/client/petstore/swift5/objcCompatible/Cartfile +++ b/samples/client/petstore/swift5/objcCompatible/Cartfile @@ -1 +1,2 @@ +github "Flight-School/AnyCodable" ~> 0.6.0 diff --git a/samples/client/petstore/swift5/objcCompatible/Package.resolved b/samples/client/petstore/swift5/objcCompatible/Package.resolved new file mode 100644 index 000000000000..d384b276b4bc --- /dev/null +++ b/samples/client/petstore/swift5/objcCompatible/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/objcCompatible/Package.swift b/samples/client/petstore/swift5/objcCompatible/Package.swift index b7fe4734aa8a..5cde507bdcf9 100644 --- a/samples/client/petstore/swift5/objcCompatible/Package.swift +++ b/samples/client/petstore/swift5/objcCompatible/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.0 +// swift-tools-version:5.1 import PackageDescription @@ -19,13 +19,14 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.6.0")), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "PetstoreClient", - dependencies: [], + dependencies: ["AnyCodable", ], path: "PetstoreClient/Classes" ), ] diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient.podspec b/samples/client/petstore/swift5/objcCompatible/PetstoreClient.podspec index b61285f6b25e..60f05891b241 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient.podspec @@ -11,4 +11,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.0' end diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift index dbdab491ff7d..01bc6ff0d8d0 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,7 +6,10 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index e1c068f26274..440c9b339a79 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -15,7 +15,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -35,10 +35,10 @@ import Foundation */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -46,9 +46,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 0af3b8d55a8c..4d94d2c69131 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -14,7 +14,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -33,10 +33,10 @@ import Foundation */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -44,9 +44,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -55,7 +55,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -74,10 +74,10 @@ import Foundation */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -85,9 +85,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -96,7 +96,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -115,10 +115,10 @@ import Foundation */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -126,9 +126,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -137,7 +137,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -156,10 +156,10 @@ import Foundation */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -167,9 +167,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -178,7 +178,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -197,10 +197,10 @@ import Foundation */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -208,9 +208,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -220,7 +220,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -239,11 +239,11 @@ import Foundation */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) @@ -253,9 +253,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -265,7 +265,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -285,10 +285,10 @@ import Foundation */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -296,9 +296,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -321,7 +321,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -357,7 +357,7 @@ import Foundation */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), @@ -378,7 +378,7 @@ import Foundation let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -386,9 +386,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -472,7 +472,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -499,7 +499,7 @@ import Foundation */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), @@ -508,8 +508,8 @@ import Foundation let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), @@ -524,9 +524,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -541,7 +541,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -566,11 +566,11 @@ import Foundation */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), @@ -584,9 +584,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -596,7 +596,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -615,10 +615,10 @@ import Foundation */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -626,9 +626,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -639,7 +639,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -659,7 +659,7 @@ import Foundation */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), @@ -668,7 +668,7 @@ import Foundation let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -676,9 +676,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 7115a294b030..36099b5f1a35 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -15,7 +15,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -38,10 +38,10 @@ import Foundation */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 7dc0f6ecde4e..1bdfc19cd71f 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -15,7 +15,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -37,10 +37,10 @@ import Foundation */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -48,9 +48,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -61,7 +61,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -87,10 +87,10 @@ import Foundation let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), @@ -98,9 +98,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -119,7 +119,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -142,11 +142,11 @@ import Foundation */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) @@ -156,9 +156,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -169,7 +169,7 @@ import Foundation - parameter completion: completion handler to receive the data and the error objects */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -193,11 +193,11 @@ import Foundation @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) @@ -207,9 +207,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -219,7 +219,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -245,10 +245,10 @@ import Foundation let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -256,9 +256,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -268,7 +268,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -290,10 +290,10 @@ import Foundation */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -301,9 +301,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -315,7 +315,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -342,7 +342,7 @@ import Foundation let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), @@ -351,7 +351,7 @@ import Foundation let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -359,9 +359,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -373,7 +373,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -400,7 +400,7 @@ import Foundation let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), @@ -409,7 +409,7 @@ import Foundation let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -417,9 +417,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -431,7 +431,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -458,7 +458,7 @@ import Foundation let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), @@ -467,7 +467,7 @@ import Foundation let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -475,9 +475,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 2abb82081dde..4acac5ebd4fc 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -15,7 +15,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -38,10 +38,10 @@ import Foundation let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -60,7 +60,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -82,10 +82,10 @@ import Foundation */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -93,9 +93,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -105,7 +105,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -128,10 +128,10 @@ import Foundation let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -139,9 +139,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -151,7 +151,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -170,10 +170,10 @@ import Foundation */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -181,9 +181,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 1b384965e079..fb331f2a38d4 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -15,7 +15,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -35,10 +35,10 @@ import Foundation */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { let path = "/user" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -46,9 +46,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -58,7 +58,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -77,10 +77,10 @@ import Foundation */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -88,9 +88,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -100,7 +100,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -119,10 +119,10 @@ import Foundation */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -130,9 +130,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -142,7 +142,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -165,10 +165,10 @@ import Foundation let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -176,9 +176,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -188,7 +188,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -210,10 +210,10 @@ import Foundation let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -221,9 +221,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -234,7 +234,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -255,11 +255,11 @@ import Foundation */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) @@ -270,9 +270,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -281,7 +281,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -299,10 +299,10 @@ import Foundation */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -310,9 +310,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -323,7 +323,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -347,10 +347,10 @@ import Foundation let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -358,9 +358,9 @@ import Foundation let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 93ed6b90b376..e23035dde30e 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,6 +5,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -52,6 +55,12 @@ extension Array: JSONEncodable { } } +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + extension Dictionary: JSONEncodable { func encodeToJSON() -> Any { var dictionary = [AnyHashable: Any]() diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 620f778bcc9a..3b250581cc15 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class AdditionalPropertiesClass: NSObject, Codable { @@ -22,4 +25,11 @@ import Foundation case mapMapString = "map_map_string" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapString, forKey: .mapString) + try container.encodeIfPresent(mapMapString, forKey: .mapMapString) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 528d7f886c0b..c8bc6f8fd9b6 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class Animal: NSObject, Codable { @@ -22,4 +25,11 @@ import Foundation case color } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(_className, forKey: ._className) + try container.encodeIfPresent(color, forKey: .color) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index e09b0e9efdc8..a0b09cb97615 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,5 +6,8 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 38334c39011c..9feb0336458b 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class ApiResponse: NSObject, Codable { @@ -24,4 +27,18 @@ import Foundation self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { + case code + case type + case message + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(code, forKey: .code) + try container.encodeIfPresent(type, forKey: .type) + try container.encodeIfPresent(message, forKey: .message) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 8ef73e96f019..acab776dfa1a 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class ArrayOfArrayOfNumberOnly: NSObject, Codable { @@ -19,4 +22,10 @@ import Foundation case arrayArrayNumber = "ArrayArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index dd95bb5be0cd..d44e23a7567e 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class ArrayOfNumberOnly: NSObject, Codable { @@ -19,4 +22,10 @@ import Foundation case arrayNumber = "ArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index 7b93023aa354..2ed77dba0afd 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class ArrayTest: NSObject, Codable { @@ -25,4 +28,12 @@ import Foundation case arrayArrayOfModel = "array_array_of_model" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayOfString, forKey: .arrayOfString) + try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) + try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index 2b42d0b45862..c7c00b23f7c2 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class Capitalization: NSObject, Codable { @@ -35,4 +38,15 @@ import Foundation case ATT_NAME } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(smallCamel, forKey: .smallCamel) + try container.encodeIfPresent(capitalCamel, forKey: .capitalCamel) + try container.encodeIfPresent(smallSnake, forKey: .smallSnake) + try container.encodeIfPresent(capitalSnake, forKey: .capitalSnake) + try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) + try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 5542ffa7de75..9f34145e79f9 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class Cat: NSObject, Codable { @@ -30,4 +33,12 @@ import Foundation case declawed } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(_className, forKey: ._className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index 6a4b10e996c1..32fe1b1e59fe 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class CatAllOf: NSObject, Codable { @@ -20,4 +23,14 @@ import Foundation self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 0e034abbf725..fd5f886af43b 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class Category: NSObject, Codable { @@ -15,9 +18,9 @@ import Foundation return _id as NSNumber? } } - public var name: String = "default-name" + public var name: String? = "default-name" - public init(_id: Int64? = nil, name: String = "default-name") { + public init(_id: Int64? = nil, name: String? = "default-name") { self._id = _id self.name = name } @@ -27,4 +30,11 @@ import Foundation case name } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_id, forKey: ._id) + try container.encode(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index 648f3a6bfb5a..10b0983599dd 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model with \"_class\" property */ @objc public class ClassModel: NSObject, Codable { @@ -16,4 +19,14 @@ import Foundation self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { + case _class + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_class, forKey: ._class) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 4c1efdd41407..c6f66fc19cb6 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class Client: NSObject, Codable { @@ -15,4 +18,14 @@ import Foundation self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { + case client + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(client, forKey: .client) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index be6118ef423f..baaa824e4e14 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class Dog: NSObject, Codable { @@ -25,4 +28,12 @@ import Foundation case breed } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(_className, forKey: ._className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 41c63007088d..8e4ca3185812 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class DogAllOf: NSObject, Codable { @@ -15,4 +18,14 @@ import Foundation self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 6e8c9d0f9abc..317ec4f86281 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class EnumArrays: NSObject, Codable { @@ -30,4 +33,11 @@ import Foundation case arrayEnum = "array_enum" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justSymbol, forKey: .justSymbol) + try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index d4029d73f8af..6ea2895aee53 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index dd3e83306c3d..39f68239e4d3 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class EnumTest: NSObject, Codable { @@ -49,4 +52,14 @@ import Foundation case outerEnum } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(enumString, forKey: .enumString) + try container.encode(enumStringRequired, forKey: .enumStringRequired) + try container.encodeIfPresent(enumInteger, forKey: .enumInteger) + try container.encodeIfPresent(enumNumber, forKey: .enumNumber) + try container.encodeIfPresent(outerEnum, forKey: .outerEnum) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/File.swift index 5124dd3b089d..b1f58093b024 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Must be named `File` for test. */ @objc public class File: NSObject, Codable { @@ -17,4 +20,14 @@ import Foundation self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { + case sourceURI + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(sourceURI, forKey: .sourceURI) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index be5963357fdc..c766f63637d1 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class FileSchemaTestClass: NSObject, Codable { @@ -17,4 +20,16 @@ import Foundation self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { + case file + case files + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(file, forKey: .file) + try container.encodeIfPresent(files, forKey: .files) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index 84f419103a41..70920c84fa8c 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class FormatTest: NSObject, Codable { @@ -64,4 +67,38 @@ import Foundation self.password = password } + public enum CodingKeys: String, CodingKey, CaseIterable { + case integer + case int32 + case int64 + case number + case float + case double + case string + case byte + case binary + case date + case dateTime + case uuid + case password + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(integer, forKey: .integer) + try container.encodeIfPresent(int32, forKey: .int32) + try container.encodeIfPresent(int64, forKey: .int64) + try container.encode(number, forKey: .number) + try container.encodeIfPresent(float, forKey: .float) + try container.encodeIfPresent(double, forKey: .double) + try container.encodeIfPresent(string, forKey: .string) + try container.encode(byte, forKey: .byte) + try container.encodeIfPresent(binary, forKey: .binary) + try container.encode(date, forKey: .date) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encode(password, forKey: .password) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index 7ca91927af7e..f491a19800eb 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class HasOnlyReadOnly: NSObject, Codable { @@ -17,4 +20,16 @@ import Foundation self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case foo + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(foo, forKey: .foo) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift index 7a977c19c7c7..baad1d10fe02 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class List: NSObject, Codable { @@ -19,4 +22,10 @@ import Foundation case _123list = "123-list" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_123list, forKey: ._123list) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index ba407e3ea25d..b095210c3f62 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class MapTest: NSObject, Codable { @@ -32,4 +35,13 @@ import Foundation case indirectMap = "indirect_map" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapMapOfString, forKey: .mapMapOfString) + try container.encodeIfPresent(mapOfEnumString, forKey: .mapOfEnumString) + try container.encodeIfPresent(directMap, forKey: .directMap) + try container.encodeIfPresent(indirectMap, forKey: .indirectMap) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index bd503cb36fce..d3b667779241 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class MixedPropertiesAndAdditionalPropertiesClass: NSObject, Codable { @@ -19,4 +22,18 @@ import Foundation self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { + case uuid + case dateTime + case map + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(map, forKey: .map) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 89c612262d2f..6abc550286bb 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name starting with number */ @objc public class Model200Response: NSObject, Codable { @@ -28,4 +31,11 @@ import Foundation case _class = "class" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(_class, forKey: ._class) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 15b0507a4785..1544a22cda58 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name same as property name */ @objc public class Name: NSObject, Codable { @@ -39,4 +42,13 @@ import Foundation case _123number = "123Number" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encodeIfPresent(snakeCase, forKey: .snakeCase) + try container.encodeIfPresent(property, forKey: .property) + try container.encodeIfPresent(_123number, forKey: ._123number) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 40fa7365d0ac..9e5280165f9f 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class NumberOnly: NSObject, Codable { @@ -19,4 +22,10 @@ import Foundation case justNumber = "JustNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justNumber, forKey: .justNumber) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 728a81434a73..d04a6cdab99a 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class Order: NSObject, Codable { @@ -60,4 +63,15 @@ import Foundation case complete } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_id, forKey: ._id) + try container.encodeIfPresent(petId, forKey: .petId) + try container.encodeIfPresent(quantity, forKey: .quantity) + try container.encodeIfPresent(shipDate, forKey: .shipDate) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(complete, forKey: .complete) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 9238070c2cb1..6521635743e8 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class OuterComposite: NSObject, Codable { @@ -30,4 +33,12 @@ import Foundation case myBoolean = "my_boolean" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(myNumber, forKey: .myNumber) + try container.encodeIfPresent(myString, forKey: .myString) + try container.encodeIfPresent(myBoolean, forKey: .myBoolean) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index c3b778cbbed4..76c34b3c2ce6 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index e17ada14c425..1339931a0735 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class Pet: NSObject, Codable { @@ -45,4 +48,15 @@ import Foundation case status } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_id, forKey: ._id) + try container.encodeIfPresent(category, forKey: .category) + try container.encode(name, forKey: .name) + try container.encode(photoUrls, forKey: .photoUrls) + try container.encodeIfPresent(tags, forKey: .tags) + try container.encodeIfPresent(status, forKey: .status) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index c16846f4ac19..7d3b2e5c9b3c 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class ReadOnlyFirst: NSObject, Codable { @@ -17,4 +20,16 @@ import Foundation self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case baz + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(baz, forKey: .baz) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index e589a9c20048..aa7cae020161 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing reserved words */ @objc public class Return: NSObject, Codable { @@ -25,4 +28,10 @@ import Foundation case _return = "return" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_return, forKey: ._return) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index 41b2bf459eff..c2ba68d894c6 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class SpecialModelName: NSObject, Codable { @@ -24,4 +27,10 @@ import Foundation case specialPropertyName = "$special[property.name]" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index ffe9730a6fe4..9ca13a19d8ef 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,9 +6,16 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class StringBooleanMap: NSObject, Codable { + + public enum CodingKeys: CodingKey, CaseIterable { + } + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -27,19 +34,18 @@ import Foundation // Encodable protocol methods public func encode(to encoder: Encoder) throws { - - var container = encoder.container(keyedBy: String.self) - - try container.encodeMap(additionalProperties) + var container = encoder.container(keyedBy: CodingKeys.self) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) } // Decodable protocol methods public required init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index fc02765d30e2..de3f7c181c4d 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class Tag: NSObject, Codable { @@ -27,4 +30,11 @@ import Foundation case name } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_id, forKey: ._id) + try container.encodeIfPresent(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index 5900ded6aad4..4882236d3e16 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class TypeHolderDefault: NSObject, Codable { @@ -31,4 +34,14 @@ import Foundation case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index 40e3a41c34d9..17dfc262df35 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class TypeHolderExample: NSObject, Codable { @@ -31,4 +34,14 @@ import Foundation case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift index 5b9831507979..8b9ef462778d 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc public class User: NSObject, Codable { @@ -51,4 +54,17 @@ import Foundation case userStatus } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_id, forKey: ._id) + try container.encodeIfPresent(username, forKey: .username) + try container.encodeIfPresent(firstName, forKey: .firstName) + try container.encodeIfPresent(lastName, forKey: .lastName) + try container.encodeIfPresent(email, forKey: .email) + try container.encodeIfPresent(password, forKey: .password) + try container.encodeIfPresent(phone, forKey: .phone) + try container.encodeIfPresent(userStatus, forKey: .userStatus) + } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 52b2071ec1aa..774c0427eaa2 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,7 +93,7 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md b/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md index 712fa591f2f4..779e16b3ce63 100644 --- a/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md @@ -379,7 +379,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) diff --git a/samples/client/petstore/swift5/objcCompatible/project.yml b/samples/client/petstore/swift5/objcCompatible/project.yml index 8e7102001b8d..0493cf65896e 100644 --- a/samples/client/petstore/swift5/objcCompatible/project.yml +++ b/samples/client/petstore/swift5/objcCompatible/project.yml @@ -11,4 +11,5 @@ targets: settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - + dependencies: + - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/oneOf/.gitignore b/samples/client/petstore/swift5/oneOf/.gitignore new file mode 100644 index 000000000000..5e5d5cebcf47 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/.gitignore @@ -0,0 +1,63 @@ +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## Build generated +build/ +DerivedData + +## Various settings +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata + +## Other +*.xccheckout +*.moved-aside +*.xcuserstate +*.xcscmblueprint + +## Obj-C/Swift specific +*.hmap +*.ipa + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +.build/ + +# CocoaPods +# +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# +# Pods/ + +# Carthage +# +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build + +# fastlane +# +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md + +fastlane/report.xml +fastlane/screenshots diff --git a/samples/client/petstore/swift5/oneOf/.openapi-generator-ignore b/samples/client/petstore/swift5/oneOf/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/swift5/oneOf/.openapi-generator/FILES b/samples/client/petstore/swift5/oneOf/.openapi-generator/FILES new file mode 100644 index 000000000000..421958ec1d26 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/.openapi-generator/FILES @@ -0,0 +1,26 @@ +.gitignore +Cartfile +Package.swift +PetstoreClient.podspec +PetstoreClient/Classes/OpenAPIs/APIHelper.swift +PetstoreClient/Classes/OpenAPIs/APIs.swift +PetstoreClient/Classes/OpenAPIs/APIs/DefaultAPI.swift +PetstoreClient/Classes/OpenAPIs/CodableHelper.swift +PetstoreClient/Classes/OpenAPIs/Configuration.swift +PetstoreClient/Classes/OpenAPIs/Extensions.swift +PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift +PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift +PetstoreClient/Classes/OpenAPIs/Models.swift +PetstoreClient/Classes/OpenAPIs/Models/Apple.swift +PetstoreClient/Classes/OpenAPIs/Models/Banana.swift +PetstoreClient/Classes/OpenAPIs/Models/Fruit.swift +PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift +PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +README.md +docs/Apple.md +docs/Banana.md +docs/DefaultAPI.md +docs/Fruit.md +git_push.sh +project.yml diff --git a/samples/client/petstore/swift5/oneOf/.openapi-generator/VERSION b/samples/client/petstore/swift5/oneOf/.openapi-generator/VERSION new file mode 100644 index 000000000000..6555596f9311 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/oneOf/Cartfile b/samples/client/petstore/swift5/oneOf/Cartfile new file mode 100644 index 000000000000..843f7adc7794 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/Cartfile @@ -0,0 +1,2 @@ + +github "Flight-School/AnyCodable" ~> 0.6.0 diff --git a/samples/client/petstore/swift5/oneOf/Package.swift b/samples/client/petstore/swift5/oneOf/Package.swift new file mode 100644 index 000000000000..5cde507bdcf9 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/Package.swift @@ -0,0 +1,33 @@ +// swift-tools-version:5.1 + +import PackageDescription + +let package = Package( + name: "PetstoreClient", + platforms: [ + .iOS(.v9), + .macOS(.v10_11), + .tvOS(.v9), + .watchOS(.v3), + ], + products: [ + // Products define the executables and libraries produced by a package, and make them visible to other packages. + .library( + name: "PetstoreClient", + targets: ["PetstoreClient"] + ), + ], + dependencies: [ + // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.6.0")), + ], + targets: [ + // Targets are the basic building blocks of a package. A target can define a module or a test suite. + // Targets can depend on other targets in this package, and on products in packages which this package depends on. + .target( + name: "PetstoreClient", + dependencies: ["AnyCodable", ], + path: "PetstoreClient/Classes" + ), + ] +) diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient.podspec b/samples/client/petstore/swift5/oneOf/PetstoreClient.podspec new file mode 100644 index 000000000000..8355c5f50e6d --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient.podspec @@ -0,0 +1,15 @@ +Pod::Spec.new do |s| + s.name = 'PetstoreClient' + s.ios.deployment_target = '9.0' + s.osx.deployment_target = '10.11' + s.tvos.deployment_target = '9.0' + s.watchos.deployment_target = '3.0' + s.version = '0.0.1' + s.source = { :git => 'git@github.com:OpenAPITools/openapi-generator.git', :tag => 'v0.0.1' } + s.authors = '' + s.license = 'Proprietary' + s.homepage = 'https://github.com/openapitools/openapi-generator' + s.summary = 'PetstoreClient' + s.source_files = 'PetstoreClient/Classes/**/*.swift' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.0' +end diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIHelper.swift similarity index 100% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIHelper.swift diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs.swift new file mode 100644 index 000000000000..7935d8a9fa6a --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -0,0 +1,65 @@ +// APIs.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { + public static var basePath = "http://localhost" + public static var credential: URLCredential? + public static var customHeaders: [String: String] = [:] + public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory() + public static var apiResponseQueue: DispatchQueue = .main +} + +open class RequestBuilder { + var credential: URLCredential? + var headers: [String: String] + public let parameters: [String: Any]? + public let method: String + public let URLString: String + + /// Optional block to obtain a reference to the request's progress instance when available. + /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. + /// If you need to get the request's progress in older OS versions, please use Alamofire http client. + public var onProgressReady: ((Progress) -> Void)? + + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.headers = headers + + addHeaders(PetstoreClient.customHeaders) + } + + open func addHeaders(_ aHeaders: [String: String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + + public func addHeader(name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + open func addCredential() -> Self { + credential = PetstoreClient.credential + return self + } +} + +public protocol RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type +} diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs/DefaultAPI.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs/DefaultAPI.swift new file mode 100644 index 000000000000..5e6a278c0d02 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs/DefaultAPI.swift @@ -0,0 +1,49 @@ +// +// DefaultAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +open class DefaultAPI { + /** + + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func rootGet(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Fruit?, _ error: Error?) -> Void)) { + rootGetWithRequestBuilder().execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - GET / + - returns: RequestBuilder + */ + open class func rootGetWithRequestBuilder() -> RequestBuilder { + let path = "/" + let URLString = PetstoreClient.basePath + path + let parameters: [String: Any]? = nil + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift similarity index 100% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Configuration.swift similarity index 100% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Configuration.swift diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift similarity index 96% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 93ed6b90b376..e23035dde30e 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,6 +5,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -52,6 +55,12 @@ extension Array: JSONEncodable { } } +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + extension Dictionary: JSONEncodable { func encodeToJSON() -> Any { var dictionary = [AnyHashable: Any]() diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift similarity index 100% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift similarity index 100% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift similarity index 100% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Apple.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Apple.swift new file mode 100644 index 000000000000..17495d47fd35 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Apple.swift @@ -0,0 +1,31 @@ +// +// Apple.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Apple: Codable, Hashable { + + public var kind: String? + + public init(kind: String? = nil) { + self.kind = kind + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case kind + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(kind, forKey: .kind) + } +} diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Banana.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Banana.swift new file mode 100644 index 000000000000..c0a23db0b1c5 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Banana.swift @@ -0,0 +1,31 @@ +// +// Banana.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Banana: Codable, Hashable { + + public var count: Double? + + public init(count: Double? = nil) { + self.count = count + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case count + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(count, forKey: .count) + } +} diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Fruit.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Fruit.swift new file mode 100644 index 000000000000..d58ad1f8b319 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Fruit.swift @@ -0,0 +1,38 @@ +// +// Fruit.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public enum Fruit: Codable { + case typeApple(Apple) + case typeBanana(Banana) + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .typeApple(let value): + try container.encode(value) + case .typeBanana(let value): + try container.encode(value) + } + } + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + if let value = try? container.decode(Apple.self) { + self = .typeApple(value) + } else if let value = try? container.decode(Banana.self) { + self = .typeBanana(value) + } else { + throw DecodingError.typeMismatch(Self.Type.self, .init(codingPath: decoder.codingPath, debugDescription: "Unable to decode instance of Fruit")) + } + } +} + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift similarity index 100% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift similarity index 100% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift similarity index 90% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 52b2071ec1aa..774c0427eaa2 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,7 +93,7 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/oneOf/README.md b/samples/client/petstore/swift5/oneOf/README.md new file mode 100644 index 000000000000..58f7c7f65ce2 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/README.md @@ -0,0 +1,46 @@ +# Swift5 API client for PetstoreClient + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 0.0.1 +- Package version: +- Build package: org.openapitools.codegen.languages.Swift5ClientCodegen + +## Installation + +### Carthage + +Run `carthage update` + +### CocoaPods + +Run `pod install` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultAPI* | [**rootGet**](docs/DefaultAPI.md#rootget) | **GET** / | + + +## Documentation For Models + + - [Apple](docs/Apple.md) + - [Banana](docs/Banana.md) + - [Fruit](docs/Fruit.md) + + +## Documentation For Authorization + + All endpoints do not require authorization. + + +## Author + + + diff --git a/samples/client/petstore/swift5/oneOf/docs/Apple.md b/samples/client/petstore/swift5/oneOf/docs/Apple.md new file mode 100644 index 000000000000..12ead3f7cb0d --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/docs/Apple.md @@ -0,0 +1,11 @@ +# Apple + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **String** | | [optional] +**color** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/oneOf/docs/Banana.md b/samples/client/petstore/swift5/oneOf/docs/Banana.md new file mode 100644 index 000000000000..e194ddc30d41 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/docs/Banana.md @@ -0,0 +1,11 @@ +# Banana + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**count** | **Double** | | [optional] +**color** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/oneOf/docs/DefaultAPI.md b/samples/client/petstore/swift5/oneOf/docs/DefaultAPI.md new file mode 100644 index 000000000000..bcefe1e3ffa1 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/docs/DefaultAPI.md @@ -0,0 +1,52 @@ +# DefaultAPI + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**rootGet**](DefaultAPI.md#rootget) | **GET** / | + + +# **rootGet** +```swift + open class func rootGet(completion: @escaping (_ data: Fruit?, _ error: Error?) -> Void) +``` + + + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + + +DefaultAPI.rootGet() { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Fruit**](Fruit.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/swift5/oneOf/docs/Fruit.md b/samples/client/petstore/swift5/oneOf/docs/Fruit.md new file mode 100644 index 000000000000..3efd863258b7 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/docs/Fruit.md @@ -0,0 +1,12 @@ +# Fruit + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**color** | **String** | | [optional] +**kind** | **String** | | [optional] +**count** | **Double** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/oneOf/git_push.sh b/samples/client/petstore/swift5/oneOf/git_push.sh new file mode 100644 index 000000000000..ced3be2b0c7b --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/git_push.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/swift5/oneOf/project.yml b/samples/client/petstore/swift5/oneOf/project.yml new file mode 100644 index 000000000000..1949ec8ed3b6 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/project.yml @@ -0,0 +1,15 @@ +name: PetstoreClient +targets: + PetstoreClient: + type: framework + platform: iOS + deploymentTarget: "9.0" + sources: [PetstoreClient] + info: + path: ./Info.plist + version: 0.0.1 + settings: + APPLICATION_EXTENSION_API_ONLY: true + scheme: {} + dependencies: + - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/promisekitLibrary/Cartfile b/samples/client/petstore/swift5/promisekitLibrary/Cartfile index 9a00bb83e5b9..e8692e8c2045 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/Cartfile +++ b/samples/client/petstore/swift5/promisekitLibrary/Cartfile @@ -1,2 +1,3 @@ -github "mxcl/PromiseKit" ~> 6.13.1 +github "mxcl/PromiseKit" ~> 6.15.3 +github "Flight-School/AnyCodable" ~> 0.6.0 diff --git a/samples/client/petstore/swift5/promisekitLibrary/Package.resolved b/samples/client/petstore/swift5/promisekitLibrary/Package.resolved index b74611fc3d6e..63ce26f05eba 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/Package.resolved +++ b/samples/client/petstore/swift5/promisekitLibrary/Package.resolved @@ -1,13 +1,22 @@ { "object": { "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + }, { "package": "PromiseKit", "repositoryURL": "https://github.com/mxcl/PromiseKit.git", "state": { "branch": null, - "revision": "80963d4317bcdc03891e0fbaa744f20511d1bc08", - "version": "6.12.0" + "revision": "d2f7ba14bcdc45e18f4f60ad9df883fb9055f081", + "version": "6.15.3" } } ] diff --git a/samples/client/petstore/swift5/promisekitLibrary/Package.swift b/samples/client/petstore/swift5/promisekitLibrary/Package.swift index 959c7bdaf458..831b4d0a740c 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/Package.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.0 +// swift-tools-version:5.1 import PackageDescription @@ -19,14 +19,15 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/mxcl/PromiseKit.git", from: "6.12.0"), + .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.6.0")), + .package(url: "https://github.com/mxcl/PromiseKit.git", from: "6.15.3"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "PetstoreClient", - dependencies: ["PromiseKit", ], + dependencies: ["AnyCodable", "PromiseKit", ], path: "PetstoreClient/Classes" ), ] diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient.podspec b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient.podspec index 92e54fcfeb77..5e3450043c00 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient.podspec @@ -11,5 +11,6 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' - s.dependency 'PromiseKit/CorePromise', '~> 6.13.1' + s.dependency 'PromiseKit/CorePromise', '~> 6.15.3' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.0' end diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index dbdab491ff7d..01bc6ff0d8d0 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,7 +6,10 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 841595419898..72ecfdc6f768 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -16,7 +16,7 @@ open class AnotherFakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func call123testSpecialTags( body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func call123testSpecialTags( body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -38,10 +38,10 @@ open class AnotherFakeAPI { */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ open class AnotherFakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index b87b809198bc..89d44314c534 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -15,7 +15,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func fakeOuterBooleanSerialize( body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func fakeOuterBooleanSerialize( body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -36,10 +36,10 @@ open class FakeAPI { */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -47,9 +47,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -58,7 +58,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func fakeOuterCompositeSerialize( body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func fakeOuterCompositeSerialize( body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -79,10 +79,10 @@ open class FakeAPI { */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -90,9 +90,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -101,7 +101,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func fakeOuterNumberSerialize( body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func fakeOuterNumberSerialize( body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -122,10 +122,10 @@ open class FakeAPI { */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -133,9 +133,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -144,7 +144,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func fakeOuterStringSerialize( body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func fakeOuterStringSerialize( body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -165,10 +165,10 @@ open class FakeAPI { */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -176,9 +176,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -187,7 +187,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testBodyWithFileSchema( body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testBodyWithFileSchema( body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -208,10 +208,10 @@ open class FakeAPI { */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -219,9 +219,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -231,7 +231,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testBodyWithQueryParams( query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testBodyWithQueryParams( query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -252,11 +252,11 @@ open class FakeAPI { */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) @@ -266,9 +266,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -278,7 +278,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testClientModel( body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testClientModel( body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -300,10 +300,10 @@ open class FakeAPI { */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -311,9 +311,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -336,7 +336,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testEndpointParameters( number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testEndpointParameters( number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute(apiResponseQueue) { result -> Void in switch result { @@ -374,7 +374,7 @@ open class FakeAPI { */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), @@ -395,7 +395,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -403,9 +403,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -489,7 +489,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testEnumParameters( enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testEnumParameters( enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { @@ -518,7 +518,7 @@ open class FakeAPI { */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), @@ -527,8 +527,8 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), @@ -543,9 +543,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -560,7 +560,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testGroupParameters( requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testGroupParameters( requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { @@ -587,11 +587,11 @@ open class FakeAPI { */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), @@ -605,9 +605,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -617,7 +617,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testInlineAdditionalProperties( param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testInlineAdditionalProperties( param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { @@ -638,10 +638,10 @@ open class FakeAPI { */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -649,9 +649,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -662,7 +662,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testJsonFormData( param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testJsonFormData( param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { @@ -684,7 +684,7 @@ open class FakeAPI { */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), @@ -693,7 +693,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -701,9 +701,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 6066f4ec8312..5cd88bffeae4 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -16,7 +16,7 @@ open class FakeClassnameTags123API { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testClassname( body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testClassname( body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -41,10 +41,10 @@ open class FakeClassnameTags123API { */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -52,9 +52,9 @@ open class FakeClassnameTags123API { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index e60028960c8b..2ca6128ac8dc 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -16,7 +16,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func addPet( body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func addPet( body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -40,10 +40,10 @@ open class PetAPI { */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -51,9 +51,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -64,7 +64,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func deletePet( petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func deletePet( petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { @@ -92,10 +92,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), @@ -103,9 +103,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -124,7 +124,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise<[Pet]> */ - open class func findPetsByStatus( status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise<[Pet]> { + open class func findPetsByStatus( status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise<[Pet]> { let deferred = Promise<[Pet]>.pending() findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { @@ -149,11 +149,11 @@ open class PetAPI { */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) @@ -163,9 +163,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -176,7 +176,7 @@ open class PetAPI { - returns: Promise<[Pet]> */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags( tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise<[Pet]> { + open class func findPetsByTags( tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise<[Pet]> { let deferred = Promise<[Pet]>.pending() findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { @@ -202,11 +202,11 @@ open class PetAPI { @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) @@ -216,9 +216,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -228,7 +228,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func getPetById( petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func getPetById( petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { @@ -256,10 +256,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -267,9 +267,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -279,7 +279,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func updatePet( body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func updatePet( body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -303,10 +303,10 @@ open class PetAPI { */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -314,9 +314,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -328,7 +328,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func updatePetWithForm( petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func updatePetWithForm( petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { @@ -357,7 +357,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), @@ -366,7 +366,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -374,9 +374,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -388,7 +388,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func uploadFile( petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func uploadFile( petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { @@ -417,7 +417,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), @@ -426,7 +426,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -434,9 +434,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -448,7 +448,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func uploadFileWithRequiredFile( petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func uploadFileWithRequiredFile( petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { @@ -477,7 +477,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), @@ -486,7 +486,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -494,9 +494,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index a76e39ab8f08..2a877b9fb576 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -16,7 +16,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func deleteOrder( orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func deleteOrder( orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { @@ -41,10 +41,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -52,9 +52,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -63,7 +63,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise<[String: Int]> */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise<[String: Int]> { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise<[String: Int]> { let deferred = Promise<[String: Int]>.pending() getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { @@ -87,10 +87,10 @@ open class StoreAPI { */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -98,9 +98,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -110,7 +110,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func getOrderById( orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func getOrderById( orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { @@ -135,10 +135,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -146,9 +146,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -158,7 +158,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func placeOrder( body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func placeOrder( body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -179,10 +179,10 @@ open class StoreAPI { */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -190,9 +190,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index b451a3404542..6b12f6a0b09b 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -16,7 +16,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func createUser( body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func createUser( body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -38,10 +38,10 @@ open class UserAPI { */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { let path = "/user" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -61,7 +61,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func createUsersWithArrayInput( body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func createUsersWithArrayInput( body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -82,10 +82,10 @@ open class UserAPI { */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -93,9 +93,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -105,7 +105,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func createUsersWithListInput( body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func createUsersWithListInput( body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -126,10 +126,10 @@ open class UserAPI { */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -137,9 +137,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -149,7 +149,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func deleteUser( username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func deleteUser( username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { @@ -174,10 +174,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -185,9 +185,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -197,7 +197,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func getUserByName( username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func getUserByName( username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { @@ -221,10 +221,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -232,9 +232,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -245,7 +245,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func loginUser( username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func loginUser( username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { @@ -268,11 +268,11 @@ open class UserAPI { */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) @@ -283,9 +283,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -294,7 +294,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { @@ -314,10 +314,10 @@ open class UserAPI { */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -325,9 +325,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -338,7 +338,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func updateUser( username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func updateUser( username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -364,10 +364,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -375,9 +375,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 736702ea5dd9..68c3c6ee7e40 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,6 +5,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif import PromiseKit extension Bool: JSONEncodable { @@ -53,6 +56,12 @@ extension Array: JSONEncodable { } } +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + extension Dictionary: JSONEncodable { func encodeToJSON() -> Any { var dictionary = [AnyHashable: Any]() diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 733b7bc51594..61a478de142b 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct AdditionalPropertiesClass: Codable, Hashable { @@ -22,4 +25,11 @@ public struct AdditionalPropertiesClass: Codable, Hashable { case mapMapString = "map_map_string" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapString, forKey: .mapString) + try container.encodeIfPresent(mapMapString, forKey: .mapMapString) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index e57c8b471765..157cca1d227b 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Animal: Codable, Hashable { @@ -17,4 +20,16 @@ public struct Animal: Codable, Hashable { self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index e09b0e9efdc8..a0b09cb97615 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,5 +6,8 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 630992f6231e..8607cbef1a33 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ApiResponse: Codable, Hashable { @@ -19,4 +22,18 @@ public struct ApiResponse: Codable, Hashable { self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { + case code + case type + case message + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(code, forKey: .code) + try container.encodeIfPresent(type, forKey: .type) + try container.encodeIfPresent(message, forKey: .message) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 4710793fc9a6..f3f161b44c1c 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { case arrayArrayNumber = "ArrayArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index a41968d9b199..d62de957472a 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayOfNumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct ArrayOfNumberOnly: Codable, Hashable { case arrayNumber = "ArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index f442ea725451..360d50d027f1 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayTest: Codable, Hashable { @@ -25,4 +28,12 @@ public struct ArrayTest: Codable, Hashable { case arrayArrayOfModel = "array_array_of_model" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayOfString, forKey: .arrayOfString) + try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) + try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index 44b50bbe0063..f0781a9cb738 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Capitalization: Codable, Hashable { @@ -35,4 +38,15 @@ public struct Capitalization: Codable, Hashable { case ATT_NAME } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(smallCamel, forKey: .smallCamel) + try container.encodeIfPresent(capitalCamel, forKey: .capitalCamel) + try container.encodeIfPresent(smallSnake, forKey: .smallSnake) + try container.encodeIfPresent(capitalSnake, forKey: .capitalSnake) + try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) + try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index c6bf4460da6e..d5519760387a 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Cat: Codable, Hashable { @@ -19,4 +22,18 @@ public struct Cat: Codable, Hashable { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index f9484f9bc8fd..8312680deb37 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct CatAllOf: Codable, Hashable { @@ -15,4 +18,14 @@ public struct CatAllOf: Codable, Hashable { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 6a19bb02d0df..398da60aa73b 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,15 +6,30 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Category: Codable, Hashable { public var id: Int64? - public var name: String = "default-name" + public var name: String? = "default-name" - public init(id: Int64? = nil, name: String = "default-name") { + public init(id: Int64? = nil, name: String? = "default-name") { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encode(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index 5c8e8882831f..03bf63e4cad1 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model with \"_class\" property */ public struct ClassModel: Codable, Hashable { @@ -16,4 +19,14 @@ public struct ClassModel: Codable, Hashable { self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { + case _class + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_class, forKey: ._class) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 1464b047c06a..596048780439 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Client: Codable, Hashable { @@ -15,4 +18,14 @@ public struct Client: Codable, Hashable { self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { + case client + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(client, forKey: .client) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index 5aed7834d537..4ada3ceb605a 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Dog: Codable, Hashable { @@ -19,4 +22,18 @@ public struct Dog: Codable, Hashable { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 716776261d30..f6c3d287301d 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct DogAllOf: Codable, Hashable { @@ -15,4 +18,14 @@ public struct DogAllOf: Codable, Hashable { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index aa13aa59f86a..0e0aad42abe6 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct EnumArrays: Codable, Hashable { @@ -30,4 +33,11 @@ public struct EnumArrays: Codable, Hashable { case arrayEnum = "array_enum" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justSymbol, forKey: .justSymbol) + try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index d4029d73f8af..6ea2895aee53 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 8b62febdc959..9e44926be9b8 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct EnumTest: Codable, Hashable { @@ -49,4 +52,14 @@ public struct EnumTest: Codable, Hashable { case outerEnum } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(enumString, forKey: .enumString) + try container.encode(enumStringRequired, forKey: .enumStringRequired) + try container.encodeIfPresent(enumInteger, forKey: .enumInteger) + try container.encodeIfPresent(enumNumber, forKey: .enumNumber) + try container.encodeIfPresent(outerEnum, forKey: .outerEnum) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift index aa14d762394d..11694b2ca59b 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Must be named `File` for test. */ public struct File: Codable, Hashable { @@ -17,4 +20,14 @@ public struct File: Codable, Hashable { self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { + case sourceURI + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(sourceURI, forKey: .sourceURI) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index 85987709776e..6aa85d8eecf9 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FileSchemaTestClass: Codable, Hashable { @@ -17,4 +20,16 @@ public struct FileSchemaTestClass: Codable, Hashable { self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { + case file + case files + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(file, forKey: .file) + try container.encodeIfPresent(files, forKey: .files) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index f09cb471b360..114c884efc5e 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FormatTest: Codable, Hashable { @@ -39,4 +42,38 @@ public struct FormatTest: Codable, Hashable { self.password = password } + public enum CodingKeys: String, CodingKey, CaseIterable { + case integer + case int32 + case int64 + case number + case float + case double + case string + case byte + case binary + case date + case dateTime + case uuid + case password + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(integer, forKey: .integer) + try container.encodeIfPresent(int32, forKey: .int32) + try container.encodeIfPresent(int64, forKey: .int64) + try container.encode(number, forKey: .number) + try container.encodeIfPresent(float, forKey: .float) + try container.encodeIfPresent(double, forKey: .double) + try container.encodeIfPresent(string, forKey: .string) + try container.encode(byte, forKey: .byte) + try container.encodeIfPresent(binary, forKey: .binary) + try container.encode(date, forKey: .date) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encode(password, forKey: .password) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index 03d35274a4ee..cb1a7456a7df 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct HasOnlyReadOnly: Codable, Hashable { @@ -17,4 +20,16 @@ public struct HasOnlyReadOnly: Codable, Hashable { self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case foo + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(foo, forKey: .foo) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift index f8f08e4c6c44..8ecdd3b02339 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct List: Codable, Hashable { @@ -19,4 +22,10 @@ public struct List: Codable, Hashable { case _123list = "123-list" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_123list, forKey: ._123list) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index bd4e7b97e81b..0ff74ed8400e 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct MapTest: Codable, Hashable { @@ -32,4 +35,13 @@ public struct MapTest: Codable, Hashable { case indirectMap = "indirect_map" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapMapOfString, forKey: .mapMapOfString) + try container.encodeIfPresent(mapOfEnumString, forKey: .mapOfEnumString) + try container.encodeIfPresent(directMap, forKey: .directMap) + try container.encodeIfPresent(indirectMap, forKey: .indirectMap) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index 80c1781a2bfc..58a0a54ca090 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { @@ -19,4 +22,18 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { + case uuid + case dateTime + case map + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(map, forKey: .map) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index d36d4e27352a..0f59769954f1 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name starting with number */ public struct Model200Response: Codable, Hashable { @@ -23,4 +26,11 @@ public struct Model200Response: Codable, Hashable { case _class = "class" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(_class, forKey: ._class) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 49cc57544179..d88c94f05c95 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name same as property name */ public struct Name: Codable, Hashable { @@ -29,4 +32,13 @@ public struct Name: Codable, Hashable { case _123number = "123Number" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encodeIfPresent(snakeCase, forKey: .snakeCase) + try container.encodeIfPresent(property, forKey: .property) + try container.encodeIfPresent(_123number, forKey: ._123number) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 6b024294e288..0f05482b9b7c 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct NumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct NumberOnly: Codable, Hashable { case justNumber = "JustNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justNumber, forKey: .justNumber) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 8ef7cb79e2c8..100d6b71fed4 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Order: Codable, Hashable { @@ -31,4 +34,24 @@ public struct Order: Codable, Hashable { self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case petId + case quantity + case shipDate + case status + case complete + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(petId, forKey: .petId) + try container.encodeIfPresent(quantity, forKey: .quantity) + try container.encodeIfPresent(shipDate, forKey: .shipDate) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(complete, forKey: .complete) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 9865764ff9bb..15a4e4a15b6e 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct OuterComposite: Codable, Hashable { @@ -25,4 +28,12 @@ public struct OuterComposite: Codable, Hashable { case myBoolean = "my_boolean" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(myNumber, forKey: .myNumber) + try container.encodeIfPresent(myString, forKey: .myString) + try container.encodeIfPresent(myBoolean, forKey: .myBoolean) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index c3b778cbbed4..76c34b3c2ce6 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 1bc823d3e960..a87ab825ea0b 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Pet: Codable, Hashable { @@ -31,4 +34,24 @@ public struct Pet: Codable, Hashable { self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case category + case name + case photoUrls + case tags + case status + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(category, forKey: .category) + try container.encode(name, forKey: .name) + try container.encode(photoUrls, forKey: .photoUrls) + try container.encodeIfPresent(tags, forKey: .tags) + try container.encodeIfPresent(status, forKey: .status) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 03b5b0dbf02b..6426deedf637 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ReadOnlyFirst: Codable, Hashable { @@ -17,4 +20,16 @@ public struct ReadOnlyFirst: Codable, Hashable { self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case baz + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(baz, forKey: .baz) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 5f539f461843..777c241bc0c0 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing reserved words */ public struct Return: Codable, Hashable { @@ -20,4 +23,10 @@ public struct Return: Codable, Hashable { case _return = "return" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_return, forKey: ._return) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index cb82d2ae3adc..b677523a7491 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct SpecialModelName: Codable, Hashable { @@ -19,4 +22,10 @@ public struct SpecialModelName: Codable, Hashable { case specialPropertyName = "$special[property.name]" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 77ab81f5f341..f575c9df65ca 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,9 +6,16 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct StringBooleanMap: Codable, Hashable { + + public enum CodingKeys: CodingKey, CaseIterable { + } + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -27,19 +34,18 @@ public struct StringBooleanMap: Codable, Hashable { // Encodable protocol methods public func encode(to encoder: Encoder) throws { - - var container = encoder.container(keyedBy: String.self) - - try container.encodeMap(additionalProperties) + var container = encoder.container(keyedBy: CodingKeys.self) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) } // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 8b8e24fc39c0..cd5acc827db7 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Tag: Codable, Hashable { @@ -17,4 +20,16 @@ public struct Tag: Codable, Hashable { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index f1920ef37788..341c9b4b8c2e 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct TypeHolderDefault: Codable, Hashable { @@ -31,4 +34,14 @@ public struct TypeHolderDefault: Codable, Hashable { case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index 1a23c1b486b8..04166af0895f 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct TypeHolderExample: Codable, Hashable { @@ -31,4 +34,14 @@ public struct TypeHolderExample: Codable, Hashable { case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift index f3b4f6bb958a..9f3ded8fcd93 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct User: Codable, Hashable { @@ -30,4 +33,28 @@ public struct User: Codable, Hashable { self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case username + case firstName + case lastName + case email + case password + case phone + case userStatus + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(username, forKey: .username) + try container.encodeIfPresent(firstName, forKey: .firstName) + try container.encodeIfPresent(lastName, forKey: .lastName) + try container.encodeIfPresent(email, forKey: .email) + try container.encodeIfPresent(password, forKey: .password) + try container.encodeIfPresent(phone, forKey: .phone) + try container.encodeIfPresent(userStatus, forKey: .userStatus) + } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 52b2071ec1aa..774c0427eaa2 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,7 +93,7 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/Podfile b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/Podfile deleted file mode 100644 index 77432f9eee92..000000000000 --- a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/Podfile +++ /dev/null @@ -1,13 +0,0 @@ -platform :ios, '9.0' - -source 'https://cdn.cocoapods.org/' - -use_frameworks! - -target 'SwaggerClient' do - pod "PetstoreClient", :path => "../" - - target 'SwaggerClientTests' do - inherit! :search_paths - end -end diff --git a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/Podfile.lock deleted file mode 100644 index c75f76b2fb89..000000000000 --- a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/Podfile.lock +++ /dev/null @@ -1,23 +0,0 @@ -PODS: - - PetstoreClient (1.0.0): - - PromiseKit/CorePromise (~> 6.13.1) - - PromiseKit/CorePromise (6.13.1) - -DEPENDENCIES: - - PetstoreClient (from `../`) - -SPEC REPOS: - trunk: - - PromiseKit - -EXTERNAL SOURCES: - PetstoreClient: - :path: "../" - -SPEC CHECKSUMS: - PetstoreClient: bf095c434cf89014d1b574779fcc7701a551fcce - PromiseKit: 28fda91c973cc377875d8c0ea4f973013c05b6db - -PODFILE CHECKSUM: 509bec696cc1d8641751b52e4fe4bef04ac4542c - -COCOAPODS: 1.10.0 diff --git a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 47fa20866cea..6013383e0d12 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -3,11 +3,10 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 52; objects = { /* Begin PBXBuildFile section */ - 54DA06C1D70D78EC0EC72B61 /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */; }; 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */; }; 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB961C692C6300B96B06 /* ViewController.swift */; }; 6D4EFB9A1C692C6300B96B06 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB981C692C6300B96B06 /* Main.storyboard */; }; @@ -16,7 +15,7 @@ 6D4EFBB51C693BE200B96B06 /* PetAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */; }; 6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */; }; 6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */; }; - 751C65B82F596107A3DC8ED9 /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */; }; + A5782C6B2664F87200CAA106 /* PetstoreClient in Frameworks */ = {isa = PBXBuildFile; productRef = A5782C6A2664F87200CAA106 /* PetstoreClient */; }; A5EA125C2419398500E30FC3 /* UIImage+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA125A2419398500E30FC3 /* UIImage+Extras.swift */; }; A5EA125D2419398500E30FC3 /* FileUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA125B2419398500E30FC3 /* FileUtils.swift */; }; /* End PBXBuildFile section */ @@ -32,7 +31,6 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 289E8A9E9C0BB66AD190C7C6 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwaggerClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 6D4EFB961C692C6300B96B06 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; @@ -45,14 +43,8 @@ 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = ""; }; 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = ""; }; 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; - 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A5EA125A2419398500E30FC3 /* UIImage+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIImage+Extras.swift"; sourceTree = ""; }; A5EA125B2419398500E30FC3 /* FileUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileUtils.swift; sourceTree = ""; }; - A638467ACFB30852DEA51F7A /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; - B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; - C07EC0A94AA0F86D60668B32 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -60,7 +52,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 751C65B82F596107A3DC8ED9 /* Pods_SwaggerClient.framework in Frameworks */, + A5782C6B2664F87200CAA106 /* PetstoreClient in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -68,30 +60,15 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 54DA06C1D70D78EC0EC72B61 /* Pods_SwaggerClientTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 0CAA98BEFA303B94D3664C7D /* Pods */ = { - isa = PBXGroup; - children = ( - A638467ACFB30852DEA51F7A /* Pods-SwaggerClient.debug.xcconfig */, - FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */, - 289E8A9E9C0BB66AD190C7C6 /* Pods-SwaggerClientTests.debug.xcconfig */, - B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */, - ); - name = Pods; - sourceTree = ""; - }; 3FABC56EC0BA84CBF4F99564 /* Frameworks */ = { isa = PBXGroup; children = ( - C07EC0A94AA0F86D60668B32 /* Pods.framework */, - 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */, - F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */, ); name = Frameworks; sourceTree = ""; @@ -103,7 +80,6 @@ 6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */, 6D4EFB921C692C6300B96B06 /* Products */, 3FABC56EC0BA84CBF4F99564 /* Frameworks */, - 0CAA98BEFA303B94D3664C7D /* Pods */, ); sourceTree = ""; }; @@ -149,17 +125,18 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */, 6D4EFB8D1C692C6300B96B06 /* Sources */, 6D4EFB8E1C692C6300B96B06 /* Frameworks */, 6D4EFB8F1C692C6300B96B06 /* Resources */, - 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( ); name = SwaggerClient; + packageProductDependencies = ( + A5782C6A2664F87200CAA106 /* PetstoreClient */, + ); productName = SwaggerClient; productReference = 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */; productType = "com.apple.product-type.application"; @@ -168,7 +145,6 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */, 6D4EFBA11C692C6300B96B06 /* Sources */, 6D4EFBA21C692C6300B96B06 /* Frameworks */, 6D4EFBA31C692C6300B96B06 /* Resources */, @@ -243,65 +219,6 @@ }; /* End PBXResourcesBuildPhase section */ -/* Begin PBXShellScriptBuildPhase section */ - 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClient-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/PetstoreClient/PetstoreClient.framework", - "${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PetstoreClient.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PromiseKit.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClientTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - /* Begin PBXSourcesBuildPhase section */ 6D4EFB8D1C692C6300B96B06 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -455,7 +372,8 @@ IPHONEOS_DEPLOYMENT_TARGET = 9.2; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; SWIFT_VERSION = 4.0; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; @@ -464,11 +382,13 @@ }; 6D4EFBAF1C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = A638467ACFB30852DEA51F7A /* Pods-SwaggerClient.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -477,11 +397,13 @@ }; 6D4EFBB01C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -490,11 +412,14 @@ }; 6D4EFBB21C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 289E8A9E9C0BB66AD190C7C6 /* Pods-SwaggerClientTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -504,11 +429,14 @@ }; 6D4EFBB31C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -547,6 +475,13 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCSwiftPackageProductDependency section */ + A5782C6A2664F87200CAA106 /* PetstoreClient */ = { + isa = XCSwiftPackageProductDependency; + productName = PetstoreClient; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 6D4EFB891C692C6300B96B06 /* Project object */; } diff --git a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata index 9b3fa18954f7..00ec9b53a7f1 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata +++ b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata @@ -2,9 +2,9 @@ + location = "group:.."> + location = "group:SwaggerClient.xcodeproj"> diff --git a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 000000000000..63ce26f05eba --- /dev/null +++ b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,25 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + }, + { + "package": "PromiseKit", + "repositoryURL": "https://github.com/mxcl/PromiseKit.git", + "state": { + "branch": null, + "revision": "d2f7ba14bcdc45e18f4f60ad9df883fb9055f081", + "version": "6.15.3" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md index f2b3e2abe1e1..a79f3ecc8af6 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md @@ -358,7 +358,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) diff --git a/samples/client/petstore/swift5/promisekitLibrary/project.yml b/samples/client/petstore/swift5/promisekitLibrary/project.yml index d6d2be8a2247..20bb0a7f6e94 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/project.yml +++ b/samples/client/petstore/swift5/promisekitLibrary/project.yml @@ -12,4 +12,5 @@ targets: APPLICATION_EXTENSION_API_ONLY: true scheme: {} dependencies: + - carthage: AnyCodable - carthage: PromiseKit diff --git a/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/VERSION b/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/readonlyProperties/Cartfile b/samples/client/petstore/swift5/readonlyProperties/Cartfile index 8b137891791f..843f7adc7794 100644 --- a/samples/client/petstore/swift5/readonlyProperties/Cartfile +++ b/samples/client/petstore/swift5/readonlyProperties/Cartfile @@ -1 +1,2 @@ +github "Flight-School/AnyCodable" ~> 0.6.0 diff --git a/samples/client/petstore/swift5/readonlyProperties/Package.swift b/samples/client/petstore/swift5/readonlyProperties/Package.swift index b7fe4734aa8a..5cde507bdcf9 100644 --- a/samples/client/petstore/swift5/readonlyProperties/Package.swift +++ b/samples/client/petstore/swift5/readonlyProperties/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.0 +// swift-tools-version:5.1 import PackageDescription @@ -19,13 +19,14 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.6.0")), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "PetstoreClient", - dependencies: [], + dependencies: ["AnyCodable", ], path: "PetstoreClient/Classes" ), ] diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient.podspec b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient.podspec index b61285f6b25e..60f05891b241 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient.podspec @@ -11,4 +11,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.0' end diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs.swift index dbdab491ff7d..01bc6ff0d8d0 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,7 +6,10 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 24b0015a270d..542fb6f69ba8 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -15,7 +15,7 @@ open class AnotherFakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -35,10 +35,10 @@ open class AnotherFakeAPI { */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -46,9 +46,9 @@ open class AnotherFakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 58c4b8a093ce..9b75edc92ee6 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -14,7 +14,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -33,10 +33,10 @@ open class FakeAPI { */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -44,9 +44,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -55,7 +55,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -74,10 +74,10 @@ open class FakeAPI { */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -85,9 +85,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -96,7 +96,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -115,10 +115,10 @@ open class FakeAPI { */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -126,9 +126,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -137,7 +137,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -156,10 +156,10 @@ open class FakeAPI { */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -167,9 +167,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -178,7 +178,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -197,10 +197,10 @@ open class FakeAPI { */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -208,9 +208,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -220,7 +220,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -239,11 +239,11 @@ open class FakeAPI { */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) @@ -253,9 +253,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -265,7 +265,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -285,10 +285,10 @@ open class FakeAPI { */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -296,9 +296,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -321,7 +321,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -357,7 +357,7 @@ open class FakeAPI { */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), @@ -378,7 +378,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -386,9 +386,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -472,7 +472,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -499,7 +499,7 @@ open class FakeAPI { */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), @@ -508,8 +508,8 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), @@ -524,9 +524,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -541,7 +541,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -566,11 +566,11 @@ open class FakeAPI { */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), @@ -584,9 +584,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -596,7 +596,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -615,10 +615,10 @@ open class FakeAPI { */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -626,9 +626,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -639,7 +639,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -659,7 +659,7 @@ open class FakeAPI { */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), @@ -668,7 +668,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -676,9 +676,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index fb3bb8ce00a7..fd7d845d3406 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -15,7 +15,7 @@ open class FakeClassnameTags123API { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -38,10 +38,10 @@ open class FakeClassnameTags123API { */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ open class FakeClassnameTags123API { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 5cd3629127bf..d7d5bdfa2eaa 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -15,7 +15,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -37,10 +37,10 @@ open class PetAPI { */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -48,9 +48,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -61,7 +61,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -87,10 +87,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), @@ -98,9 +98,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -119,7 +119,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -142,11 +142,11 @@ open class PetAPI { */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) @@ -156,9 +156,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -169,7 +169,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -193,11 +193,11 @@ open class PetAPI { @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) @@ -207,9 +207,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -219,7 +219,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -245,10 +245,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -256,9 +256,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -268,7 +268,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -290,10 +290,10 @@ open class PetAPI { */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -301,9 +301,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -315,7 +315,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -342,7 +342,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), @@ -351,7 +351,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -359,9 +359,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -373,7 +373,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -400,7 +400,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), @@ -409,7 +409,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -417,9 +417,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -431,7 +431,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -458,7 +458,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), @@ -467,7 +467,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -475,9 +475,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 95adcc200ae0..c80d4286b536 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -15,7 +15,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -38,10 +38,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -60,7 +60,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -82,10 +82,10 @@ open class StoreAPI { */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -93,9 +93,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -105,7 +105,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -128,10 +128,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -139,9 +139,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -151,7 +151,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -170,10 +170,10 @@ open class StoreAPI { */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -181,9 +181,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index cfd30068a9db..542dc212bd1b 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -15,7 +15,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -35,10 +35,10 @@ open class UserAPI { */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { let path = "/user" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -46,9 +46,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -58,7 +58,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -77,10 +77,10 @@ open class UserAPI { */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -88,9 +88,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -100,7 +100,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -119,10 +119,10 @@ open class UserAPI { */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -130,9 +130,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -142,7 +142,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -165,10 +165,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -176,9 +176,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -188,7 +188,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -210,10 +210,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -221,9 +221,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -234,7 +234,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -255,11 +255,11 @@ open class UserAPI { */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) @@ -270,9 +270,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -281,7 +281,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -299,10 +299,10 @@ open class UserAPI { */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -310,9 +310,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -323,7 +323,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -347,10 +347,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -358,9 +358,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 93ed6b90b376..e23035dde30e 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,6 +5,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -52,6 +55,12 @@ extension Array: JSONEncodable { } } +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + extension Dictionary: JSONEncodable { func encodeToJSON() -> Any { var dictionary = [AnyHashable: Any]() diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 4c5e1a53bd4b..55e1a850f068 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct AdditionalPropertiesClass: Codable, Hashable { @@ -22,4 +25,11 @@ public struct AdditionalPropertiesClass: Codable, Hashable { case mapMapString = "map_map_string" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapString, forKey: .mapString) + try container.encodeIfPresent(mapMapString, forKey: .mapMapString) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 48229f750cdc..3fded4244c37 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Animal: Codable, Hashable { @@ -17,4 +20,16 @@ public struct Animal: Codable, Hashable { self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index e09b0e9efdc8..a0b09cb97615 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,5 +6,8 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 93b598e8d6f7..1522485099ca 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ApiResponse: Codable, Hashable { @@ -19,4 +22,18 @@ public struct ApiResponse: Codable, Hashable { self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { + case code + case type + case message + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(code, forKey: .code) + try container.encodeIfPresent(type, forKey: .type) + try container.encodeIfPresent(message, forKey: .message) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 6225dd84be7a..d754b57dd072 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { case arrayArrayNumber = "ArrayArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index 698c3adf98cb..261f521a2e3d 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayOfNumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct ArrayOfNumberOnly: Codable, Hashable { case arrayNumber = "ArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index 578d06178524..e68cd879f6c7 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayTest: Codable, Hashable { @@ -25,4 +28,12 @@ public struct ArrayTest: Codable, Hashable { case arrayArrayOfModel = "array_array_of_model" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayOfString, forKey: .arrayOfString) + try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) + try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index 6b4d8425c4af..d449c5890d1b 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Capitalization: Codable, Hashable { @@ -35,4 +38,15 @@ public struct Capitalization: Codable, Hashable { case ATT_NAME } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(smallCamel, forKey: .smallCamel) + try container.encodeIfPresent(capitalCamel, forKey: .capitalCamel) + try container.encodeIfPresent(smallSnake, forKey: .smallSnake) + try container.encodeIfPresent(capitalSnake, forKey: .capitalSnake) + try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) + try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 731f11bf6f16..3ddf9bee2fd5 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Cat: Codable, Hashable { @@ -19,4 +22,18 @@ public struct Cat: Codable, Hashable { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index 34cf645193dd..40685ac1a16d 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct CatAllOf: Codable, Hashable { @@ -15,4 +18,14 @@ public struct CatAllOf: Codable, Hashable { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 4089925077ff..da9e51d2a512 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,15 +6,30 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Category: Codable, Hashable { public private(set) var id: Int64? - public private(set) var name: String = "default-name" + public private(set) var name: String? = "default-name" - public init(id: Int64? = nil, name: String = "default-name") { + public init(id: Int64? = nil, name: String? = "default-name") { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encode(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index a76f014c0364..c6984e27050c 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model with \"_class\" property */ public struct ClassModel: Codable, Hashable { @@ -16,4 +19,14 @@ public struct ClassModel: Codable, Hashable { self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { + case _class + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_class, forKey: ._class) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index f1dd2364bfc2..a08ef9f5ba42 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Client: Codable, Hashable { @@ -15,4 +18,14 @@ public struct Client: Codable, Hashable { self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { + case client + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(client, forKey: .client) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index ef91e2a47a5b..efe8988d3811 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Dog: Codable, Hashable { @@ -19,4 +22,18 @@ public struct Dog: Codable, Hashable { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 0eab83890406..1d1f8ca7db91 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct DogAllOf: Codable, Hashable { @@ -15,4 +18,14 @@ public struct DogAllOf: Codable, Hashable { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index e3befc6dfe57..d8e15faf3a39 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct EnumArrays: Codable, Hashable { @@ -30,4 +33,11 @@ public struct EnumArrays: Codable, Hashable { case arrayEnum = "array_enum" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justSymbol, forKey: .justSymbol) + try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index d4029d73f8af..6ea2895aee53 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index d9dd6a64b064..ca412e06fe1b 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct EnumTest: Codable, Hashable { @@ -49,4 +52,14 @@ public struct EnumTest: Codable, Hashable { case outerEnum } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(enumString, forKey: .enumString) + try container.encode(enumStringRequired, forKey: .enumStringRequired) + try container.encodeIfPresent(enumInteger, forKey: .enumInteger) + try container.encodeIfPresent(enumNumber, forKey: .enumNumber) + try container.encodeIfPresent(outerEnum, forKey: .outerEnum) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/File.swift index 1fbc65d2db54..1c9a0f33ee83 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Must be named `File` for test. */ public struct File: Codable, Hashable { @@ -17,4 +20,14 @@ public struct File: Codable, Hashable { self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { + case sourceURI + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(sourceURI, forKey: .sourceURI) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index aa4cf089d0f7..50304fe594a3 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FileSchemaTestClass: Codable, Hashable { @@ -17,4 +20,16 @@ public struct FileSchemaTestClass: Codable, Hashable { self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { + case file + case files + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(file, forKey: .file) + try container.encodeIfPresent(files, forKey: .files) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index fce99baa8f02..bf2d4131948e 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FormatTest: Codable, Hashable { @@ -39,4 +42,38 @@ public struct FormatTest: Codable, Hashable { self.password = password } + public enum CodingKeys: String, CodingKey, CaseIterable { + case integer + case int32 + case int64 + case number + case float + case double + case string + case byte + case binary + case date + case dateTime + case uuid + case password + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(integer, forKey: .integer) + try container.encodeIfPresent(int32, forKey: .int32) + try container.encodeIfPresent(int64, forKey: .int64) + try container.encode(number, forKey: .number) + try container.encodeIfPresent(float, forKey: .float) + try container.encodeIfPresent(double, forKey: .double) + try container.encodeIfPresent(string, forKey: .string) + try container.encode(byte, forKey: .byte) + try container.encodeIfPresent(binary, forKey: .binary) + try container.encode(date, forKey: .date) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encode(password, forKey: .password) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index 0b2b2f5887e4..ee6bd8280bdb 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct HasOnlyReadOnly: Codable, Hashable { @@ -17,4 +20,16 @@ public struct HasOnlyReadOnly: Codable, Hashable { self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case foo + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(foo, forKey: .foo) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/List.swift index 0247967c505f..41a0eacd2ac5 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct List: Codable, Hashable { @@ -19,4 +22,10 @@ public struct List: Codable, Hashable { case _123list = "123-list" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_123list, forKey: ._123list) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index 15bdb8c852f1..27e27b36d0fa 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct MapTest: Codable, Hashable { @@ -32,4 +35,13 @@ public struct MapTest: Codable, Hashable { case indirectMap = "indirect_map" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapMapOfString, forKey: .mapMapOfString) + try container.encodeIfPresent(mapOfEnumString, forKey: .mapOfEnumString) + try container.encodeIfPresent(directMap, forKey: .directMap) + try container.encodeIfPresent(indirectMap, forKey: .indirectMap) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index 1253cecf1b8c..306c8adeaa36 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { @@ -19,4 +22,18 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { + case uuid + case dateTime + case map + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(map, forKey: .map) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 1c8c0b4b11f1..233fa7656abf 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name starting with number */ public struct Model200Response: Codable, Hashable { @@ -23,4 +26,11 @@ public struct Model200Response: Codable, Hashable { case _class = "class" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(_class, forKey: ._class) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 59fc35b4999f..c1fda99c0c7e 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name same as property name */ public struct Name: Codable, Hashable { @@ -29,4 +32,13 @@ public struct Name: Codable, Hashable { case _123number = "123Number" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encodeIfPresent(snakeCase, forKey: .snakeCase) + try container.encodeIfPresent(property, forKey: .property) + try container.encodeIfPresent(_123number, forKey: ._123number) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 71634b248270..5526fc2fbf25 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct NumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct NumberOnly: Codable, Hashable { case justNumber = "JustNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justNumber, forKey: .justNumber) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 25ac0c3fabb1..c79bc3f02d3d 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Order: Codable, Hashable { @@ -31,4 +34,24 @@ public struct Order: Codable, Hashable { self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case petId + case quantity + case shipDate + case status + case complete + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(petId, forKey: .petId) + try container.encodeIfPresent(quantity, forKey: .quantity) + try container.encodeIfPresent(shipDate, forKey: .shipDate) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(complete, forKey: .complete) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 36a489ac41a3..c69f16e2a883 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct OuterComposite: Codable, Hashable { @@ -25,4 +28,12 @@ public struct OuterComposite: Codable, Hashable { case myBoolean = "my_boolean" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(myNumber, forKey: .myNumber) + try container.encodeIfPresent(myString, forKey: .myString) + try container.encodeIfPresent(myBoolean, forKey: .myBoolean) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index c3b778cbbed4..76c34b3c2ce6 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 561d18526968..46f5919b6b74 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Pet: Codable, Hashable { @@ -31,4 +34,24 @@ public struct Pet: Codable, Hashable { self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case category + case name + case photoUrls + case tags + case status + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(category, forKey: .category) + try container.encode(name, forKey: .name) + try container.encode(photoUrls, forKey: .photoUrls) + try container.encodeIfPresent(tags, forKey: .tags) + try container.encodeIfPresent(status, forKey: .status) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index ae8af88b8a29..249d7691c215 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ReadOnlyFirst: Codable, Hashable { @@ -17,4 +20,16 @@ public struct ReadOnlyFirst: Codable, Hashable { self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case baz + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(baz, forKey: .baz) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 1bb551dcaef8..23e8e52f6e5f 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing reserved words */ public struct Return: Codable, Hashable { @@ -20,4 +23,10 @@ public struct Return: Codable, Hashable { case _return = "return" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_return, forKey: ._return) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index 78dc5a7db12e..8a12be510ab8 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct SpecialModelName: Codable, Hashable { @@ -19,4 +22,10 @@ public struct SpecialModelName: Codable, Hashable { case specialPropertyName = "$special[property.name]" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 0a6fc2976ee4..19103698f9a5 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,9 +6,16 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct StringBooleanMap: Codable, Hashable { + + public enum CodingKeys: CodingKey, CaseIterable { + } + public private(set) var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -27,19 +34,18 @@ public struct StringBooleanMap: Codable, Hashable { // Encodable protocol methods public func encode(to encoder: Encoder) throws { - - var container = encoder.container(keyedBy: String.self) - - try container.encodeMap(additionalProperties) + var container = encoder.container(keyedBy: CodingKeys.self) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) } // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index c35e07111a00..e3d44bf635f9 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Tag: Codable, Hashable { @@ -17,4 +20,16 @@ public struct Tag: Codable, Hashable { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index 0ad0e39ab4d8..575466ee7d57 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct TypeHolderDefault: Codable, Hashable { @@ -31,4 +34,14 @@ public struct TypeHolderDefault: Codable, Hashable { case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index a26b555da79e..ba22b15d8487 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct TypeHolderExample: Codable, Hashable { @@ -31,4 +34,14 @@ public struct TypeHolderExample: Codable, Hashable { case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/User.swift index 4c33cf58d3b6..33cb2a060441 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct User: Codable, Hashable { @@ -30,4 +33,28 @@ public struct User: Codable, Hashable { self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case username + case firstName + case lastName + case email + case password + case phone + case userStatus + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(username, forKey: .username) + try container.encodeIfPresent(firstName, forKey: .firstName) + try container.encodeIfPresent(lastName, forKey: .lastName) + try container.encodeIfPresent(email, forKey: .email) + try container.encodeIfPresent(password, forKey: .password) + try container.encodeIfPresent(phone, forKey: .phone) + try container.encodeIfPresent(userStatus, forKey: .userStatus) + } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 52b2071ec1aa..774c0427eaa2 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,7 +93,7 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md b/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md index 543869c0d2e0..553a46281aa0 100644 --- a/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md @@ -379,7 +379,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) diff --git a/samples/client/petstore/swift5/readonlyProperties/project.yml b/samples/client/petstore/swift5/readonlyProperties/project.yml index 8e7102001b8d..0493cf65896e 100644 --- a/samples/client/petstore/swift5/readonlyProperties/project.yml +++ b/samples/client/petstore/swift5/readonlyProperties/project.yml @@ -11,4 +11,5 @@ targets: settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - + dependencies: + - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/resultLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/resultLibrary/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/swift5/resultLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/resultLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/resultLibrary/Cartfile b/samples/client/petstore/swift5/resultLibrary/Cartfile index 8b137891791f..843f7adc7794 100644 --- a/samples/client/petstore/swift5/resultLibrary/Cartfile +++ b/samples/client/petstore/swift5/resultLibrary/Cartfile @@ -1 +1,2 @@ +github "Flight-School/AnyCodable" ~> 0.6.0 diff --git a/samples/client/petstore/swift5/resultLibrary/Package.resolved b/samples/client/petstore/swift5/resultLibrary/Package.resolved new file mode 100644 index 000000000000..d384b276b4bc --- /dev/null +++ b/samples/client/petstore/swift5/resultLibrary/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/resultLibrary/Package.swift b/samples/client/petstore/swift5/resultLibrary/Package.swift index b7fe4734aa8a..5cde507bdcf9 100644 --- a/samples/client/petstore/swift5/resultLibrary/Package.swift +++ b/samples/client/petstore/swift5/resultLibrary/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.0 +// swift-tools-version:5.1 import PackageDescription @@ -19,13 +19,14 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.6.0")), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "PetstoreClient", - dependencies: [], + dependencies: ["AnyCodable", ], path: "PetstoreClient/Classes" ), ] diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient.podspec b/samples/client/petstore/swift5/resultLibrary/PetstoreClient.podspec index b61285f6b25e..60f05891b241 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient.podspec @@ -11,4 +11,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.0' end diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index dbdab491ff7d..01bc6ff0d8d0 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,7 +6,10 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 1c777abff633..f2f733281fc6 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -15,7 +15,7 @@ open class AnotherFakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -35,10 +35,10 @@ open class AnotherFakeAPI { */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -46,9 +46,9 @@ open class AnotherFakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 642370b2bc1c..180df7841ae7 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -14,7 +14,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -33,10 +33,10 @@ open class FakeAPI { */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -44,9 +44,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -55,7 +55,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -74,10 +74,10 @@ open class FakeAPI { */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -85,9 +85,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -96,7 +96,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -115,10 +115,10 @@ open class FakeAPI { */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -126,9 +126,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -137,7 +137,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -156,10 +156,10 @@ open class FakeAPI { */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -167,9 +167,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -178,7 +178,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -197,10 +197,10 @@ open class FakeAPI { */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -208,9 +208,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -220,7 +220,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -239,11 +239,11 @@ open class FakeAPI { */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) @@ -253,9 +253,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -265,7 +265,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -285,10 +285,10 @@ open class FakeAPI { */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -296,9 +296,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -321,7 +321,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -357,7 +357,7 @@ open class FakeAPI { */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), @@ -378,7 +378,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -386,9 +386,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -472,7 +472,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -499,7 +499,7 @@ open class FakeAPI { */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), @@ -508,8 +508,8 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), @@ -524,9 +524,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -541,7 +541,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -566,11 +566,11 @@ open class FakeAPI { */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), @@ -584,9 +584,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -596,7 +596,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -615,10 +615,10 @@ open class FakeAPI { */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -626,9 +626,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -639,7 +639,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -659,7 +659,7 @@ open class FakeAPI { */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), @@ -668,7 +668,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -676,9 +676,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 4cf17d8a8849..161b2c3f7585 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -15,7 +15,7 @@ open class FakeClassnameTags123API { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -38,10 +38,10 @@ open class FakeClassnameTags123API { */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ open class FakeClassnameTags123API { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index fd4c8fb152ad..23e7fc21b701 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -15,7 +15,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -37,10 +37,10 @@ open class PetAPI { */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -48,9 +48,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -61,7 +61,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -87,10 +87,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), @@ -98,9 +98,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -119,7 +119,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[Pet], Error>) -> Void)) { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[Pet], Error>) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -142,11 +142,11 @@ open class PetAPI { */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) @@ -156,9 +156,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -169,7 +169,7 @@ open class PetAPI { - parameter completion: completion handler to receive the result */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[Pet], Error>) -> Void)) { + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[Pet], Error>) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -193,11 +193,11 @@ open class PetAPI { @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) @@ -207,9 +207,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -219,7 +219,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -245,10 +245,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -256,9 +256,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -268,7 +268,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -290,10 +290,10 @@ open class PetAPI { */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -301,9 +301,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -315,7 +315,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -342,7 +342,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), @@ -351,7 +351,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -359,9 +359,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -373,7 +373,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -400,7 +400,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), @@ -409,7 +409,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -417,9 +417,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -431,7 +431,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -458,7 +458,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), @@ -467,7 +467,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -475,9 +475,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index a50d54cada1e..ccdb44bf803e 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -15,7 +15,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -38,10 +38,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -60,7 +60,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[String: Int], Error>) -> Void)) { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[String: Int], Error>) -> Void)) { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -82,10 +82,10 @@ open class StoreAPI { */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -93,9 +93,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -105,7 +105,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -128,10 +128,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -139,9 +139,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -151,7 +151,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -170,10 +170,10 @@ open class StoreAPI { */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -181,9 +181,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 58b6b51d8b06..ea100babfcad 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -15,7 +15,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -35,10 +35,10 @@ open class UserAPI { */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { let path = "/user" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -46,9 +46,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -58,7 +58,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -77,10 +77,10 @@ open class UserAPI { */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -88,9 +88,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -100,7 +100,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -119,10 +119,10 @@ open class UserAPI { */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -130,9 +130,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -142,7 +142,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -165,10 +165,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -176,9 +176,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -188,7 +188,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -210,10 +210,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -221,9 +221,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -234,7 +234,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -255,11 +255,11 @@ open class UserAPI { */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) @@ -270,9 +270,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -281,7 +281,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -299,10 +299,10 @@ open class UserAPI { */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -310,9 +310,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -323,7 +323,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -347,10 +347,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -358,9 +358,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 93ed6b90b376..e23035dde30e 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,6 +5,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -52,6 +55,12 @@ extension Array: JSONEncodable { } } +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + extension Dictionary: JSONEncodable { func encodeToJSON() -> Any { var dictionary = [AnyHashable: Any]() diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 733b7bc51594..61a478de142b 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct AdditionalPropertiesClass: Codable, Hashable { @@ -22,4 +25,11 @@ public struct AdditionalPropertiesClass: Codable, Hashable { case mapMapString = "map_map_string" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapString, forKey: .mapString) + try container.encodeIfPresent(mapMapString, forKey: .mapMapString) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index e57c8b471765..157cca1d227b 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Animal: Codable, Hashable { @@ -17,4 +20,16 @@ public struct Animal: Codable, Hashable { self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index e09b0e9efdc8..a0b09cb97615 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,5 +6,8 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 630992f6231e..8607cbef1a33 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ApiResponse: Codable, Hashable { @@ -19,4 +22,18 @@ public struct ApiResponse: Codable, Hashable { self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { + case code + case type + case message + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(code, forKey: .code) + try container.encodeIfPresent(type, forKey: .type) + try container.encodeIfPresent(message, forKey: .message) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 4710793fc9a6..f3f161b44c1c 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { case arrayArrayNumber = "ArrayArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index a41968d9b199..d62de957472a 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayOfNumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct ArrayOfNumberOnly: Codable, Hashable { case arrayNumber = "ArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index f442ea725451..360d50d027f1 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayTest: Codable, Hashable { @@ -25,4 +28,12 @@ public struct ArrayTest: Codable, Hashable { case arrayArrayOfModel = "array_array_of_model" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayOfString, forKey: .arrayOfString) + try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) + try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index 44b50bbe0063..f0781a9cb738 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Capitalization: Codable, Hashable { @@ -35,4 +38,15 @@ public struct Capitalization: Codable, Hashable { case ATT_NAME } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(smallCamel, forKey: .smallCamel) + try container.encodeIfPresent(capitalCamel, forKey: .capitalCamel) + try container.encodeIfPresent(smallSnake, forKey: .smallSnake) + try container.encodeIfPresent(capitalSnake, forKey: .capitalSnake) + try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) + try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index c6bf4460da6e..d5519760387a 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Cat: Codable, Hashable { @@ -19,4 +22,18 @@ public struct Cat: Codable, Hashable { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index f9484f9bc8fd..8312680deb37 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct CatAllOf: Codable, Hashable { @@ -15,4 +18,14 @@ public struct CatAllOf: Codable, Hashable { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 6a19bb02d0df..398da60aa73b 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,15 +6,30 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Category: Codable, Hashable { public var id: Int64? - public var name: String = "default-name" + public var name: String? = "default-name" - public init(id: Int64? = nil, name: String = "default-name") { + public init(id: Int64? = nil, name: String? = "default-name") { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encode(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index 5c8e8882831f..03bf63e4cad1 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model with \"_class\" property */ public struct ClassModel: Codable, Hashable { @@ -16,4 +19,14 @@ public struct ClassModel: Codable, Hashable { self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { + case _class + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_class, forKey: ._class) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 1464b047c06a..596048780439 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Client: Codable, Hashable { @@ -15,4 +18,14 @@ public struct Client: Codable, Hashable { self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { + case client + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(client, forKey: .client) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index 5aed7834d537..4ada3ceb605a 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Dog: Codable, Hashable { @@ -19,4 +22,18 @@ public struct Dog: Codable, Hashable { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 716776261d30..f6c3d287301d 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct DogAllOf: Codable, Hashable { @@ -15,4 +18,14 @@ public struct DogAllOf: Codable, Hashable { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index aa13aa59f86a..0e0aad42abe6 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct EnumArrays: Codable, Hashable { @@ -30,4 +33,11 @@ public struct EnumArrays: Codable, Hashable { case arrayEnum = "array_enum" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justSymbol, forKey: .justSymbol) + try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index d4029d73f8af..6ea2895aee53 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 8b62febdc959..9e44926be9b8 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct EnumTest: Codable, Hashable { @@ -49,4 +52,14 @@ public struct EnumTest: Codable, Hashable { case outerEnum } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(enumString, forKey: .enumString) + try container.encode(enumStringRequired, forKey: .enumStringRequired) + try container.encodeIfPresent(enumInteger, forKey: .enumInteger) + try container.encodeIfPresent(enumNumber, forKey: .enumNumber) + try container.encodeIfPresent(outerEnum, forKey: .outerEnum) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift index aa14d762394d..11694b2ca59b 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Must be named `File` for test. */ public struct File: Codable, Hashable { @@ -17,4 +20,14 @@ public struct File: Codable, Hashable { self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { + case sourceURI + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(sourceURI, forKey: .sourceURI) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index 85987709776e..6aa85d8eecf9 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FileSchemaTestClass: Codable, Hashable { @@ -17,4 +20,16 @@ public struct FileSchemaTestClass: Codable, Hashable { self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { + case file + case files + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(file, forKey: .file) + try container.encodeIfPresent(files, forKey: .files) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index f09cb471b360..114c884efc5e 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FormatTest: Codable, Hashable { @@ -39,4 +42,38 @@ public struct FormatTest: Codable, Hashable { self.password = password } + public enum CodingKeys: String, CodingKey, CaseIterable { + case integer + case int32 + case int64 + case number + case float + case double + case string + case byte + case binary + case date + case dateTime + case uuid + case password + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(integer, forKey: .integer) + try container.encodeIfPresent(int32, forKey: .int32) + try container.encodeIfPresent(int64, forKey: .int64) + try container.encode(number, forKey: .number) + try container.encodeIfPresent(float, forKey: .float) + try container.encodeIfPresent(double, forKey: .double) + try container.encodeIfPresent(string, forKey: .string) + try container.encode(byte, forKey: .byte) + try container.encodeIfPresent(binary, forKey: .binary) + try container.encode(date, forKey: .date) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encode(password, forKey: .password) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index 03d35274a4ee..cb1a7456a7df 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct HasOnlyReadOnly: Codable, Hashable { @@ -17,4 +20,16 @@ public struct HasOnlyReadOnly: Codable, Hashable { self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case foo + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(foo, forKey: .foo) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift index f8f08e4c6c44..8ecdd3b02339 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct List: Codable, Hashable { @@ -19,4 +22,10 @@ public struct List: Codable, Hashable { case _123list = "123-list" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_123list, forKey: ._123list) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index bd4e7b97e81b..0ff74ed8400e 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct MapTest: Codable, Hashable { @@ -32,4 +35,13 @@ public struct MapTest: Codable, Hashable { case indirectMap = "indirect_map" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapMapOfString, forKey: .mapMapOfString) + try container.encodeIfPresent(mapOfEnumString, forKey: .mapOfEnumString) + try container.encodeIfPresent(directMap, forKey: .directMap) + try container.encodeIfPresent(indirectMap, forKey: .indirectMap) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index 80c1781a2bfc..58a0a54ca090 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { @@ -19,4 +22,18 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { + case uuid + case dateTime + case map + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(map, forKey: .map) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index d36d4e27352a..0f59769954f1 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name starting with number */ public struct Model200Response: Codable, Hashable { @@ -23,4 +26,11 @@ public struct Model200Response: Codable, Hashable { case _class = "class" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(_class, forKey: ._class) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 49cc57544179..d88c94f05c95 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name same as property name */ public struct Name: Codable, Hashable { @@ -29,4 +32,13 @@ public struct Name: Codable, Hashable { case _123number = "123Number" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encodeIfPresent(snakeCase, forKey: .snakeCase) + try container.encodeIfPresent(property, forKey: .property) + try container.encodeIfPresent(_123number, forKey: ._123number) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 6b024294e288..0f05482b9b7c 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct NumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct NumberOnly: Codable, Hashable { case justNumber = "JustNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justNumber, forKey: .justNumber) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 8ef7cb79e2c8..100d6b71fed4 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Order: Codable, Hashable { @@ -31,4 +34,24 @@ public struct Order: Codable, Hashable { self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case petId + case quantity + case shipDate + case status + case complete + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(petId, forKey: .petId) + try container.encodeIfPresent(quantity, forKey: .quantity) + try container.encodeIfPresent(shipDate, forKey: .shipDate) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(complete, forKey: .complete) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 9865764ff9bb..15a4e4a15b6e 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct OuterComposite: Codable, Hashable { @@ -25,4 +28,12 @@ public struct OuterComposite: Codable, Hashable { case myBoolean = "my_boolean" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(myNumber, forKey: .myNumber) + try container.encodeIfPresent(myString, forKey: .myString) + try container.encodeIfPresent(myBoolean, forKey: .myBoolean) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index c3b778cbbed4..76c34b3c2ce6 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 1bc823d3e960..a87ab825ea0b 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Pet: Codable, Hashable { @@ -31,4 +34,24 @@ public struct Pet: Codable, Hashable { self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case category + case name + case photoUrls + case tags + case status + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(category, forKey: .category) + try container.encode(name, forKey: .name) + try container.encode(photoUrls, forKey: .photoUrls) + try container.encodeIfPresent(tags, forKey: .tags) + try container.encodeIfPresent(status, forKey: .status) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 03b5b0dbf02b..6426deedf637 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ReadOnlyFirst: Codable, Hashable { @@ -17,4 +20,16 @@ public struct ReadOnlyFirst: Codable, Hashable { self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case baz + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(baz, forKey: .baz) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 5f539f461843..777c241bc0c0 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing reserved words */ public struct Return: Codable, Hashable { @@ -20,4 +23,10 @@ public struct Return: Codable, Hashable { case _return = "return" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_return, forKey: ._return) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index cb82d2ae3adc..b677523a7491 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct SpecialModelName: Codable, Hashable { @@ -19,4 +22,10 @@ public struct SpecialModelName: Codable, Hashable { case specialPropertyName = "$special[property.name]" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 77ab81f5f341..f575c9df65ca 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,9 +6,16 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct StringBooleanMap: Codable, Hashable { + + public enum CodingKeys: CodingKey, CaseIterable { + } + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -27,19 +34,18 @@ public struct StringBooleanMap: Codable, Hashable { // Encodable protocol methods public func encode(to encoder: Encoder) throws { - - var container = encoder.container(keyedBy: String.self) - - try container.encodeMap(additionalProperties) + var container = encoder.container(keyedBy: CodingKeys.self) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) } // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 8b8e24fc39c0..cd5acc827db7 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Tag: Codable, Hashable { @@ -17,4 +20,16 @@ public struct Tag: Codable, Hashable { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index f1920ef37788..341c9b4b8c2e 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct TypeHolderDefault: Codable, Hashable { @@ -31,4 +34,14 @@ public struct TypeHolderDefault: Codable, Hashable { case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index 1a23c1b486b8..04166af0895f 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct TypeHolderExample: Codable, Hashable { @@ -31,4 +34,14 @@ public struct TypeHolderExample: Codable, Hashable { case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift index f3b4f6bb958a..9f3ded8fcd93 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct User: Codable, Hashable { @@ -30,4 +33,28 @@ public struct User: Codable, Hashable { self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case username + case firstName + case lastName + case email + case password + case phone + case userStatus + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(username, forKey: .username) + try container.encodeIfPresent(firstName, forKey: .firstName) + try container.encodeIfPresent(lastName, forKey: .lastName) + try container.encodeIfPresent(email, forKey: .email) + try container.encodeIfPresent(password, forKey: .password) + try container.encodeIfPresent(phone, forKey: .phone) + try container.encodeIfPresent(userStatus, forKey: .userStatus) + } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 52b2071ec1aa..774c0427eaa2 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,7 +93,7 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md index 543869c0d2e0..553a46281aa0 100644 --- a/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md @@ -379,7 +379,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) diff --git a/samples/client/petstore/swift5/resultLibrary/project.yml b/samples/client/petstore/swift5/resultLibrary/project.yml index 8e7102001b8d..0493cf65896e 100644 --- a/samples/client/petstore/swift5/resultLibrary/project.yml +++ b/samples/client/petstore/swift5/resultLibrary/project.yml @@ -11,4 +11,5 @@ targets: settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - + dependencies: + - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/rxswiftLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/rxswiftLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000000..919434a6254f --- /dev/null +++ b/samples/client/petstore/swift5/rxswiftLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/Cartfile b/samples/client/petstore/swift5/rxswiftLibrary/Cartfile index 37dea8f2ead7..a49f6c9da038 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/Cartfile +++ b/samples/client/petstore/swift5/rxswiftLibrary/Cartfile @@ -1,2 +1,3 @@ -github "ReactiveX/RxSwift" ~> 5.1.1 +github "ReactiveX/RxSwift" ~> 6.2.0 +github "Flight-School/AnyCodable" ~> 0.6.0 diff --git a/samples/client/petstore/swift5/rxswiftLibrary/Package.resolved b/samples/client/petstore/swift5/rxswiftLibrary/Package.resolved index e3afef806b8d..231d85369677 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/Package.resolved +++ b/samples/client/petstore/swift5/rxswiftLibrary/Package.resolved @@ -1,13 +1,22 @@ { "object": { "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + }, { "package": "RxSwift", "repositoryURL": "https://github.com/ReactiveX/RxSwift.git", "state": { "branch": null, - "revision": "b3e888b4972d9bc76495dd74d30a8c7fad4b9395", - "version": "5.0.1" + "revision": "7c17a6ccca06b5c107cfa4284e634562ddaf5951", + "version": "6.2.0" } } ] diff --git a/samples/client/petstore/swift5/rxswiftLibrary/Package.swift b/samples/client/petstore/swift5/rxswiftLibrary/Package.swift index e774d3e15c77..36541008daaa 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/Package.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.0 +// swift-tools-version:5.1 import PackageDescription @@ -19,14 +19,15 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/ReactiveX/RxSwift.git", from: "5.0.0"), + .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.6.0")), + .package(url: "https://github.com/ReactiveX/RxSwift.git", from: "6.2.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "PetstoreClient", - dependencies: ["RxSwift"], + dependencies: ["AnyCodable", "RxSwift"], path: "PetstoreClient/Classes" ), ] diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient.podspec b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient.podspec index 2e94d8a71f3e..32a1ff8ae6f4 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient.podspec @@ -11,5 +11,6 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' - s.dependency 'RxSwift', '~> 5.1.1' + s.dependency 'RxSwift', '~> 6.2.0' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.0' end diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index dbdab491ff7d..01bc6ff0d8d0 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,7 +6,10 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 1affe07267f1..d46906177c87 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -16,7 +16,7 @@ open class AnotherFakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -40,10 +40,10 @@ open class AnotherFakeAPI { */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -51,9 +51,9 @@ open class AnotherFakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index f76577526ec8..abf1a1b7f5de 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -15,7 +15,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -38,10 +38,10 @@ open class FakeAPI { */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -60,7 +60,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -83,10 +83,10 @@ open class FakeAPI { */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -94,9 +94,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -105,7 +105,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -128,10 +128,10 @@ open class FakeAPI { */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -139,9 +139,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -150,7 +150,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -173,10 +173,10 @@ open class FakeAPI { */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -184,9 +184,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -195,7 +195,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -218,10 +218,10 @@ open class FakeAPI { */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -229,9 +229,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -241,7 +241,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -264,11 +264,11 @@ open class FakeAPI { */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) @@ -278,9 +278,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -290,7 +290,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -314,10 +314,10 @@ open class FakeAPI { */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -325,9 +325,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -350,7 +350,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute(apiResponseQueue) { result -> Void in switch result { @@ -390,7 +390,7 @@ open class FakeAPI { */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), @@ -411,7 +411,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -419,9 +419,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -505,7 +505,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { @@ -536,7 +536,7 @@ open class FakeAPI { */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), @@ -545,8 +545,8 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), @@ -561,9 +561,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -578,7 +578,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { @@ -607,11 +607,11 @@ open class FakeAPI { */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), @@ -625,9 +625,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -637,7 +637,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { @@ -660,10 +660,10 @@ open class FakeAPI { */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -671,9 +671,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -684,7 +684,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { @@ -708,7 +708,7 @@ open class FakeAPI { */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), @@ -717,7 +717,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -725,9 +725,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index ec0775dbde0a..4e4de2bab774 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -16,7 +16,7 @@ open class FakeClassnameTags123API { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -43,10 +43,10 @@ open class FakeClassnameTags123API { */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -54,9 +54,9 @@ open class FakeClassnameTags123API { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index e1152e64add8..a51e91c1f0e0 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -16,7 +16,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -42,10 +42,10 @@ open class PetAPI { */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -53,9 +53,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -66,7 +66,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { @@ -96,10 +96,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), @@ -107,9 +107,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -128,7 +128,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable<[Pet]> */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<[Pet]> { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable<[Pet]> { return Observable.create { observer -> Disposable in findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { @@ -155,11 +155,11 @@ open class PetAPI { */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) @@ -169,9 +169,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -182,7 +182,7 @@ open class PetAPI { - returns: Observable<[Pet]> */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<[Pet]> { + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable<[Pet]> { return Observable.create { observer -> Disposable in findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { @@ -210,11 +210,11 @@ open class PetAPI { @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) @@ -224,9 +224,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -236,7 +236,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { @@ -266,10 +266,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -277,9 +277,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -289,7 +289,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -315,10 +315,10 @@ open class PetAPI { */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -326,9 +326,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -340,7 +340,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { @@ -371,7 +371,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), @@ -380,7 +380,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -388,9 +388,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -402,7 +402,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { @@ -433,7 +433,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), @@ -442,7 +442,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -450,9 +450,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -464,7 +464,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { @@ -495,7 +495,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), @@ -504,7 +504,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -512,9 +512,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 4dac29ad2be3..9343800cddb5 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -16,7 +16,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { @@ -43,10 +43,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -54,9 +54,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -65,7 +65,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable<[String: Int]> */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<[String: Int]> { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable<[String: Int]> { return Observable.create { observer -> Disposable in getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { @@ -91,10 +91,10 @@ open class StoreAPI { */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -102,9 +102,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -114,7 +114,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { @@ -141,10 +141,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -152,9 +152,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -164,7 +164,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -187,10 +187,10 @@ open class StoreAPI { */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -198,9 +198,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 5bfcc43e2a2e..2e9dac80ae32 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -16,7 +16,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -40,10 +40,10 @@ open class UserAPI { */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { let path = "/user" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -51,9 +51,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -63,7 +63,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -86,10 +86,10 @@ open class UserAPI { */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -97,9 +97,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -109,7 +109,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -132,10 +132,10 @@ open class UserAPI { */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -143,9 +143,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -155,7 +155,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { @@ -182,10 +182,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -193,9 +193,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -205,7 +205,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { @@ -231,10 +231,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -242,9 +242,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -255,7 +255,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { @@ -280,11 +280,11 @@ open class UserAPI { */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) @@ -295,9 +295,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -306,7 +306,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { @@ -328,10 +328,10 @@ open class UserAPI { */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -339,9 +339,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -352,7 +352,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -380,10 +380,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -391,9 +391,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 93ed6b90b376..dc0913d093f8 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,6 +5,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -52,6 +55,12 @@ extension Array: JSONEncodable { } } +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + extension Dictionary: JSONEncodable { func encodeToJSON() -> Any { var dictionary = [AnyHashable: Any]() @@ -86,92 +95,6 @@ extension UUID: JSONEncodable { } } -extension String: CodingKey { - - public var stringValue: String { - return self - } - - public init?(stringValue: String) { - self.init(stringLiteral: stringValue) - } - - public var intValue: Int? { - return nil - } - - public init?(intValue: Int) { - return nil - } - -} - -extension KeyedEncodingContainerProtocol { - - public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable { - var arrayContainer = nestedUnkeyedContainer(forKey: key) - try arrayContainer.encode(contentsOf: values) - } - - public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable { - if let values = values { - try encodeArray(values, forKey: key) - } - } - - public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable { - for (key, value) in pairs { - try encode(value, forKey: key) - } - } - - public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable { - if let pairs = pairs { - try encodeMap(pairs) - } - } - -} - -extension KeyedDecodingContainerProtocol { - - public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable { - var tmpArray = [T]() - - var nestedContainer = try nestedUnkeyedContainer(forKey: key) - while !nestedContainer.isAtEnd { - let arrayValue = try nestedContainer.decode(T.self) - tmpArray.append(arrayValue) - } - - return tmpArray - } - - public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable { - var tmpArray: [T]? - - if contains(key) { - tmpArray = try decodeArray(T.self, forKey: key) - } - - return tmpArray - } - - public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable { - var map: [Self.Key: T] = [:] - - for key in allKeys { - if !excludedKeys.contains(key) { - let value = try decode(T.self, forKey: key) - map[key] = value - } - } - - return map - } - -} - extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { return Array(200 ..< 300).contains(statusCode) diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 733b7bc51594..61a478de142b 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct AdditionalPropertiesClass: Codable, Hashable { @@ -22,4 +25,11 @@ public struct AdditionalPropertiesClass: Codable, Hashable { case mapMapString = "map_map_string" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapString, forKey: .mapString) + try container.encodeIfPresent(mapMapString, forKey: .mapMapString) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index e57c8b471765..157cca1d227b 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Animal: Codable, Hashable { @@ -17,4 +20,16 @@ public struct Animal: Codable, Hashable { self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index e09b0e9efdc8..a0b09cb97615 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,5 +6,8 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 630992f6231e..8607cbef1a33 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ApiResponse: Codable, Hashable { @@ -19,4 +22,18 @@ public struct ApiResponse: Codable, Hashable { self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { + case code + case type + case message + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(code, forKey: .code) + try container.encodeIfPresent(type, forKey: .type) + try container.encodeIfPresent(message, forKey: .message) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 4710793fc9a6..f3f161b44c1c 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { case arrayArrayNumber = "ArrayArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index a41968d9b199..d62de957472a 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayOfNumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct ArrayOfNumberOnly: Codable, Hashable { case arrayNumber = "ArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index f442ea725451..360d50d027f1 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ArrayTest: Codable, Hashable { @@ -25,4 +28,12 @@ public struct ArrayTest: Codable, Hashable { case arrayArrayOfModel = "array_array_of_model" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayOfString, forKey: .arrayOfString) + try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) + try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index 44b50bbe0063..f0781a9cb738 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Capitalization: Codable, Hashable { @@ -35,4 +38,15 @@ public struct Capitalization: Codable, Hashable { case ATT_NAME } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(smallCamel, forKey: .smallCamel) + try container.encodeIfPresent(capitalCamel, forKey: .capitalCamel) + try container.encodeIfPresent(smallSnake, forKey: .smallSnake) + try container.encodeIfPresent(capitalSnake, forKey: .capitalSnake) + try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) + try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index c6bf4460da6e..d5519760387a 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Cat: Codable, Hashable { @@ -19,4 +22,18 @@ public struct Cat: Codable, Hashable { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index f9484f9bc8fd..8312680deb37 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct CatAllOf: Codable, Hashable { @@ -15,4 +18,14 @@ public struct CatAllOf: Codable, Hashable { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(declawed, forKey: .declawed) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 6a19bb02d0df..398da60aa73b 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,15 +6,30 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Category: Codable, Hashable { public var id: Int64? - public var name: String = "default-name" + public var name: String? = "default-name" - public init(id: Int64? = nil, name: String = "default-name") { + public init(id: Int64? = nil, name: String? = "default-name") { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encode(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index 5c8e8882831f..761eb4f866ec 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,14 +6,27 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model with \"_class\" property */ public struct ClassModel: Codable, Hashable { - public var _class: String? + public var `class`: String? - public init(_class: String? = nil) { - self._class = _class + public init(`class`: String? = nil) { + self.`class` = `class` } + public enum CodingKeys: String, CodingKey, CaseIterable { + case `class` = "_class" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(`class`, forKey: .`class`) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 1464b047c06a..596048780439 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Client: Codable, Hashable { @@ -15,4 +18,14 @@ public struct Client: Codable, Hashable { self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { + case client + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(client, forKey: .client) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index 5aed7834d537..4ada3ceb605a 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Dog: Codable, Hashable { @@ -19,4 +22,18 @@ public struct Dog: Codable, Hashable { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 716776261d30..f6c3d287301d 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct DogAllOf: Codable, Hashable { @@ -15,4 +18,14 @@ public struct DogAllOf: Codable, Hashable { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(breed, forKey: .breed) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index aa13aa59f86a..0e0aad42abe6 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct EnumArrays: Codable, Hashable { @@ -30,4 +33,11 @@ public struct EnumArrays: Codable, Hashable { case arrayEnum = "array_enum" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justSymbol, forKey: .justSymbol) + try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index d4029d73f8af..6ea2895aee53 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 8b62febdc959..9e44926be9b8 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct EnumTest: Codable, Hashable { @@ -49,4 +52,14 @@ public struct EnumTest: Codable, Hashable { case outerEnum } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(enumString, forKey: .enumString) + try container.encode(enumStringRequired, forKey: .enumStringRequired) + try container.encodeIfPresent(enumInteger, forKey: .enumInteger) + try container.encodeIfPresent(enumNumber, forKey: .enumNumber) + try container.encodeIfPresent(outerEnum, forKey: .outerEnum) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift index aa14d762394d..11694b2ca59b 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Must be named `File` for test. */ public struct File: Codable, Hashable { @@ -17,4 +20,14 @@ public struct File: Codable, Hashable { self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { + case sourceURI + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(sourceURI, forKey: .sourceURI) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index 85987709776e..6aa85d8eecf9 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FileSchemaTestClass: Codable, Hashable { @@ -17,4 +20,16 @@ public struct FileSchemaTestClass: Codable, Hashable { self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { + case file + case files + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(file, forKey: .file) + try container.encodeIfPresent(files, forKey: .files) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index f09cb471b360..114c884efc5e 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FormatTest: Codable, Hashable { @@ -39,4 +42,38 @@ public struct FormatTest: Codable, Hashable { self.password = password } + public enum CodingKeys: String, CodingKey, CaseIterable { + case integer + case int32 + case int64 + case number + case float + case double + case string + case byte + case binary + case date + case dateTime + case uuid + case password + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(integer, forKey: .integer) + try container.encodeIfPresent(int32, forKey: .int32) + try container.encodeIfPresent(int64, forKey: .int64) + try container.encode(number, forKey: .number) + try container.encodeIfPresent(float, forKey: .float) + try container.encodeIfPresent(double, forKey: .double) + try container.encodeIfPresent(string, forKey: .string) + try container.encode(byte, forKey: .byte) + try container.encodeIfPresent(binary, forKey: .binary) + try container.encode(date, forKey: .date) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encode(password, forKey: .password) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index 03d35274a4ee..cb1a7456a7df 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct HasOnlyReadOnly: Codable, Hashable { @@ -17,4 +20,16 @@ public struct HasOnlyReadOnly: Codable, Hashable { self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case foo + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(foo, forKey: .foo) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift index f8f08e4c6c44..8ecdd3b02339 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct List: Codable, Hashable { @@ -19,4 +22,10 @@ public struct List: Codable, Hashable { case _123list = "123-list" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_123list, forKey: ._123list) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index bd4e7b97e81b..0ff74ed8400e 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct MapTest: Codable, Hashable { @@ -32,4 +35,13 @@ public struct MapTest: Codable, Hashable { case indirectMap = "indirect_map" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapMapOfString, forKey: .mapMapOfString) + try container.encodeIfPresent(mapOfEnumString, forKey: .mapOfEnumString) + try container.encodeIfPresent(directMap, forKey: .directMap) + try container.encodeIfPresent(indirectMap, forKey: .indirectMap) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index 80c1781a2bfc..58a0a54ca090 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { @@ -19,4 +22,18 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { + case uuid + case dateTime + case map + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(map, forKey: .map) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index d36d4e27352a..e5906f844364 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,21 +6,31 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name starting with number */ public struct Model200Response: Codable, Hashable { public var name: Int? - public var _class: String? + public var `class`: String? - public init(name: Int? = nil, _class: String? = nil) { + public init(name: Int? = nil, `class`: String? = nil) { self.name = name - self._class = _class + self.`class` = `class` } public enum CodingKeys: String, CodingKey, CaseIterable { case name - case _class = "class" + case `class` = "class" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(`class`, forKey: .`class`) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 49cc57544179..d88c94f05c95 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name same as property name */ public struct Name: Codable, Hashable { @@ -29,4 +32,13 @@ public struct Name: Codable, Hashable { case _123number = "123Number" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encodeIfPresent(snakeCase, forKey: .snakeCase) + try container.encodeIfPresent(property, forKey: .property) + try container.encodeIfPresent(_123number, forKey: ._123number) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 6b024294e288..0f05482b9b7c 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct NumberOnly: Codable, Hashable { @@ -19,4 +22,10 @@ public struct NumberOnly: Codable, Hashable { case justNumber = "JustNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justNumber, forKey: .justNumber) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 8ef7cb79e2c8..100d6b71fed4 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Order: Codable, Hashable { @@ -31,4 +34,24 @@ public struct Order: Codable, Hashable { self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case petId + case quantity + case shipDate + case status + case complete + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(petId, forKey: .petId) + try container.encodeIfPresent(quantity, forKey: .quantity) + try container.encodeIfPresent(shipDate, forKey: .shipDate) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(complete, forKey: .complete) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 9865764ff9bb..15a4e4a15b6e 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct OuterComposite: Codable, Hashable { @@ -25,4 +28,12 @@ public struct OuterComposite: Codable, Hashable { case myBoolean = "my_boolean" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(myNumber, forKey: .myNumber) + try container.encodeIfPresent(myString, forKey: .myString) + try container.encodeIfPresent(myBoolean, forKey: .myBoolean) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index c3b778cbbed4..76c34b3c2ce6 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 1bc823d3e960..a87ab825ea0b 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Pet: Codable, Hashable { @@ -31,4 +34,24 @@ public struct Pet: Codable, Hashable { self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case category + case name + case photoUrls + case tags + case status + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(category, forKey: .category) + try container.encode(name, forKey: .name) + try container.encode(photoUrls, forKey: .photoUrls) + try container.encodeIfPresent(tags, forKey: .tags) + try container.encodeIfPresent(status, forKey: .status) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 03b5b0dbf02b..6426deedf637 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ReadOnlyFirst: Codable, Hashable { @@ -17,4 +20,16 @@ public struct ReadOnlyFirst: Codable, Hashable { self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case baz + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(baz, forKey: .baz) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 5f539f461843..268ce3bfee0b 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,18 +6,27 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing reserved words */ public struct Return: Codable, Hashable { - public var _return: Int? + public var `return`: Int? - public init(_return: Int? = nil) { - self._return = _return + public init(`return`: Int? = nil) { + self.`return` = `return` } public enum CodingKeys: String, CodingKey, CaseIterable { - case _return = "return" + case `return` = "return" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(`return`, forKey: .`return`) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index cb82d2ae3adc..b677523a7491 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct SpecialModelName: Codable, Hashable { @@ -19,4 +22,10 @@ public struct SpecialModelName: Codable, Hashable { case specialPropertyName = "$special[property.name]" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 77ab81f5f341..eb3882d7c2a5 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,40 +6,19 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct StringBooleanMap: Codable, Hashable { - public var additionalProperties: [String: Bool] = [:] - public subscript(key: String) -> Bool? { - get { - if let value = additionalProperties[key] { - return value - } - return nil - } - - set { - additionalProperties[key] = newValue - } + public enum CodingKeys: CodingKey, CaseIterable { } // Encodable protocol methods public func encode(to encoder: Encoder) throws { - - var container = encoder.container(keyedBy: String.self) - - try container.encodeMap(additionalProperties) - } - - // Decodable protocol methods - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) - - var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + var container = encoder.container(keyedBy: CodingKeys.self) } - } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 8b8e24fc39c0..cd5acc827db7 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Tag: Codable, Hashable { @@ -17,4 +20,16 @@ public struct Tag: Codable, Hashable { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(name, forKey: .name) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index f1920ef37788..341c9b4b8c2e 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct TypeHolderDefault: Codable, Hashable { @@ -31,4 +34,14 @@ public struct TypeHolderDefault: Codable, Hashable { case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index 1a23c1b486b8..04166af0895f 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct TypeHolderExample: Codable, Hashable { @@ -31,4 +34,14 @@ public struct TypeHolderExample: Codable, Hashable { case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift index f3b4f6bb958a..9f3ded8fcd93 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct User: Codable, Hashable { @@ -30,4 +33,28 @@ public struct User: Codable, Hashable { self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case username + case firstName + case lastName + case email + case password + case phone + case userStatus + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(username, forKey: .username) + try container.encodeIfPresent(firstName, forKey: .firstName) + try container.encodeIfPresent(lastName, forKey: .lastName) + try container.encodeIfPresent(email, forKey: .email) + try container.encodeIfPresent(password, forKey: .password) + try container.encodeIfPresent(phone, forKey: .phone) + try container.encodeIfPresent(userStatus, forKey: .userStatus) + } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 52b2071ec1aa..774c0427eaa2 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,7 +93,7 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/Podfile b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/Podfile deleted file mode 100644 index 77432f9eee92..000000000000 --- a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/Podfile +++ /dev/null @@ -1,13 +0,0 @@ -platform :ios, '9.0' - -source 'https://cdn.cocoapods.org/' - -use_frameworks! - -target 'SwaggerClient' do - pod "PetstoreClient", :path => "../" - - target 'SwaggerClientTests' do - inherit! :search_paths - end -end diff --git a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/Podfile.lock deleted file mode 100644 index be3757ec1f40..000000000000 --- a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/Podfile.lock +++ /dev/null @@ -1,23 +0,0 @@ -PODS: - - PetstoreClient (1.0.0): - - RxSwift (~> 5.1.1) - - RxSwift (5.1.1) - -DEPENDENCIES: - - PetstoreClient (from `../`) - -SPEC REPOS: - trunk: - - RxSwift - -EXTERNAL SOURCES: - PetstoreClient: - :path: "../" - -SPEC CHECKSUMS: - PetstoreClient: f3d073d9543d90440a155feec649c16b98d84c31 - RxSwift: 81470a2074fa8780320ea5fe4102807cb7118178 - -PODFILE CHECKSUM: 509bec696cc1d8641751b52e4fe4bef04ac4542c - -COCOAPODS: 1.10.0 diff --git a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index f04b8be9b6a9..a9c4af1c818d 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -3,14 +3,13 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 52; objects = { /* Begin PBXBuildFile section */ + A5782C702664FA2300CAA106 /* PetstoreClient in Frameworks */ = {isa = PBXBuildFile; productRef = A5782C6F2664FA2300CAA106 /* PetstoreClient */; }; A5EA1260241941BE00E30FC3 /* FileUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA125E241941BE00E30FC3 /* FileUtils.swift */; }; A5EA1261241941BE00E30FC3 /* UIImage+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA125F241941BE00E30FC3 /* UIImage+Extras.swift */; }; - B024164FBFF71BF644D4419A /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 177A58DD5CF63F2989335DCC /* Pods_SwaggerClient.framework */; }; - B1D0246C8960F47A60098F37 /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6F96A0131101344CC5406CB3 /* Pods_SwaggerClientTests.framework */; }; B596E4BD205657A500B46F03 /* APIHelperTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B596E4BC205657A500B46F03 /* APIHelperTests.swift */; }; EAEC0BC21D4E30CE00C908A3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAEC0BC11D4E30CE00C908A3 /* AppDelegate.swift */; }; EAEC0BC41D4E30CE00C908A3 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAEC0BC31D4E30CE00C908A3 /* ViewController.swift */; }; @@ -33,11 +32,6 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 177A58DD5CF63F2989335DCC /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 2DEFA8828BD4E38FA5262F53 /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; - 4EF2021609D112A6F5AE0F55 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; - 6F96A0131101344CC5406CB3 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 8D99518E8E05FD856A952698 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; A5EA125E241941BE00E30FC3 /* FileUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileUtils.swift; sourceTree = ""; }; A5EA125F241941BE00E30FC3 /* UIImage+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIImage+Extras.swift"; sourceTree = ""; }; B596E4BC205657A500B46F03 /* APIHelperTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APIHelperTests.swift; sourceTree = ""; }; @@ -53,7 +47,6 @@ EAEC0BE31D4E330700C908A3 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = ""; }; EAEC0BE51D4E379000C908A3 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = ""; }; EAEC0BE71D4E38CB00C908A3 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; - EFD8AB05F53C74985527D117 /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -61,7 +54,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - B024164FBFF71BF644D4419A /* Pods_SwaggerClient.framework in Frameworks */, + A5782C702664FA2300CAA106 /* PetstoreClient in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -69,41 +62,26 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - B1D0246C8960F47A60098F37 /* Pods_SwaggerClientTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 55DC454FF5FFEF8A9CBC1CA3 /* Frameworks */ = { + A5782C6E2664FA2300CAA106 /* Frameworks */ = { isa = PBXGroup; children = ( - 177A58DD5CF63F2989335DCC /* Pods_SwaggerClient.framework */, - 6F96A0131101344CC5406CB3 /* Pods_SwaggerClientTests.framework */, ); name = Frameworks; sourceTree = ""; }; - CB19142D951AB5DD885404A8 /* Pods */ = { - isa = PBXGroup; - children = ( - 8D99518E8E05FD856A952698 /* Pods-SwaggerClient.debug.xcconfig */, - 2DEFA8828BD4E38FA5262F53 /* Pods-SwaggerClient.release.xcconfig */, - 4EF2021609D112A6F5AE0F55 /* Pods-SwaggerClientTests.debug.xcconfig */, - EFD8AB05F53C74985527D117 /* Pods-SwaggerClientTests.release.xcconfig */, - ); - name = Pods; - sourceTree = ""; - }; EAEC0BB51D4E30CE00C908A3 = { isa = PBXGroup; children = ( EAEC0BC01D4E30CE00C908A3 /* SwaggerClient */, EAEC0BD51D4E30CE00C908A3 /* SwaggerClientTests */, EAEC0BBF1D4E30CE00C908A3 /* Products */, - CB19142D951AB5DD885404A8 /* Pods */, - 55DC454FF5FFEF8A9CBC1CA3 /* Frameworks */, + A5782C6E2664FA2300CAA106 /* Frameworks */, ); sourceTree = ""; }; @@ -150,17 +128,18 @@ isa = PBXNativeTarget; buildConfigurationList = EAEC0BDB1D4E30CE00C908A3 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 898E536ECC2C4811DDDF67C1 /* [CP] Check Pods Manifest.lock */, EAEC0BBA1D4E30CE00C908A3 /* Sources */, EAEC0BBB1D4E30CE00C908A3 /* Frameworks */, EAEC0BBC1D4E30CE00C908A3 /* Resources */, - 8A7961360961F06AADAF17C9 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( ); name = SwaggerClient; + packageProductDependencies = ( + A5782C6F2664FA2300CAA106 /* PetstoreClient */, + ); productName = SwaggerClient; productReference = EAEC0BBE1D4E30CE00C908A3 /* SwaggerClient.app */; productType = "com.apple.product-type.application"; @@ -169,7 +148,6 @@ isa = PBXNativeTarget; buildConfigurationList = EAEC0BDE1D4E30CE00C908A3 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - 82CB35D52E274C6177DAC0DD /* [CP] Check Pods Manifest.lock */, EAEC0BCE1D4E30CE00C908A3 /* Sources */, EAEC0BCF1D4E30CE00C908A3 /* Frameworks */, EAEC0BD01D4E30CE00C908A3 /* Resources */, @@ -244,65 +222,6 @@ }; /* End PBXResourcesBuildPhase section */ -/* Begin PBXShellScriptBuildPhase section */ - 82CB35D52E274C6177DAC0DD /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClientTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 898E536ECC2C4811DDDF67C1 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClient-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 8A7961360961F06AADAF17C9 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/PetstoreClient/PetstoreClient.framework", - "${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PetstoreClient.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RxSwift.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - /* Begin PBXSourcesBuildPhase section */ EAEC0BBA1D4E30CE00C908A3 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -458,7 +377,8 @@ IPHONEOS_DEPLOYMENT_TARGET = 9.3; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; SWIFT_VERSION = 4.2; VALIDATE_PRODUCT = YES; }; @@ -466,11 +386,13 @@ }; EAEC0BDC1D4E30CE00C908A3 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 8D99518E8E05FD856A952698 /* Pods-SwaggerClient.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -480,11 +402,13 @@ }; EAEC0BDD1D4E30CE00C908A3 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 2DEFA8828BD4E38FA5262F53 /* Pods-SwaggerClient.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -494,12 +418,15 @@ }; EAEC0BDF1D4E30CE00C908A3 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 4EF2021609D112A6F5AE0F55 /* Pods-SwaggerClientTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CLANG_ENABLE_MODULES = YES; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -510,12 +437,15 @@ }; EAEC0BE01D4E30CE00C908A3 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = EFD8AB05F53C74985527D117 /* Pods-SwaggerClientTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CLANG_ENABLE_MODULES = YES; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -554,6 +484,13 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCSwiftPackageProductDependency section */ + A5782C6F2664FA2300CAA106 /* PetstoreClient */ = { + isa = XCSwiftPackageProductDependency; + productName = PetstoreClient; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = EAEC0BB61D4E30CE00C908A3 /* Project object */; } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata index 9b3fa18954f7..00ec9b53a7f1 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata +++ b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata @@ -2,9 +2,9 @@ + location = "group:.."> + location = "group:SwaggerClient.xcodeproj"> diff --git a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 000000000000..231d85369677 --- /dev/null +++ b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,25 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + }, + { + "package": "RxSwift", + "repositoryURL": "https://github.com/ReactiveX/RxSwift.git", + "state": { + "branch": null, + "revision": "7c17a6ccca06b5c107cfa4284e634562ddaf5951", + "version": "6.2.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift index fb68168b697c..db7609caf07d 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift @@ -62,7 +62,7 @@ class PetAPITests: XCTestCase { expectation.fulfill() }, onError: { _ in XCTFail("error getting pet") - }).disposed(by: disposeBag) + }).disposed(by: disposeBag) self.waitForExpectations(timeout: testTimeout, handler: nil) } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/docs/ClassModel.md b/samples/client/petstore/swift5/rxswiftLibrary/docs/ClassModel.md index e3912fdf0fd5..60989bb6b64e 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/docs/ClassModel.md +++ b/samples/client/petstore/swift5/rxswiftLibrary/docs/ClassModel.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**_class** | **String** | | [optional] +**`class`** | **String** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md index 9ca07180e074..76acf726217a 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md @@ -315,7 +315,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) diff --git a/samples/client/petstore/swift5/rxswiftLibrary/docs/Model200Response.md b/samples/client/petstore/swift5/rxswiftLibrary/docs/Model200Response.md index 5865ea690cc3..e064d9d01117 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/docs/Model200Response.md +++ b/samples/client/petstore/swift5/rxswiftLibrary/docs/Model200Response.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **Int** | | [optional] -**_class** | **String** | | [optional] +**`class`** | **String** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/swift5/rxswiftLibrary/docs/Return.md b/samples/client/petstore/swift5/rxswiftLibrary/docs/Return.md index 66d17c27c887..e310b15bb5b7 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/docs/Return.md +++ b/samples/client/petstore/swift5/rxswiftLibrary/docs/Return.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**_return** | **Int** | | [optional] +**`return`** | **Int** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/swift5/rxswiftLibrary/project.yml b/samples/client/petstore/swift5/rxswiftLibrary/project.yml index 60393c28e669..5471ac0bc64a 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/project.yml +++ b/samples/client/petstore/swift5/rxswiftLibrary/project.yml @@ -12,4 +12,5 @@ targets: APPLICATION_EXTENSION_API_ONLY: true scheme: {} dependencies: + - carthage: AnyCodable - carthage: RxSwift diff --git a/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/FILES b/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/FILES index c81943baf2af..27a85ba47e60 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/FILES +++ b/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/FILES @@ -2,64 +2,64 @@ Cartfile Package.swift PetstoreClient.podspec -PetstoreClient/Classes/OpenAPIs/APIHelper.swift -PetstoreClient/Classes/OpenAPIs/APIs.swift -PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift -PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift -PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift -PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift -PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift -PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift -PetstoreClient/Classes/OpenAPIs/CodableHelper.swift -PetstoreClient/Classes/OpenAPIs/Configuration.swift -PetstoreClient/Classes/OpenAPIs/Extensions.swift -PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift -PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift -PetstoreClient/Classes/OpenAPIs/Models.swift -PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift -PetstoreClient/Classes/OpenAPIs/Models/Animal.swift -PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift -PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift -PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift -PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift -PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift -PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift -PetstoreClient/Classes/OpenAPIs/Models/Cat.swift -PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift -PetstoreClient/Classes/OpenAPIs/Models/Category.swift -PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift -PetstoreClient/Classes/OpenAPIs/Models/Client.swift -PetstoreClient/Classes/OpenAPIs/Models/Dog.swift -PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift -PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift -PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift -PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift -PetstoreClient/Classes/OpenAPIs/Models/File.swift -PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift -PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift -PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift -PetstoreClient/Classes/OpenAPIs/Models/List.swift -PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift -PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift -PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift -PetstoreClient/Classes/OpenAPIs/Models/Name.swift -PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift -PetstoreClient/Classes/OpenAPIs/Models/Order.swift -PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift -PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift -PetstoreClient/Classes/OpenAPIs/Models/Pet.swift -PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift -PetstoreClient/Classes/OpenAPIs/Models/Return.swift -PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift -PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift -PetstoreClient/Classes/OpenAPIs/Models/Tag.swift -PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift -PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift -PetstoreClient/Classes/OpenAPIs/Models/User.swift -PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift -PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift -PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift README.md +Sources/PetstoreClient/APIHelper.swift +Sources/PetstoreClient/APIs.swift +Sources/PetstoreClient/APIs/AnotherFakeAPI.swift +Sources/PetstoreClient/APIs/FakeAPI.swift +Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift +Sources/PetstoreClient/APIs/PetAPI.swift +Sources/PetstoreClient/APIs/StoreAPI.swift +Sources/PetstoreClient/APIs/UserAPI.swift +Sources/PetstoreClient/CodableHelper.swift +Sources/PetstoreClient/Configuration.swift +Sources/PetstoreClient/Extensions.swift +Sources/PetstoreClient/JSONDataEncoding.swift +Sources/PetstoreClient/JSONEncodingHelper.swift +Sources/PetstoreClient/Models.swift +Sources/PetstoreClient/Models/AdditionalPropertiesClass.swift +Sources/PetstoreClient/Models/Animal.swift +Sources/PetstoreClient/Models/AnimalFarm.swift +Sources/PetstoreClient/Models/ApiResponse.swift +Sources/PetstoreClient/Models/ArrayOfArrayOfNumberOnly.swift +Sources/PetstoreClient/Models/ArrayOfNumberOnly.swift +Sources/PetstoreClient/Models/ArrayTest.swift +Sources/PetstoreClient/Models/Capitalization.swift +Sources/PetstoreClient/Models/Cat.swift +Sources/PetstoreClient/Models/CatAllOf.swift +Sources/PetstoreClient/Models/Category.swift +Sources/PetstoreClient/Models/ClassModel.swift +Sources/PetstoreClient/Models/Client.swift +Sources/PetstoreClient/Models/Dog.swift +Sources/PetstoreClient/Models/DogAllOf.swift +Sources/PetstoreClient/Models/EnumArrays.swift +Sources/PetstoreClient/Models/EnumClass.swift +Sources/PetstoreClient/Models/EnumTest.swift +Sources/PetstoreClient/Models/File.swift +Sources/PetstoreClient/Models/FileSchemaTestClass.swift +Sources/PetstoreClient/Models/FormatTest.swift +Sources/PetstoreClient/Models/HasOnlyReadOnly.swift +Sources/PetstoreClient/Models/List.swift +Sources/PetstoreClient/Models/MapTest.swift +Sources/PetstoreClient/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +Sources/PetstoreClient/Models/Model200Response.swift +Sources/PetstoreClient/Models/Name.swift +Sources/PetstoreClient/Models/NumberOnly.swift +Sources/PetstoreClient/Models/Order.swift +Sources/PetstoreClient/Models/OuterComposite.swift +Sources/PetstoreClient/Models/OuterEnum.swift +Sources/PetstoreClient/Models/Pet.swift +Sources/PetstoreClient/Models/ReadOnlyFirst.swift +Sources/PetstoreClient/Models/Return.swift +Sources/PetstoreClient/Models/SpecialModelName.swift +Sources/PetstoreClient/Models/StringBooleanMap.swift +Sources/PetstoreClient/Models/Tag.swift +Sources/PetstoreClient/Models/TypeHolderDefault.swift +Sources/PetstoreClient/Models/TypeHolderExample.swift +Sources/PetstoreClient/Models/User.swift +Sources/PetstoreClient/OpenISO8601DateFormatter.swift +Sources/PetstoreClient/SynchronizedDictionary.swift +Sources/PetstoreClient/URLSessionImplementations.swift docs/AdditionalPropertiesClass.md docs/Animal.md docs/AnimalFarm.md diff --git a/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/urlsessionLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/urlsessionLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000000..919434a6254f --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Cartfile b/samples/client/petstore/swift5/urlsessionLibrary/Cartfile index 8b137891791f..843f7adc7794 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Cartfile +++ b/samples/client/petstore/swift5/urlsessionLibrary/Cartfile @@ -1 +1,2 @@ +github "Flight-School/AnyCodable" ~> 0.6.0 diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Package.resolved b/samples/client/petstore/swift5/urlsessionLibrary/Package.resolved new file mode 100644 index 000000000000..d384b276b4bc --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Package.swift b/samples/client/petstore/swift5/urlsessionLibrary/Package.swift index b7fe4734aa8a..eea99ce549e1 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Package.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.0 +// swift-tools-version:5.1 import PackageDescription @@ -19,14 +19,15 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.6.0")), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "PetstoreClient", - dependencies: [], - path: "PetstoreClient/Classes" + dependencies: ["AnyCodable", ], + path: "Sources/PetstoreClient" ), ] ) diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient.podspec b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient.podspec index b61285f6b25e..350282d85aee 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient.podspec @@ -10,5 +10,6 @@ Pod::Spec.new do |s| s.license = 'Proprietary' s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' - s.source_files = 'PetstoreClient/Classes/**/*.swift' + s.source_files = 'Sources/PetstoreClient/**/*.swift' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.0' end diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift deleted file mode 100644 index e57c8b471765..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// Animal.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -public struct Animal: Codable, Hashable { - - public var className: String - public var color: String? = "red" - - public init(className: String, color: String? = "red") { - self.className = className - self.color = color - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift deleted file mode 100644 index 630992f6231e..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// ApiResponse.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -public struct ApiResponse: Codable, Hashable { - - public var code: Int? - public var type: String? - public var message: String? - - public init(code: Int? = nil, type: String? = nil, message: String? = nil) { - self.code = code - self.type = type - self.message = message - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift deleted file mode 100644 index c6bf4460da6e..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// Cat.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -public struct Cat: Codable, Hashable { - - public var className: String - public var color: String? = "red" - public var declawed: Bool? - - public init(className: String, color: String? = "red", declawed: Bool? = nil) { - self.className = className - self.color = color - self.declawed = declawed - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift deleted file mode 100644 index f9484f9bc8fd..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ /dev/null @@ -1,18 +0,0 @@ -// -// CatAllOf.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -public struct CatAllOf: Codable, Hashable { - - public var declawed: Bool? - - public init(declawed: Bool? = nil) { - self.declawed = declawed - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift deleted file mode 100644 index 6a19bb02d0df..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// Category.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -public struct Category: Codable, Hashable { - - public var id: Int64? - public var name: String = "default-name" - - public init(id: Int64? = nil, name: String = "default-name") { - self.id = id - self.name = name - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift deleted file mode 100644 index 5c8e8882831f..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ /dev/null @@ -1,19 +0,0 @@ -// -// ClassModel.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -/** Model for testing model with \"_class\" property */ -public struct ClassModel: Codable, Hashable { - - public var _class: String? - - public init(_class: String? = nil) { - self._class = _class - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift deleted file mode 100644 index 1464b047c06a..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ /dev/null @@ -1,18 +0,0 @@ -// -// Client.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -public struct Client: Codable, Hashable { - - public var client: String? - - public init(client: String? = nil) { - self.client = client - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift deleted file mode 100644 index 5aed7834d537..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// Dog.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -public struct Dog: Codable, Hashable { - - public var className: String - public var color: String? = "red" - public var breed: String? - - public init(className: String, color: String? = "red", breed: String? = nil) { - self.className = className - self.color = color - self.breed = breed - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift deleted file mode 100644 index 716776261d30..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ /dev/null @@ -1,18 +0,0 @@ -// -// DogAllOf.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -public struct DogAllOf: Codable, Hashable { - - public var breed: String? - - public init(breed: String? = nil) { - self.breed = breed - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift deleted file mode 100644 index aa14d762394d..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// File.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -/** Must be named `File` for test. */ -public struct File: Codable, Hashable { - - /** Test capitalization */ - public var sourceURI: String? - - public init(sourceURI: String? = nil) { - self.sourceURI = sourceURI - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift deleted file mode 100644 index 85987709776e..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// FileSchemaTestClass.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -public struct FileSchemaTestClass: Codable, Hashable { - - public var file: File? - public var files: [File]? - - public init(file: File? = nil, files: [File]? = nil) { - self.file = file - self.files = files - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift deleted file mode 100644 index f09cb471b360..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ /dev/null @@ -1,42 +0,0 @@ -// -// FormatTest.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -public struct FormatTest: Codable, Hashable { - - public var integer: Int? - public var int32: Int? - public var int64: Int64? - public var number: Double - public var float: Float? - public var double: Double? - public var string: String? - public var byte: Data - public var binary: URL? - public var date: Date - public var dateTime: Date? - public var uuid: UUID? - public var password: String - - public init(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double? = nil, string: String? = nil, byte: Data, binary: URL? = nil, date: Date, dateTime: Date? = nil, uuid: UUID? = nil, password: String) { - self.integer = integer - self.int32 = int32 - self.int64 = int64 - self.number = number - self.float = float - self.double = double - self.string = string - self.byte = byte - self.binary = binary - self.date = date - self.dateTime = dateTime - self.uuid = uuid - self.password = password - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift deleted file mode 100644 index 03d35274a4ee..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// HasOnlyReadOnly.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -public struct HasOnlyReadOnly: Codable, Hashable { - - public var bar: String? - public var foo: String? - - public init(bar: String? = nil, foo: String? = nil) { - self.bar = bar - self.foo = foo - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift deleted file mode 100644 index 80c1781a2bfc..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// MixedPropertiesAndAdditionalPropertiesClass.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { - - public var uuid: UUID? - public var dateTime: Date? - public var map: [String: Animal]? - - public init(uuid: UUID? = nil, dateTime: Date? = nil, map: [String: Animal]? = nil) { - self.uuid = uuid - self.dateTime = dateTime - self.map = map - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift deleted file mode 100644 index 03b5b0dbf02b..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// ReadOnlyFirst.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -public struct ReadOnlyFirst: Codable, Hashable { - - public var bar: String? - public var baz: String? - - public init(bar: String? = nil, baz: String? = nil) { - self.bar = bar - self.baz = baz - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift deleted file mode 100644 index 8b8e24fc39c0..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// Tag.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -public struct Tag: Codable, Hashable { - - public var id: Int64? - public var name: String? - - public init(id: Int64? = nil, name: String? = nil) { - self.id = id - self.name = name - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift deleted file mode 100644 index f3b4f6bb958a..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ /dev/null @@ -1,33 +0,0 @@ -// -// User.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -public struct User: Codable, Hashable { - - public var id: Int64? - public var username: String? - public var firstName: String? - public var lastName: String? - public var email: String? - public var password: String? - public var phone: String? - /** User Status */ - public var userStatus: Int? - - public init(id: Int64? = nil, username: String? = nil, firstName: String? = nil, lastName: String? = nil, email: String? = nil, password: String? = nil, phone: String? = nil, userStatus: Int? = nil) { - self.id = id - self.username = username - self.firstName = firstName - self.lastName = lastName - self.email = email - self.password = password - self.phone = phone - self.userStatus = userStatus - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIHelper.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIHelper.swift new file mode 100644 index 000000000000..f7bb5274bd98 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIHelper.swift @@ -0,0 +1,71 @@ +// APIHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +public struct APIHelper { + public static func rejectNil(_ source: [String: Any?]) -> [String: Any]? { + let destination = source.reduce(into: [String: Any]()) { result, item in + if let value = item.value { + result[item.key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { + return source.reduce(into: [String: String]()) { result, item in + if let collection = item.value as? [Any?] { + result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + } else if let value: Any = item.value { + result[item.key] = "\(value)" + } + } + } + + public static func convertBoolToString(_ source: [String: Any]?) -> [String: Any]? { + guard let source = source else { + return nil + } + + return source.reduce(into: [String: Any]()) { result, item in + switch item.value { + case let x as Bool: + result[item.key] = x.description + default: + result[item.key] = item.value + } + } + } + + public static func mapValueToPathItem(_ source: Any) -> Any { + if let collection = source as? [Any?] { + return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + } + return source + } + + public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { + let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value as? [Any?] { + collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } else if let value = item.value { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs.swift similarity index 85% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift rename to samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs.swift index dbdab491ff7d..01bc6ff0d8d0 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs.swift @@ -6,7 +6,10 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/AnotherFakeAPI.swift new file mode 100644 index 000000000000..cce6d705d431 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/AnotherFakeAPI.swift @@ -0,0 +1,58 @@ +// +// AnotherFakeAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +extension PetstoreClient { + + +open class AnotherFakeAPI { + /** + To test special tags + + - parameter body: (body) client model + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + To test special tags + - PATCH /another-fake/dummy + - To test special tags and operation ID starting with number + - parameter body: (body) client model + - returns: RequestBuilder + */ + open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { + let path = "/another-fake/dummy" + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift new file mode 100644 index 000000000000..dbe358912cbb --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift @@ -0,0 +1,688 @@ +// +// FakeAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +extension PetstoreClient { + + +open class FakeAPI { + /** + + - parameter body: (body) Input boolean as post body (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { + fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - POST /fake/outer/boolean + - Test serialization of outer boolean types + - parameter body: (body) Input boolean as post body (optional) + - returns: RequestBuilder + */ + open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { + let path = "/fake/outer/boolean" + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + + - parameter body: (body) Input composite as post body (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { + fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - POST /fake/outer/composite + - Test serialization of object with outer number type + - parameter body: (body) Input composite as post body (optional) + - returns: RequestBuilder + */ + open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { + let path = "/fake/outer/composite" + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + + - parameter body: (body) Input number as post body (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { + fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - POST /fake/outer/number + - Test serialization of outer number types + - parameter body: (body) Input number as post body (optional) + - returns: RequestBuilder + */ + open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { + let path = "/fake/outer/number" + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + + - parameter body: (body) Input string as post body (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - POST /fake/outer/string + - Test serialization of outer string types + - parameter body: (body) Input string as post body (optional) + - returns: RequestBuilder + */ + open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { + let path = "/fake/outer/string" + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + + - parameter body: (body) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - PUT /fake/body-with-file-schema + - For this test, the body for this request much reference a schema named `File`. + - parameter body: (body) + - returns: RequestBuilder + */ + open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { + let path = "/fake/body-with-file-schema" + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + + - parameter query: (query) + - parameter body: (body) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - PUT /fake/body-with-query-params + - parameter query: (query) + - parameter body: (body) + - returns: RequestBuilder + */ + open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { + let path = "/fake/body-with-query-params" + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "query": query.encodeToJSON(), + ]) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + To test \"client\" model + + - parameter body: (body) client model + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + To test \"client\" model + - PATCH /fake + - To test \"client\" model + - parameter body: (body) client model + - returns: RequestBuilder + */ + open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { + let path = "/fake" + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + - parameter number: (form) None + - parameter double: (form) None + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter float: (form) None (optional) + - parameter string: (form) None (optional) + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - POST /fake + - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - BASIC: + - type: http + - name: http_basic_test + - parameter number: (form) None + - parameter double: (form) None + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter float: (form) None (optional) + - parameter string: (form) None (optional) + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + - returns: RequestBuilder + */ + open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { + let path = "/fake" + let URLString = PetstoreClient.basePath + path + let formParams: [String: Any?] = [ + "integer": integer?.encodeToJSON(), + "int32": int32?.encodeToJSON(), + "int64": int64?.encodeToJSON(), + "number": number.encodeToJSON(), + "float": float?.encodeToJSON(), + "double": double.encodeToJSON(), + "string": string?.encodeToJSON(), + "pattern_without_delimiter": patternWithoutDelimiter.encodeToJSON(), + "byte": byte.encodeToJSON(), + "binary": binary?.encodeToJSON(), + "date": date?.encodeToJSON(), + "dateTime": dateTime?.encodeToJSON(), + "password": password?.encodeToJSON(), + "callback": callback?.encodeToJSON(), + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + * enum for parameter enumHeaderStringArray + */ + public enum EnumHeaderStringArray_testEnumParameters: String, CaseIterable { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumHeaderString + */ + public enum EnumHeaderString_testEnumParameters: String, CaseIterable { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumQueryStringArray + */ + public enum EnumQueryStringArray_testEnumParameters: String, CaseIterable { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumQueryString + */ + public enum EnumQueryString_testEnumParameters: String, CaseIterable { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumQueryInteger + */ + public enum EnumQueryInteger_testEnumParameters: Int, CaseIterable { + case _1 = 1 + case number2 = -2 + } + + /** + * enum for parameter enumQueryDouble + */ + public enum EnumQueryDouble_testEnumParameters: Double, CaseIterable { + case _11 = 1.1 + case number12 = -1.2 + } + + /** + * enum for parameter enumFormStringArray + */ + public enum EnumFormStringArray_testEnumParameters: String, CaseIterable { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumFormString + */ + public enum EnumFormString_testEnumParameters: String, CaseIterable { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + To test enum parameters + + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to .efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to .efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (query) Query parameter enum test (double) (optional) + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional, default to .dollar) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + To test enum parameters + - GET /fake + - To test enum parameters + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to .efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to .efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (query) Query parameter enum test (double) (optional) + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional, default to .dollar) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) + - returns: RequestBuilder + */ + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + let path = "/fake" + let URLString = PetstoreClient.basePath + path + let formParams: [String: Any?] = [ + "enum_form_string_array": enumFormStringArray?.encodeToJSON(), + "enum_form_string": enumFormString?.encodeToJSON(), + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), + "enum_query_string": enumQueryString?.encodeToJSON(), + "enum_query_integer": enumQueryInteger?.encodeToJSON(), + "enum_query_double": enumQueryDouble?.encodeToJSON(), + ]) + + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), + "enum_header_string": enumHeaderString?.encodeToJSON(), + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + Fake endpoint to test group parameters (optional) + + - parameter requiredStringGroup: (query) Required String in group parameters + - parameter requiredBooleanGroup: (header) Required Boolean in group parameters + - parameter requiredInt64Group: (query) Required Integer in group parameters + - parameter stringGroup: (query) String in group parameters (optional) + - parameter booleanGroup: (header) Boolean in group parameters (optional) + - parameter int64Group: (query) Integer in group parameters (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Fake endpoint to test group parameters (optional) + - DELETE /fake + - Fake endpoint to test group parameters (optional) + - parameter requiredStringGroup: (query) Required String in group parameters + - parameter requiredBooleanGroup: (header) Required Boolean in group parameters + - parameter requiredInt64Group: (query) Required Integer in group parameters + - parameter stringGroup: (query) String in group parameters (optional) + - parameter booleanGroup: (header) Boolean in group parameters (optional) + - parameter int64Group: (query) Integer in group parameters (optional) + - returns: RequestBuilder + */ + open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { + let path = "/fake" + let URLString = PetstoreClient.basePath + path + let parameters: [String: Any]? = nil + + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "required_string_group": requiredStringGroup.encodeToJSON(), + "required_int64_group": requiredInt64Group.encodeToJSON(), + "string_group": stringGroup?.encodeToJSON(), + "int64_group": int64Group?.encodeToJSON(), + ]) + + let nillableHeaders: [String: Any?] = [ + "required_boolean_group": requiredBooleanGroup.encodeToJSON(), + "boolean_group": booleanGroup?.encodeToJSON(), + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + test inline additionalProperties + + - parameter param: (body) request body + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + test inline additionalProperties + - POST /fake/inline-additionalProperties + - parameter param: (body) request body + - returns: RequestBuilder + */ + open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { + let path = "/fake/inline-additionalProperties" + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + test json serialization of form data + + - parameter param: (form) field1 + - parameter param2: (form) field2 + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + test json serialization of form data + - GET /fake/jsonFormData + - parameter param: (form) field1 + - parameter param2: (form) field2 + - returns: RequestBuilder + */ + open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { + let path = "/fake/jsonFormData" + let URLString = PetstoreClient.basePath + path + let formParams: [String: Any?] = [ + "param": param.encodeToJSON(), + "param2": param2.encodeToJSON(), + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift new file mode 100644 index 000000000000..a8bfc8b05464 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift @@ -0,0 +1,61 @@ +// +// FakeClassnameTags123API.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +extension PetstoreClient { + + +open class FakeClassnameTags123API { + /** + To test class name in snake case + + - parameter body: (body) client model + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + To test class name in snake case + - PATCH /fake_classname_test + - To test class name in snake case + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query + - parameter body: (body) client model + - returns: RequestBuilder + */ + open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { + let path = "/fake_classname_test" + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift new file mode 100644 index 000000000000..ea664ec3af4d --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift @@ -0,0 +1,487 @@ +// +// PetAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +extension PetstoreClient { + + +open class PetAPI { + /** + Add a new pet to the store + + - parameter body: (body) Pet object that needs to be added to the store + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Add a new pet to the store + - POST /pet + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter body: (body) Pet object that needs to be added to the store + - returns: RequestBuilder + */ + open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { + let path = "/pet" + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + Deletes a pet + + - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Deletes a pet + - DELETE /pet/{petId} + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) + - returns: RequestBuilder + */ + open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { + var path = "/pet/{petId}" + let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let URLString = PetstoreClient.basePath + path + let parameters: [String: Any]? = nil + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + "api_key": apiKey?.encodeToJSON(), + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + * enum for parameter status + */ + public enum Status_findPetsByStatus: String, CaseIterable { + case available = "available" + case pending = "pending" + case sold = "sold" + } + + /** + Finds Pets by status + + - parameter status: (query) Status values that need to be considered for filter + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Finds Pets by status + - GET /pet/findByStatus + - Multiple status values can be provided with comma separated strings + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter status: (query) Status values that need to be considered for filter + - returns: RequestBuilder<[Pet]> + */ + open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + let path = "/pet/findByStatus" + let URLString = PetstoreClient.basePath + path + let parameters: [String: Any]? = nil + + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "status": status.encodeToJSON(), + ]) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + Finds Pets by tags + + - parameter tags: (query) Tags to filter by + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @available(*, deprecated, message: "This operation is deprecated.") + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Finds Pets by tags + - GET /pet/findByTags + - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter tags: (query) Tags to filter by + - returns: RequestBuilder<[Pet]> + */ + @available(*, deprecated, message: "This operation is deprecated.") + open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { + let path = "/pet/findByTags" + let URLString = PetstoreClient.basePath + path + let parameters: [String: Any]? = nil + + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "tags": tags.encodeToJSON(), + ]) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + Find pet by ID + + - parameter petId: (path) ID of pet to return + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { + getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Find pet by ID + - GET /pet/{petId} + - Returns a single pet + - API Key: + - type: apiKey api_key + - name: api_key + - parameter petId: (path) ID of pet to return + - returns: RequestBuilder + */ + open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { + var path = "/pet/{petId}" + let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let URLString = PetstoreClient.basePath + path + let parameters: [String: Any]? = nil + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + Update an existing pet + + - parameter body: (body) Pet object that needs to be added to the store + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Update an existing pet + - PUT /pet + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter body: (body) Pet object that needs to be added to the store + - returns: RequestBuilder + */ + open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { + let path = "/pet" + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + Updates a pet in the store with form data + + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Updates a pet in the store with form data + - POST /pet/{petId} + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + - returns: RequestBuilder + */ + open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { + var path = "/pet/{petId}" + let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let URLString = PetstoreClient.basePath + path + let formParams: [String: Any?] = [ + "name": name?.encodeToJSON(), + "status": status?.encodeToJSON(), + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + uploads an image + + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter file: (form) file to upload (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + uploads an image + - POST /pet/{petId}/uploadImage + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter file: (form) file to upload (optional) + - returns: RequestBuilder + */ + open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { + var path = "/pet/{petId}/uploadImage" + let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let URLString = PetstoreClient.basePath + path + let formParams: [String: Any?] = [ + "additionalMetadata": additionalMetadata?.encodeToJSON(), + "file": file?.encodeToJSON(), + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + uploads an image (required) + + - parameter petId: (path) ID of pet to update + - parameter requiredFile: (form) file to upload + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + uploads an image (required) + - POST /fake/{petId}/uploadImageWithRequiredFile + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) ID of pet to update + - parameter requiredFile: (form) file to upload + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - returns: RequestBuilder + */ + open class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> RequestBuilder { + var path = "/fake/{petId}/uploadImageWithRequiredFile" + let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let URLString = PetstoreClient.basePath + path + let formParams: [String: Any?] = [ + "additionalMetadata": additionalMetadata?.encodeToJSON(), + "requiredFile": requiredFile.encodeToJSON(), + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/StoreAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/StoreAPI.swift new file mode 100644 index 000000000000..6c53077c654b --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/StoreAPI.swift @@ -0,0 +1,193 @@ +// +// StoreAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +extension PetstoreClient { + + +open class StoreAPI { + /** + Delete purchase order by ID + + - parameter orderId: (path) ID of the order that needs to be deleted + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Delete purchase order by ID + - DELETE /store/order/{order_id} + - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + - parameter orderId: (path) ID of the order that needs to be deleted + - returns: RequestBuilder + */ + open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { + var path = "/store/order/{order_id}" + let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let URLString = PetstoreClient.basePath + path + let parameters: [String: Any]? = nil + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + Returns pet inventories by status + + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { + getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Returns pet inventories by status + - GET /store/inventory + - Returns a map of status codes to quantities + - API Key: + - type: apiKey api_key + - name: api_key + - returns: RequestBuilder<[String: Int]> + */ + open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { + let path = "/store/inventory" + let URLString = PetstoreClient.basePath + path + let parameters: [String: Any]? = nil + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + Find purchase order by ID + + - parameter orderId: (path) ID of pet that needs to be fetched + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Find purchase order by ID + - GET /store/order/{order_id} + - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + - parameter orderId: (path) ID of pet that needs to be fetched + - returns: RequestBuilder + */ + open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { + var path = "/store/order/{order_id}" + let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let URLString = PetstoreClient.basePath + path + let parameters: [String: Any]? = nil + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + Place an order for a pet + + - parameter body: (body) order placed for purchasing the pet + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Place an order for a pet + - POST /store/order + - parameter body: (body) order placed for purchasing the pet + - returns: RequestBuilder + */ + open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { + let path = "/store/order" + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/UserAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/UserAPI.swift new file mode 100644 index 000000000000..1b09adafcfb7 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/UserAPI.swift @@ -0,0 +1,370 @@ +// +// UserAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +extension PetstoreClient { + + +open class UserAPI { + /** + Create user + + - parameter body: (body) Created user object + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Create user + - POST /user + - This can only be done by the logged in user. + - parameter body: (body) Created user object + - returns: RequestBuilder + */ + open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { + let path = "/user" + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Creates list of users with given input array + - POST /user/createWithArray + - parameter body: (body) List of user object + - returns: RequestBuilder + */ + open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { + let path = "/user/createWithArray" + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Creates list of users with given input array + - POST /user/createWithList + - parameter body: (body) List of user object + - returns: RequestBuilder + */ + open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { + let path = "/user/createWithList" + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + Delete user + + - parameter username: (path) The name that needs to be deleted + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Delete user + - DELETE /user/{username} + - This can only be done by the logged in user. + - parameter username: (path) The name that needs to be deleted + - returns: RequestBuilder + */ + open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { + var path = "/user/{username}" + let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let URLString = PetstoreClient.basePath + path + let parameters: [String: Any]? = nil + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + Get user by user name + + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { + getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Get user by user name + - GET /user/{username} + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - returns: RequestBuilder + */ + open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { + var path = "/user/{username}" + let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let URLString = PetstoreClient.basePath + path + let parameters: [String: Any]? = nil + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + Logs user into the system + + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Logs user into the system + - GET /user/login + - responseHeaders: [X-Rate-Limit(Int), X-Expires-After(Date)] + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + - returns: RequestBuilder + */ + open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { + let path = "/user/login" + let URLString = PetstoreClient.basePath + path + let parameters: [String: Any]? = nil + + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "username": username.encodeToJSON(), + "password": password.encodeToJSON(), + ]) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + Logs out current logged in user session + + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Logs out current logged in user session + - GET /user/logout + - returns: RequestBuilder + */ + open class func logoutUserWithRequestBuilder() -> RequestBuilder { + let path = "/user/logout" + let URLString = PetstoreClient.basePath + path + let parameters: [String: Any]? = nil + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + + /** + Updated user + + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Updated user + - PUT /user/{username} + - This can only be done by the logged in user. + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object + - returns: RequestBuilder + */ + open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { + var path = "/user/{username}" + let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let URLString = PetstoreClient.basePath + path + let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let urlComponents = URLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + : + ] + + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() + + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + } + +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/CodableHelper.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/CodableHelper.swift new file mode 100644 index 000000000000..09c82e53e132 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/CodableHelper.swift @@ -0,0 +1,49 @@ +// +// CodableHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +open class CodableHelper { + private static var customDateFormatter: DateFormatter? + private static var defaultDateFormatter: DateFormatter = OpenISO8601DateFormatter() + + private static var customJSONDecoder: JSONDecoder? + private static var defaultJSONDecoder: JSONDecoder = { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .formatted(CodableHelper.dateFormatter) + return decoder + }() + + private static var customJSONEncoder: JSONEncoder? + private static var defaultJSONEncoder: JSONEncoder = { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .formatted(CodableHelper.dateFormatter) + encoder.outputFormatting = .prettyPrinted + return encoder + }() + + public static var dateFormatter: DateFormatter { + get { return customDateFormatter ?? defaultDateFormatter } + set { customDateFormatter = newValue } + } + public static var jsonDecoder: JSONDecoder { + get { return customJSONDecoder ?? defaultJSONDecoder } + set { customJSONDecoder = newValue } + } + public static var jsonEncoder: JSONEncoder { + get { return customJSONEncoder ?? defaultJSONEncoder } + set { customJSONEncoder = newValue } + } + + open class func decode(_ type: T.Type, from data: Data) -> Swift.Result where T: Decodable { + return Swift.Result { try jsonDecoder.decode(type, from: data) } + } + + open class func encode(_ value: T) -> Swift.Result where T: Encodable { + return Swift.Result { try jsonEncoder.encode(value) } + } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Configuration.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Configuration.swift new file mode 100644 index 000000000000..2ad2048e74c3 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Configuration.swift @@ -0,0 +1,19 @@ +// Configuration.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +@available(*, deprecated, renamed: "PetstoreClient.Configuration") +public typealias Configuration = PetstoreClient.Configuration + +extension PetstoreClient { +open class Configuration { + // This value is used to configure the date formatter that is used to serialize dates into JSON format. + // You must set it prior to encoding any dates, and it will only be read once. + @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") + public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift new file mode 100644 index 000000000000..e23035dde30e --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift @@ -0,0 +1,188 @@ +// Extensions.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +extension Bool: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Float: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Int: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Int32: JSONEncodable { + func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } +} + +extension Int64: JSONEncodable { + func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } +} + +extension Double: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension String: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension RawRepresentable where RawValue: JSONEncodable { + func encodeToJSON() -> Any { return self.rawValue as Any } +} + +private func encodeIfPossible(_ object: T) -> Any { + if let encodableObject = object as? JSONEncodable { + return encodableObject.encodeToJSON() + } else { + return object as Any + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> Any { + return self.map(encodeIfPossible) + } +} + +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> Any { + var dictionary = [AnyHashable: Any]() + for (key, value) in self { + dictionary[key] = encodeIfPossible(value) + } + return dictionary as Any + } +} + +extension Data: JSONEncodable { + func encodeToJSON() -> Any { + return self.base64EncodedString(options: Data.Base64EncodingOptions()) + } +} + +extension Date: JSONEncodable { + func encodeToJSON() -> Any { + return CodableHelper.dateFormatter.string(from: self) as Any + } +} + +extension URL: JSONEncodable { + func encodeToJSON() -> Any { + return self + } +} + +extension UUID: JSONEncodable { + func encodeToJSON() -> Any { + return self.uuidString + } +} + +extension String: CodingKey { + + public var stringValue: String { + return self + } + + public init?(stringValue: String) { + self.init(stringLiteral: stringValue) + } + + public var intValue: Int? { + return nil + } + + public init?(intValue: Int) { + return nil + } + +} + +extension KeyedEncodingContainerProtocol { + + public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable { + var arrayContainer = nestedUnkeyedContainer(forKey: key) + try arrayContainer.encode(contentsOf: values) + } + + public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable { + if let values = values { + try encodeArray(values, forKey: key) + } + } + + public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable { + for (key, value) in pairs { + try encode(value, forKey: key) + } + } + + public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable { + if let pairs = pairs { + try encodeMap(pairs) + } + } + +} + +extension KeyedDecodingContainerProtocol { + + public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable { + var tmpArray = [T]() + + var nestedContainer = try nestedUnkeyedContainer(forKey: key) + while !nestedContainer.isAtEnd { + let arrayValue = try nestedContainer.decode(T.self) + tmpArray.append(arrayValue) + } + + return tmpArray + } + + public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable { + var tmpArray: [T]? + + if contains(key) { + tmpArray = try decodeArray(T.self, forKey: key) + } + + return tmpArray + } + + public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable { + var map: [Self.Key: T] = [:] + + for key in allKeys { + if !excludedKeys.contains(key) { + let value = try decode(T.self, forKey: key) + map[key] = value + } + } + + return map + } + +} + +extension HTTPURLResponse { + var isStatusCodeSuccessful: Bool { + return Array(200 ..< 300).contains(statusCode) + } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/JSONDataEncoding.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/JSONDataEncoding.swift new file mode 100644 index 000000000000..b79e9f5e64d5 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/JSONDataEncoding.swift @@ -0,0 +1,53 @@ +// +// JSONDataEncoding.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +public struct JSONDataEncoding { + + // MARK: Properties + + private static let jsonDataKey = "jsonData" + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. This should have a single key/value + /// pair with "jsonData" as the key and a Data object as the value. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) -> URLRequest { + var urlRequest = urlRequest + + guard let jsonData = parameters?[JSONDataEncoding.jsonDataKey] as? Data, !jsonData.isEmpty else { + return urlRequest + } + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = jsonData + + return urlRequest + } + + public static func encodingParameters(jsonData: Data?) -> [String: Any]? { + var returnedParams: [String: Any]? + if let jsonData = jsonData, !jsonData.isEmpty { + var params: [String: Any] = [:] + params[jsonDataKey] = jsonData + returnedParams = params + } + return returnedParams + } + +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/JSONEncodingHelper.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/JSONEncodingHelper.swift new file mode 100644 index 000000000000..02f78ffb4705 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/JSONEncodingHelper.swift @@ -0,0 +1,45 @@ +// +// JSONEncodingHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +open class JSONEncodingHelper { + + open class func encodingParameters(forEncodableObject encodableObj: T?) -> [String: Any]? { + var params: [String: Any]? + + // Encode the Encodable object + if let encodableObj = encodableObj { + let encodeResult = CodableHelper.encode(encodableObj) + do { + let data = try encodeResult.get() + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error.localizedDescription) + } + } + + return params + } + + open class func encodingParameters(forEncodableObject encodableObj: Any?) -> [String: Any]? { + var params: [String: Any]? + + if let encodableObj = encodableObj { + do { + let data = try JSONSerialization.data(withJSONObject: encodableObj, options: .prettyPrinted) + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error.localizedDescription) + return nil + } + } + + return params + } + +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift new file mode 100644 index 000000000000..96e26a20f7d6 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift @@ -0,0 +1,54 @@ +// Models.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +protocol JSONEncodable { + func encodeToJSON() -> Any +} + +public enum ErrorResponse: Error { + case error(Int, Data?, URLResponse?, Error) +} + +public enum DownloadException: Error { + case responseDataMissing + case responseFailed + case requestMissing + case requestMissingPath + case requestMissingURL +} + +public enum DecodableRequestBuilderError: Error { + case emptyDataResponse + case nilHTTPResponse + case unsuccessfulHTTPStatusCode + case jsonDecoding(DecodingError) + case generalError(Error) +} + +open class Response { + public let statusCode: Int + public let header: [String: String] + public let body: T? + + public init(statusCode: Int, header: [String: String], body: T?) { + self.statusCode = statusCode + self.header = header + self.body = body + } + + public convenience init(response: HTTPURLResponse, body: T?) { + let rawHeader = response.allHeaderFields + var header = [String: String]() + for (key, value) in rawHeader { + if let key = key.base as? String, let value = value as? String { + header[key] = value + } + } + self.init(statusCode: response.statusCode, header: header, body: body) + } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesClass.swift new file mode 100644 index 000000000000..1baefca59430 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesClass.swift @@ -0,0 +1,53 @@ +// +// AdditionalPropertiesClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.AdditionalPropertiesClass") +public typealias AdditionalPropertiesClass = PetstoreClient.AdditionalPropertiesClass + +extension PetstoreClient { + +public final class AdditionalPropertiesClass: Codable, Hashable { + + public var mapString: [String: String]? + public var mapMapString: [String: [String: String]]? + + public init(mapString: [String: String]? = nil, mapMapString: [String: [String: String]]? = nil) { + self.mapString = mapString + self.mapMapString = mapMapString + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case mapString = "map_string" + case mapMapString = "map_map_string" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapString, forKey: .mapString) + try container.encodeIfPresent(mapMapString, forKey: .mapMapString) + } + + public static func == (lhs: AdditionalPropertiesClass, rhs: AdditionalPropertiesClass) -> Bool { + lhs.mapString == rhs.mapString && + lhs.mapMapString == rhs.mapMapString + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(mapString?.hashValue) + hasher.combine(mapMapString?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Animal.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Animal.swift new file mode 100644 index 000000000000..bb5768728135 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Animal.swift @@ -0,0 +1,53 @@ +// +// Animal.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Animal") +public typealias Animal = PetstoreClient.Animal + +extension PetstoreClient { + +public final class Animal: Codable, Hashable { + + public var className: String + public var color: String? = "red" + + public init(className: String, color: String? = "red") { + self.className = className + self.color = color + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + } + + public static func == (lhs: Animal, rhs: Animal) -> Bool { + lhs.className == rhs.className && + lhs.color == rhs.color + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(className.hashValue) + hasher.combine(color?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/AnimalFarm.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/AnimalFarm.swift new file mode 100644 index 000000000000..ef664c5e4522 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/AnimalFarm.swift @@ -0,0 +1,19 @@ +// +// AnimalFarm.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.AnimalFarm") +public typealias AnimalFarm = PetstoreClient.AnimalFarm + +extension PetstoreClient { + +public typealias AnimalFarm = [Animal] +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ApiResponse.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ApiResponse.swift new file mode 100644 index 000000000000..7682a7cb7f90 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ApiResponse.swift @@ -0,0 +1,59 @@ +// +// ApiResponse.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.ApiResponse") +public typealias ApiResponse = PetstoreClient.ApiResponse + +extension PetstoreClient { + +public final class ApiResponse: Codable, Hashable { + + public var code: Int? + public var type: String? + public var message: String? + + public init(code: Int? = nil, type: String? = nil, message: String? = nil) { + self.code = code + self.type = type + self.message = message + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case code + case type + case message + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(code, forKey: .code) + try container.encodeIfPresent(type, forKey: .type) + try container.encodeIfPresent(message, forKey: .message) + } + + public static func == (lhs: ApiResponse, rhs: ApiResponse) -> Bool { + lhs.code == rhs.code && + lhs.type == rhs.type && + lhs.message == rhs.message + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(code?.hashValue) + hasher.combine(type?.hashValue) + hasher.combine(message?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayOfArrayOfNumberOnly.swift new file mode 100644 index 000000000000..42b106c6f61e --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayOfArrayOfNumberOnly.swift @@ -0,0 +1,47 @@ +// +// ArrayOfArrayOfNumberOnly.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.ArrayOfArrayOfNumberOnly") +public typealias ArrayOfArrayOfNumberOnly = PetstoreClient.ArrayOfArrayOfNumberOnly + +extension PetstoreClient { + +public final class ArrayOfArrayOfNumberOnly: Codable, Hashable { + + public var arrayArrayNumber: [[Double]]? + + public init(arrayArrayNumber: [[Double]]? = nil) { + self.arrayArrayNumber = arrayArrayNumber + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case arrayArrayNumber = "ArrayArrayNumber" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) + } + + public static func == (lhs: ArrayOfArrayOfNumberOnly, rhs: ArrayOfArrayOfNumberOnly) -> Bool { + lhs.arrayArrayNumber == rhs.arrayArrayNumber + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(arrayArrayNumber?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayOfNumberOnly.swift new file mode 100644 index 000000000000..13a415a44694 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayOfNumberOnly.swift @@ -0,0 +1,47 @@ +// +// ArrayOfNumberOnly.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.ArrayOfNumberOnly") +public typealias ArrayOfNumberOnly = PetstoreClient.ArrayOfNumberOnly + +extension PetstoreClient { + +public final class ArrayOfNumberOnly: Codable, Hashable { + + public var arrayNumber: [Double]? + + public init(arrayNumber: [Double]? = nil) { + self.arrayNumber = arrayNumber + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case arrayNumber = "ArrayNumber" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) + } + + public static func == (lhs: ArrayOfNumberOnly, rhs: ArrayOfNumberOnly) -> Bool { + lhs.arrayNumber == rhs.arrayNumber + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(arrayNumber?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayTest.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayTest.swift new file mode 100644 index 000000000000..943c193458c9 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayTest.swift @@ -0,0 +1,59 @@ +// +// ArrayTest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.ArrayTest") +public typealias ArrayTest = PetstoreClient.ArrayTest + +extension PetstoreClient { + +public final class ArrayTest: Codable, Hashable { + + public var arrayOfString: [String]? + public var arrayArrayOfInteger: [[Int64]]? + public var arrayArrayOfModel: [[ReadOnlyFirst]]? + + public init(arrayOfString: [String]? = nil, arrayArrayOfInteger: [[Int64]]? = nil, arrayArrayOfModel: [[ReadOnlyFirst]]? = nil) { + self.arrayOfString = arrayOfString + self.arrayArrayOfInteger = arrayArrayOfInteger + self.arrayArrayOfModel = arrayArrayOfModel + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case arrayOfString = "array_of_string" + case arrayArrayOfInteger = "array_array_of_integer" + case arrayArrayOfModel = "array_array_of_model" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayOfString, forKey: .arrayOfString) + try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) + try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) + } + + public static func == (lhs: ArrayTest, rhs: ArrayTest) -> Bool { + lhs.arrayOfString == rhs.arrayOfString && + lhs.arrayArrayOfInteger == rhs.arrayArrayOfInteger && + lhs.arrayArrayOfModel == rhs.arrayArrayOfModel + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(arrayOfString?.hashValue) + hasher.combine(arrayArrayOfInteger?.hashValue) + hasher.combine(arrayArrayOfModel?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Capitalization.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Capitalization.swift new file mode 100644 index 000000000000..d72936f45ac4 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Capitalization.swift @@ -0,0 +1,78 @@ +// +// Capitalization.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Capitalization") +public typealias Capitalization = PetstoreClient.Capitalization + +extension PetstoreClient { + +public final class Capitalization: Codable, Hashable { + + public var smallCamel: String? + public var capitalCamel: String? + public var smallSnake: String? + public var capitalSnake: String? + public var sCAETHFlowPoints: String? + /** Name of the pet */ + public var ATT_NAME: String? + + public init(smallCamel: String? = nil, capitalCamel: String? = nil, smallSnake: String? = nil, capitalSnake: String? = nil, sCAETHFlowPoints: String? = nil, ATT_NAME: String? = nil) { + self.smallCamel = smallCamel + self.capitalCamel = capitalCamel + self.smallSnake = smallSnake + self.capitalSnake = capitalSnake + self.sCAETHFlowPoints = sCAETHFlowPoints + self.ATT_NAME = ATT_NAME + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case smallCamel + case capitalCamel = "CapitalCamel" + case smallSnake = "small_Snake" + case capitalSnake = "Capital_Snake" + case sCAETHFlowPoints = "SCA_ETH_Flow_Points" + case ATT_NAME + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(smallCamel, forKey: .smallCamel) + try container.encodeIfPresent(capitalCamel, forKey: .capitalCamel) + try container.encodeIfPresent(smallSnake, forKey: .smallSnake) + try container.encodeIfPresent(capitalSnake, forKey: .capitalSnake) + try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) + try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) + } + + public static func == (lhs: Capitalization, rhs: Capitalization) -> Bool { + lhs.smallCamel == rhs.smallCamel && + lhs.capitalCamel == rhs.capitalCamel && + lhs.smallSnake == rhs.smallSnake && + lhs.capitalSnake == rhs.capitalSnake && + lhs.sCAETHFlowPoints == rhs.sCAETHFlowPoints && + lhs.ATT_NAME == rhs.ATT_NAME + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(smallCamel?.hashValue) + hasher.combine(capitalCamel?.hashValue) + hasher.combine(smallSnake?.hashValue) + hasher.combine(capitalSnake?.hashValue) + hasher.combine(sCAETHFlowPoints?.hashValue) + hasher.combine(ATT_NAME?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Cat.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Cat.swift new file mode 100644 index 000000000000..5ba88eae81cd --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Cat.swift @@ -0,0 +1,59 @@ +// +// Cat.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Cat") +public typealias Cat = PetstoreClient.Cat + +extension PetstoreClient { + +public final class Cat: Codable, Hashable { + + public var className: String + public var color: String? = "red" + public var declawed: Bool? + + public init(className: String, color: String? = "red", declawed: Bool? = nil) { + self.className = className + self.color = color + self.declawed = declawed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(declawed, forKey: .declawed) + } + + public static func == (lhs: Cat, rhs: Cat) -> Bool { + lhs.className == rhs.className && + lhs.color == rhs.color && + lhs.declawed == rhs.declawed + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(className.hashValue) + hasher.combine(color?.hashValue) + hasher.combine(declawed?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/CatAllOf.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/CatAllOf.swift new file mode 100644 index 000000000000..4437f05ec8ca --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/CatAllOf.swift @@ -0,0 +1,47 @@ +// +// CatAllOf.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.CatAllOf") +public typealias CatAllOf = PetstoreClient.CatAllOf + +extension PetstoreClient { + +public final class CatAllOf: Codable, Hashable { + + public var declawed: Bool? + + public init(declawed: Bool? = nil) { + self.declawed = declawed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(declawed, forKey: .declawed) + } + + public static func == (lhs: CatAllOf, rhs: CatAllOf) -> Bool { + lhs.declawed == rhs.declawed + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(declawed?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Category.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Category.swift new file mode 100644 index 000000000000..4cd6f0940b06 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Category.swift @@ -0,0 +1,53 @@ +// +// Category.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Category") +public typealias Category = PetstoreClient.Category + +extension PetstoreClient { + +public final class Category: Codable, Hashable { + + public var id: Int64? + public var name: String? = "default-name" + + public init(id: Int64? = nil, name: String? = "default-name") { + self.id = id + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encode(name, forKey: .name) + } + + public static func == (lhs: Category, rhs: Category) -> Bool { + lhs.id == rhs.id && + lhs.name == rhs.name + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(id?.hashValue) + hasher.combine(name.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ClassModel.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ClassModel.swift new file mode 100644 index 000000000000..ebba6acf1f30 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ClassModel.swift @@ -0,0 +1,48 @@ +// +// ClassModel.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.ClassModel") +public typealias ClassModel = PetstoreClient.ClassModel + +extension PetstoreClient { + +/** Model for testing model with \"_class\" property */ +public final class ClassModel: Codable, Hashable { + + public var _class: String? + + public init(_class: String? = nil) { + self._class = _class + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case _class + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_class, forKey: ._class) + } + + public static func == (lhs: ClassModel, rhs: ClassModel) -> Bool { + lhs._class == rhs._class + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(_class?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Client.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Client.swift new file mode 100644 index 000000000000..d671608ac8e6 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Client.swift @@ -0,0 +1,47 @@ +// +// Client.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Client") +public typealias Client = PetstoreClient.Client + +extension PetstoreClient { + +public final class Client: Codable, Hashable { + + public var client: String? + + public init(client: String? = nil) { + self.client = client + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case client + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(client, forKey: .client) + } + + public static func == (lhs: Client, rhs: Client) -> Bool { + lhs.client == rhs.client + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(client?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Dog.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Dog.swift new file mode 100644 index 000000000000..a506fe020977 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Dog.swift @@ -0,0 +1,59 @@ +// +// Dog.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Dog") +public typealias Dog = PetstoreClient.Dog + +extension PetstoreClient { + +public final class Dog: Codable, Hashable { + + public var className: String + public var color: String? = "red" + public var breed: String? + + public init(className: String, color: String? = "red", breed: String? = nil) { + self.className = className + self.color = color + self.breed = breed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(breed, forKey: .breed) + } + + public static func == (lhs: Dog, rhs: Dog) -> Bool { + lhs.className == rhs.className && + lhs.color == rhs.color && + lhs.breed == rhs.breed + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(className.hashValue) + hasher.combine(color?.hashValue) + hasher.combine(breed?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/DogAllOf.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/DogAllOf.swift new file mode 100644 index 000000000000..ea53f2f14e1f --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/DogAllOf.swift @@ -0,0 +1,47 @@ +// +// DogAllOf.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.DogAllOf") +public typealias DogAllOf = PetstoreClient.DogAllOf + +extension PetstoreClient { + +public final class DogAllOf: Codable, Hashable { + + public var breed: String? + + public init(breed: String? = nil) { + self.breed = breed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(breed, forKey: .breed) + } + + public static func == (lhs: DogAllOf, rhs: DogAllOf) -> Bool { + lhs.breed == rhs.breed + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(breed?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumArrays.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumArrays.swift new file mode 100644 index 000000000000..82a858e12504 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumArrays.swift @@ -0,0 +1,61 @@ +// +// EnumArrays.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.EnumArrays") +public typealias EnumArrays = PetstoreClient.EnumArrays + +extension PetstoreClient { + +public final class EnumArrays: Codable, Hashable { + + public enum JustSymbol: String, Codable, CaseIterable { + case greaterThanOrEqualTo = ">=" + case dollar = "$" + } + public enum ArrayEnum: String, Codable, CaseIterable { + case fish = "fish" + case crab = "crab" + } + public var justSymbol: JustSymbol? + public var arrayEnum: [ArrayEnum]? + + public init(justSymbol: JustSymbol? = nil, arrayEnum: [ArrayEnum]? = nil) { + self.justSymbol = justSymbol + self.arrayEnum = arrayEnum + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case justSymbol = "just_symbol" + case arrayEnum = "array_enum" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justSymbol, forKey: .justSymbol) + try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) + } + + public static func == (lhs: EnumArrays, rhs: EnumArrays) -> Bool { + lhs.justSymbol == rhs.justSymbol && + lhs.arrayEnum == rhs.arrayEnum + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(justSymbol?.hashValue) + hasher.combine(arrayEnum?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumClass.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumClass.swift new file mode 100644 index 000000000000..37984373236a --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumClass.swift @@ -0,0 +1,23 @@ +// +// EnumClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.EnumClass") +public typealias EnumClass = PetstoreClient.EnumClass + +extension PetstoreClient { + +public enum EnumClass: String, Codable, CaseIterable { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumTest.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumTest.swift new file mode 100644 index 000000000000..dc229bc01088 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumTest.swift @@ -0,0 +1,89 @@ +// +// EnumTest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.EnumTest") +public typealias EnumTest = PetstoreClient.EnumTest + +extension PetstoreClient { + +public final class EnumTest: Codable, Hashable { + + public enum EnumString: String, Codable, CaseIterable { + case upper = "UPPER" + case lower = "lower" + case empty = "" + } + public enum EnumStringRequired: String, Codable, CaseIterable { + case upper = "UPPER" + case lower = "lower" + case empty = "" + } + public enum EnumInteger: Int, Codable, CaseIterable { + case _1 = 1 + case number1 = -1 + } + public enum EnumNumber: Double, Codable, CaseIterable { + case _11 = 1.1 + case number12 = -1.2 + } + public var enumString: EnumString? + public var enumStringRequired: EnumStringRequired + public var enumInteger: EnumInteger? + public var enumNumber: EnumNumber? + public var outerEnum: OuterEnum? + + public init(enumString: EnumString? = nil, enumStringRequired: EnumStringRequired, enumInteger: EnumInteger? = nil, enumNumber: EnumNumber? = nil, outerEnum: OuterEnum? = nil) { + self.enumString = enumString + self.enumStringRequired = enumStringRequired + self.enumInteger = enumInteger + self.enumNumber = enumNumber + self.outerEnum = outerEnum + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case enumString = "enum_string" + case enumStringRequired = "enum_string_required" + case enumInteger = "enum_integer" + case enumNumber = "enum_number" + case outerEnum + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(enumString, forKey: .enumString) + try container.encode(enumStringRequired, forKey: .enumStringRequired) + try container.encodeIfPresent(enumInteger, forKey: .enumInteger) + try container.encodeIfPresent(enumNumber, forKey: .enumNumber) + try container.encodeIfPresent(outerEnum, forKey: .outerEnum) + } + + public static func == (lhs: EnumTest, rhs: EnumTest) -> Bool { + lhs.enumString == rhs.enumString && + lhs.enumStringRequired == rhs.enumStringRequired && + lhs.enumInteger == rhs.enumInteger && + lhs.enumNumber == rhs.enumNumber && + lhs.outerEnum == rhs.outerEnum + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(enumString?.hashValue) + hasher.combine(enumStringRequired.hashValue) + hasher.combine(enumInteger?.hashValue) + hasher.combine(enumNumber?.hashValue) + hasher.combine(outerEnum?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/File.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/File.swift new file mode 100644 index 000000000000..0e8e00f2e4e2 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/File.swift @@ -0,0 +1,49 @@ +// +// File.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.File") +public typealias File = PetstoreClient.File + +extension PetstoreClient { + +/** Must be named `File` for test. */ +public final class File: Codable, Hashable { + + /** Test capitalization */ + public var sourceURI: String? + + public init(sourceURI: String? = nil) { + self.sourceURI = sourceURI + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case sourceURI + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(sourceURI, forKey: .sourceURI) + } + + public static func == (lhs: File, rhs: File) -> Bool { + lhs.sourceURI == rhs.sourceURI + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(sourceURI?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/FileSchemaTestClass.swift new file mode 100644 index 000000000000..3eaf14887a65 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/FileSchemaTestClass.swift @@ -0,0 +1,53 @@ +// +// FileSchemaTestClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.FileSchemaTestClass") +public typealias FileSchemaTestClass = PetstoreClient.FileSchemaTestClass + +extension PetstoreClient { + +public final class FileSchemaTestClass: Codable, Hashable { + + public var file: File? + public var files: [File]? + + public init(file: File? = nil, files: [File]? = nil) { + self.file = file + self.files = files + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case file + case files + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(file, forKey: .file) + try container.encodeIfPresent(files, forKey: .files) + } + + public static func == (lhs: FileSchemaTestClass, rhs: FileSchemaTestClass) -> Bool { + lhs.file == rhs.file && + lhs.files == rhs.files + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(file?.hashValue) + hasher.combine(files?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/FormatTest.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/FormatTest.swift new file mode 100644 index 000000000000..3becb33e171e --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/FormatTest.swift @@ -0,0 +1,119 @@ +// +// FormatTest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.FormatTest") +public typealias FormatTest = PetstoreClient.FormatTest + +extension PetstoreClient { + +public final class FormatTest: Codable, Hashable { + + public var integer: Int? + public var int32: Int? + public var int64: Int64? + public var number: Double + public var float: Float? + public var double: Double? + public var string: String? + public var byte: Data + public var binary: URL? + public var date: Date + public var dateTime: Date? + public var uuid: UUID? + public var password: String + + public init(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double? = nil, string: String? = nil, byte: Data, binary: URL? = nil, date: Date, dateTime: Date? = nil, uuid: UUID? = nil, password: String) { + self.integer = integer + self.int32 = int32 + self.int64 = int64 + self.number = number + self.float = float + self.double = double + self.string = string + self.byte = byte + self.binary = binary + self.date = date + self.dateTime = dateTime + self.uuid = uuid + self.password = password + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case integer + case int32 + case int64 + case number + case float + case double + case string + case byte + case binary + case date + case dateTime + case uuid + case password + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(integer, forKey: .integer) + try container.encodeIfPresent(int32, forKey: .int32) + try container.encodeIfPresent(int64, forKey: .int64) + try container.encode(number, forKey: .number) + try container.encodeIfPresent(float, forKey: .float) + try container.encodeIfPresent(double, forKey: .double) + try container.encodeIfPresent(string, forKey: .string) + try container.encode(byte, forKey: .byte) + try container.encodeIfPresent(binary, forKey: .binary) + try container.encode(date, forKey: .date) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encode(password, forKey: .password) + } + + public static func == (lhs: FormatTest, rhs: FormatTest) -> Bool { + lhs.integer == rhs.integer && + lhs.int32 == rhs.int32 && + lhs.int64 == rhs.int64 && + lhs.number == rhs.number && + lhs.float == rhs.float && + lhs.double == rhs.double && + lhs.string == rhs.string && + lhs.byte == rhs.byte && + lhs.binary == rhs.binary && + lhs.date == rhs.date && + lhs.dateTime == rhs.dateTime && + lhs.uuid == rhs.uuid && + lhs.password == rhs.password + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(integer?.hashValue) + hasher.combine(int32?.hashValue) + hasher.combine(int64?.hashValue) + hasher.combine(number.hashValue) + hasher.combine(float?.hashValue) + hasher.combine(double?.hashValue) + hasher.combine(string?.hashValue) + hasher.combine(byte.hashValue) + hasher.combine(binary?.hashValue) + hasher.combine(date.hashValue) + hasher.combine(dateTime?.hashValue) + hasher.combine(uuid?.hashValue) + hasher.combine(password.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/HasOnlyReadOnly.swift new file mode 100644 index 000000000000..2eeee949b9e5 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/HasOnlyReadOnly.swift @@ -0,0 +1,53 @@ +// +// HasOnlyReadOnly.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.HasOnlyReadOnly") +public typealias HasOnlyReadOnly = PetstoreClient.HasOnlyReadOnly + +extension PetstoreClient { + +public final class HasOnlyReadOnly: Codable, Hashable { + + public var bar: String? + public var foo: String? + + public init(bar: String? = nil, foo: String? = nil) { + self.bar = bar + self.foo = foo + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case foo + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(foo, forKey: .foo) + } + + public static func == (lhs: HasOnlyReadOnly, rhs: HasOnlyReadOnly) -> Bool { + lhs.bar == rhs.bar && + lhs.foo == rhs.foo + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(bar?.hashValue) + hasher.combine(foo?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/List.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/List.swift new file mode 100644 index 000000000000..d7bd15e4ab7a --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/List.swift @@ -0,0 +1,47 @@ +// +// List.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.List") +public typealias List = PetstoreClient.List + +extension PetstoreClient { + +public final class List: Codable, Hashable { + + public var _123list: String? + + public init(_123list: String? = nil) { + self._123list = _123list + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case _123list = "123-list" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_123list, forKey: ._123list) + } + + public static func == (lhs: List, rhs: List) -> Bool { + lhs._123list == rhs._123list + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(_123list?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/MapTest.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/MapTest.swift new file mode 100644 index 000000000000..e1b5051c98ab --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/MapTest.swift @@ -0,0 +1,69 @@ +// +// MapTest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.MapTest") +public typealias MapTest = PetstoreClient.MapTest + +extension PetstoreClient { + +public final class MapTest: Codable, Hashable { + + public enum MapOfEnumString: String, Codable, CaseIterable { + case upper = "UPPER" + case lower = "lower" + } + public var mapMapOfString: [String: [String: String]]? + public var mapOfEnumString: [String: String]? + public var directMap: [String: Bool]? + public var indirectMap: StringBooleanMap? + + public init(mapMapOfString: [String: [String: String]]? = nil, mapOfEnumString: [String: String]? = nil, directMap: [String: Bool]? = nil, indirectMap: StringBooleanMap? = nil) { + self.mapMapOfString = mapMapOfString + self.mapOfEnumString = mapOfEnumString + self.directMap = directMap + self.indirectMap = indirectMap + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case mapMapOfString = "map_map_of_string" + case mapOfEnumString = "map_of_enum_string" + case directMap = "direct_map" + case indirectMap = "indirect_map" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapMapOfString, forKey: .mapMapOfString) + try container.encodeIfPresent(mapOfEnumString, forKey: .mapOfEnumString) + try container.encodeIfPresent(directMap, forKey: .directMap) + try container.encodeIfPresent(indirectMap, forKey: .indirectMap) + } + + public static func == (lhs: MapTest, rhs: MapTest) -> Bool { + lhs.mapMapOfString == rhs.mapMapOfString && + lhs.mapOfEnumString == rhs.mapOfEnumString && + lhs.directMap == rhs.directMap && + lhs.indirectMap == rhs.indirectMap + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(mapMapOfString?.hashValue) + hasher.combine(mapOfEnumString?.hashValue) + hasher.combine(directMap?.hashValue) + hasher.combine(indirectMap?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/MixedPropertiesAndAdditionalPropertiesClass.swift new file mode 100644 index 000000000000..126d5952d232 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -0,0 +1,59 @@ +// +// MixedPropertiesAndAdditionalPropertiesClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.MixedPropertiesAndAdditionalPropertiesClass") +public typealias MixedPropertiesAndAdditionalPropertiesClass = PetstoreClient.MixedPropertiesAndAdditionalPropertiesClass + +extension PetstoreClient { + +public final class MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { + + public var uuid: UUID? + public var dateTime: Date? + public var map: [String: Animal]? + + public init(uuid: UUID? = nil, dateTime: Date? = nil, map: [String: Animal]? = nil) { + self.uuid = uuid + self.dateTime = dateTime + self.map = map + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case uuid + case dateTime + case map + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(map, forKey: .map) + } + + public static func == (lhs: MixedPropertiesAndAdditionalPropertiesClass, rhs: MixedPropertiesAndAdditionalPropertiesClass) -> Bool { + lhs.uuid == rhs.uuid && + lhs.dateTime == rhs.dateTime && + lhs.map == rhs.map + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(uuid?.hashValue) + hasher.combine(dateTime?.hashValue) + hasher.combine(map?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Model200Response.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Model200Response.swift new file mode 100644 index 000000000000..abec4f578a33 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Model200Response.swift @@ -0,0 +1,54 @@ +// +// Model200Response.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Model200Response") +public typealias Model200Response = PetstoreClient.Model200Response + +extension PetstoreClient { + +/** Model for testing model name starting with number */ +public final class Model200Response: Codable, Hashable { + + public var name: Int? + public var _class: String? + + public init(name: Int? = nil, _class: String? = nil) { + self.name = name + self._class = _class + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case _class = "class" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(_class, forKey: ._class) + } + + public static func == (lhs: Model200Response, rhs: Model200Response) -> Bool { + lhs.name == rhs.name && + lhs._class == rhs._class + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(name?.hashValue) + hasher.combine(_class?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Name.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Name.swift new file mode 100644 index 000000000000..ae67e9ce2c97 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Name.swift @@ -0,0 +1,66 @@ +// +// Name.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Name") +public typealias Name = PetstoreClient.Name + +extension PetstoreClient { + +/** Model for testing model name same as property name */ +public final class Name: Codable, Hashable { + + public var name: Int + public var snakeCase: Int? + public var property: String? + public var _123number: Int? + + public init(name: Int, snakeCase: Int? = nil, property: String? = nil, _123number: Int? = nil) { + self.name = name + self.snakeCase = snakeCase + self.property = property + self._123number = _123number + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case snakeCase = "snake_case" + case property + case _123number = "123Number" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encodeIfPresent(snakeCase, forKey: .snakeCase) + try container.encodeIfPresent(property, forKey: .property) + try container.encodeIfPresent(_123number, forKey: ._123number) + } + + public static func == (lhs: Name, rhs: Name) -> Bool { + lhs.name == rhs.name && + lhs.snakeCase == rhs.snakeCase && + lhs.property == rhs.property && + lhs._123number == rhs._123number + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(name.hashValue) + hasher.combine(snakeCase?.hashValue) + hasher.combine(property?.hashValue) + hasher.combine(_123number?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/NumberOnly.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/NumberOnly.swift new file mode 100644 index 000000000000..122ba86ecf64 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/NumberOnly.swift @@ -0,0 +1,47 @@ +// +// NumberOnly.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.NumberOnly") +public typealias NumberOnly = PetstoreClient.NumberOnly + +extension PetstoreClient { + +public final class NumberOnly: Codable, Hashable { + + public var justNumber: Double? + + public init(justNumber: Double? = nil) { + self.justNumber = justNumber + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case justNumber = "JustNumber" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justNumber, forKey: .justNumber) + } + + public static func == (lhs: NumberOnly, rhs: NumberOnly) -> Bool { + lhs.justNumber == rhs.justNumber + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(justNumber?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Order.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Order.swift new file mode 100644 index 000000000000..31979b10b855 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Order.swift @@ -0,0 +1,83 @@ +// +// Order.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Order") +public typealias Order = PetstoreClient.Order + +extension PetstoreClient { + +public final class Order: Codable, Hashable { + + public enum Status: String, Codable, CaseIterable { + case placed = "placed" + case approved = "approved" + case delivered = "delivered" + } + public var id: Int64? + public var petId: Int64? + public var quantity: Int? + public var shipDate: Date? + /** Order Status */ + public var status: Status? + public var complete: Bool? = false + + public init(id: Int64? = nil, petId: Int64? = nil, quantity: Int? = nil, shipDate: Date? = nil, status: Status? = nil, complete: Bool? = false) { + self.id = id + self.petId = petId + self.quantity = quantity + self.shipDate = shipDate + self.status = status + self.complete = complete + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case petId + case quantity + case shipDate + case status + case complete + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(petId, forKey: .petId) + try container.encodeIfPresent(quantity, forKey: .quantity) + try container.encodeIfPresent(shipDate, forKey: .shipDate) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(complete, forKey: .complete) + } + + public static func == (lhs: Order, rhs: Order) -> Bool { + lhs.id == rhs.id && + lhs.petId == rhs.petId && + lhs.quantity == rhs.quantity && + lhs.shipDate == rhs.shipDate && + lhs.status == rhs.status && + lhs.complete == rhs.complete + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(id?.hashValue) + hasher.combine(petId?.hashValue) + hasher.combine(quantity?.hashValue) + hasher.combine(shipDate?.hashValue) + hasher.combine(status?.hashValue) + hasher.combine(complete?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/OuterComposite.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/OuterComposite.swift new file mode 100644 index 000000000000..377df8fd2e0b --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/OuterComposite.swift @@ -0,0 +1,59 @@ +// +// OuterComposite.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.OuterComposite") +public typealias OuterComposite = PetstoreClient.OuterComposite + +extension PetstoreClient { + +public final class OuterComposite: Codable, Hashable { + + public var myNumber: Double? + public var myString: String? + public var myBoolean: Bool? + + public init(myNumber: Double? = nil, myString: String? = nil, myBoolean: Bool? = nil) { + self.myNumber = myNumber + self.myString = myString + self.myBoolean = myBoolean + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case myNumber = "my_number" + case myString = "my_string" + case myBoolean = "my_boolean" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(myNumber, forKey: .myNumber) + try container.encodeIfPresent(myString, forKey: .myString) + try container.encodeIfPresent(myBoolean, forKey: .myBoolean) + } + + public static func == (lhs: OuterComposite, rhs: OuterComposite) -> Bool { + lhs.myNumber == rhs.myNumber && + lhs.myString == rhs.myString && + lhs.myBoolean == rhs.myBoolean + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(myNumber?.hashValue) + hasher.combine(myString?.hashValue) + hasher.combine(myBoolean?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/OuterEnum.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/OuterEnum.swift new file mode 100644 index 000000000000..78ad5bedb38a --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/OuterEnum.swift @@ -0,0 +1,23 @@ +// +// OuterEnum.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.OuterEnum") +public typealias OuterEnum = PetstoreClient.OuterEnum + +extension PetstoreClient { + +public enum OuterEnum: String, Codable, CaseIterable { + case placed = "placed" + case approved = "approved" + case delivered = "delivered" +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Pet.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Pet.swift new file mode 100644 index 000000000000..d93428d9bda5 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Pet.swift @@ -0,0 +1,83 @@ +// +// Pet.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Pet") +public typealias Pet = PetstoreClient.Pet + +extension PetstoreClient { + +public final class Pet: Codable, Hashable { + + public enum Status: String, Codable, CaseIterable { + case available = "available" + case pending = "pending" + case sold = "sold" + } + public var id: Int64? + public var category: Category? + public var name: String + public var photoUrls: [String] + public var tags: [Tag]? + /** pet status in the store */ + public var status: Status? + + public init(id: Int64? = nil, category: Category? = nil, name: String, photoUrls: [String], tags: [Tag]? = nil, status: Status? = nil) { + self.id = id + self.category = category + self.name = name + self.photoUrls = photoUrls + self.tags = tags + self.status = status + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case category + case name + case photoUrls + case tags + case status + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(category, forKey: .category) + try container.encode(name, forKey: .name) + try container.encode(photoUrls, forKey: .photoUrls) + try container.encodeIfPresent(tags, forKey: .tags) + try container.encodeIfPresent(status, forKey: .status) + } + + public static func == (lhs: Pet, rhs: Pet) -> Bool { + lhs.id == rhs.id && + lhs.category == rhs.category && + lhs.name == rhs.name && + lhs.photoUrls == rhs.photoUrls && + lhs.tags == rhs.tags && + lhs.status == rhs.status + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(id?.hashValue) + hasher.combine(category?.hashValue) + hasher.combine(name.hashValue) + hasher.combine(photoUrls.hashValue) + hasher.combine(tags?.hashValue) + hasher.combine(status?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ReadOnlyFirst.swift new file mode 100644 index 000000000000..e3a074ebcc8f --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ReadOnlyFirst.swift @@ -0,0 +1,53 @@ +// +// ReadOnlyFirst.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.ReadOnlyFirst") +public typealias ReadOnlyFirst = PetstoreClient.ReadOnlyFirst + +extension PetstoreClient { + +public final class ReadOnlyFirst: Codable, Hashable { + + public var bar: String? + public var baz: String? + + public init(bar: String? = nil, baz: String? = nil) { + self.bar = bar + self.baz = baz + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case baz + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(baz, forKey: .baz) + } + + public static func == (lhs: ReadOnlyFirst, rhs: ReadOnlyFirst) -> Bool { + lhs.bar == rhs.bar && + lhs.baz == rhs.baz + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(bar?.hashValue) + hasher.combine(baz?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Return.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Return.swift new file mode 100644 index 000000000000..f517ed557148 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Return.swift @@ -0,0 +1,48 @@ +// +// Return.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Return") +public typealias Return = PetstoreClient.Return + +extension PetstoreClient { + +/** Model for testing reserved words */ +public final class Return: Codable, Hashable { + + public var _return: Int? + + public init(_return: Int? = nil) { + self._return = _return + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case _return = "return" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_return, forKey: ._return) + } + + public static func == (lhs: Return, rhs: Return) -> Bool { + lhs._return == rhs._return + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(_return?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/SpecialModelName.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/SpecialModelName.swift new file mode 100644 index 000000000000..3b5cc1853195 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/SpecialModelName.swift @@ -0,0 +1,47 @@ +// +// SpecialModelName.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.SpecialModelName") +public typealias SpecialModelName = PetstoreClient.SpecialModelName + +extension PetstoreClient { + +public final class SpecialModelName: Codable, Hashable { + + public var specialPropertyName: Int64? + + public init(specialPropertyName: Int64? = nil) { + self.specialPropertyName = specialPropertyName + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case specialPropertyName = "$special[property.name]" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) + } + + public static func == (lhs: SpecialModelName, rhs: SpecialModelName) -> Bool { + lhs.specialPropertyName == rhs.specialPropertyName + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(specialPropertyName?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/StringBooleanMap.swift new file mode 100644 index 000000000000..1449e89190f2 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/StringBooleanMap.swift @@ -0,0 +1,65 @@ +// +// StringBooleanMap.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.StringBooleanMap") +public typealias StringBooleanMap = PetstoreClient.StringBooleanMap + +extension PetstoreClient { + +public final class StringBooleanMap: Codable, Hashable { + + + public enum CodingKeys: CodingKey, CaseIterable { + } + + public var additionalProperties: [String: Bool] = [:] + + public subscript(key: String) -> Bool? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + var nonAdditionalPropertyKeys = Set() + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + } + + public static func == (lhs: StringBooleanMap, rhs: StringBooleanMap) -> Bool { + lhs.additionalProperties == rhs.additionalProperties + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(additionalProperties.hashValue) + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Tag.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Tag.swift new file mode 100644 index 000000000000..cfd84044fe2e --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Tag.swift @@ -0,0 +1,53 @@ +// +// Tag.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Tag") +public typealias Tag = PetstoreClient.Tag + +extension PetstoreClient { + +public final class Tag: Codable, Hashable { + + public var id: Int64? + public var name: String? + + public init(id: Int64? = nil, name: String? = nil) { + self.id = id + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(name, forKey: .name) + } + + public static func == (lhs: Tag, rhs: Tag) -> Bool { + lhs.id == rhs.id && + lhs.name == rhs.name + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(id?.hashValue) + hasher.combine(name?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/TypeHolderDefault.swift new file mode 100644 index 000000000000..82595deb5009 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/TypeHolderDefault.swift @@ -0,0 +1,71 @@ +// +// TypeHolderDefault.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.TypeHolderDefault") +public typealias TypeHolderDefault = PetstoreClient.TypeHolderDefault + +extension PetstoreClient { + +public final class TypeHolderDefault: Codable, Hashable { + + public var stringItem: String = "what" + public var numberItem: Double + public var integerItem: Int + public var boolItem: Bool = true + public var arrayItem: [Int] + + public init(stringItem: String = "what", numberItem: Double, integerItem: Int, boolItem: Bool = true, arrayItem: [Int]) { + self.stringItem = stringItem + self.numberItem = numberItem + self.integerItem = integerItem + self.boolItem = boolItem + self.arrayItem = arrayItem + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case stringItem = "string_item" + case numberItem = "number_item" + case integerItem = "integer_item" + case boolItem = "bool_item" + case arrayItem = "array_item" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } + + public static func == (lhs: TypeHolderDefault, rhs: TypeHolderDefault) -> Bool { + lhs.stringItem == rhs.stringItem && + lhs.numberItem == rhs.numberItem && + lhs.integerItem == rhs.integerItem && + lhs.boolItem == rhs.boolItem && + lhs.arrayItem == rhs.arrayItem + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(stringItem.hashValue) + hasher.combine(numberItem.hashValue) + hasher.combine(integerItem.hashValue) + hasher.combine(boolItem.hashValue) + hasher.combine(arrayItem.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/TypeHolderExample.swift new file mode 100644 index 000000000000..9509c507b87b --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/TypeHolderExample.swift @@ -0,0 +1,71 @@ +// +// TypeHolderExample.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.TypeHolderExample") +public typealias TypeHolderExample = PetstoreClient.TypeHolderExample + +extension PetstoreClient { + +public final class TypeHolderExample: Codable, Hashable { + + public var stringItem: String + public var numberItem: Double + public var integerItem: Int + public var boolItem: Bool + public var arrayItem: [Int] + + public init(stringItem: String, numberItem: Double, integerItem: Int, boolItem: Bool, arrayItem: [Int]) { + self.stringItem = stringItem + self.numberItem = numberItem + self.integerItem = integerItem + self.boolItem = boolItem + self.arrayItem = arrayItem + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case stringItem = "string_item" + case numberItem = "number_item" + case integerItem = "integer_item" + case boolItem = "bool_item" + case arrayItem = "array_item" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } + + public static func == (lhs: TypeHolderExample, rhs: TypeHolderExample) -> Bool { + lhs.stringItem == rhs.stringItem && + lhs.numberItem == rhs.numberItem && + lhs.integerItem == rhs.integerItem && + lhs.boolItem == rhs.boolItem && + lhs.arrayItem == rhs.arrayItem + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(stringItem.hashValue) + hasher.combine(numberItem.hashValue) + hasher.combine(integerItem.hashValue) + hasher.combine(boolItem.hashValue) + hasher.combine(arrayItem.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/User.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/User.swift new file mode 100644 index 000000000000..63b13180dcd2 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/User.swift @@ -0,0 +1,90 @@ +// +// User.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.User") +public typealias User = PetstoreClient.User + +extension PetstoreClient { + +public final class User: Codable, Hashable { + + public var id: Int64? + public var username: String? + public var firstName: String? + public var lastName: String? + public var email: String? + public var password: String? + public var phone: String? + /** User Status */ + public var userStatus: Int? + + public init(id: Int64? = nil, username: String? = nil, firstName: String? = nil, lastName: String? = nil, email: String? = nil, password: String? = nil, phone: String? = nil, userStatus: Int? = nil) { + self.id = id + self.username = username + self.firstName = firstName + self.lastName = lastName + self.email = email + self.password = password + self.phone = phone + self.userStatus = userStatus + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case username + case firstName + case lastName + case email + case password + case phone + case userStatus + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(username, forKey: .username) + try container.encodeIfPresent(firstName, forKey: .firstName) + try container.encodeIfPresent(lastName, forKey: .lastName) + try container.encodeIfPresent(email, forKey: .email) + try container.encodeIfPresent(password, forKey: .password) + try container.encodeIfPresent(phone, forKey: .phone) + try container.encodeIfPresent(userStatus, forKey: .userStatus) + } + + public static func == (lhs: User, rhs: User) -> Bool { + lhs.id == rhs.id && + lhs.username == rhs.username && + lhs.firstName == rhs.firstName && + lhs.lastName == rhs.lastName && + lhs.email == rhs.email && + lhs.password == rhs.password && + lhs.phone == rhs.phone && + lhs.userStatus == rhs.userStatus + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(id?.hashValue) + hasher.combine(username?.hashValue) + hasher.combine(firstName?.hashValue) + hasher.combine(lastName?.hashValue) + hasher.combine(email?.hashValue) + hasher.combine(password?.hashValue) + hasher.combine(phone?.hashValue) + hasher.combine(userStatus?.hashValue) + + } +} +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/OpenISO8601DateFormatter.swift new file mode 100644 index 000000000000..e06208074cd9 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/OpenISO8601DateFormatter.swift @@ -0,0 +1,44 @@ +// +// OpenISO8601DateFormatter.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +// https://stackoverflow.com/a/50281094/976628 +public class OpenISO8601DateFormatter: DateFormatter { + static let withoutSeconds: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" + return formatter + }() + + private func setup() { + calendar = Calendar(identifier: .iso8601) + locale = Locale(identifier: "en_US_POSIX") + timeZone = TimeZone(secondsFromGMT: 0) + dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + } + + override init() { + super.init() + setup() + } + + required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + setup() + } + + override public func date(from string: String) -> Date? { + if let result = super.date(from: string) { + return result + } + return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/SynchronizedDictionary.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/SynchronizedDictionary.swift new file mode 100644 index 000000000000..acf7ff4031bd --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/SynchronizedDictionary.swift @@ -0,0 +1,36 @@ +// SynchronizedDictionary.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +internal struct SynchronizedDictionary { + + private var dictionary = [K: V]() + private let queue = DispatchQueue( + label: "SynchronizedDictionary", + qos: DispatchQoS.userInitiated, + attributes: [DispatchQueue.Attributes.concurrent], + autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, + target: nil + ) + + internal subscript(key: K) -> V? { + get { + var value: V? + + queue.sync { + value = self.dictionary[key] + } + + return value + } + set { + queue.sync(flags: DispatchWorkItemFlags.barrier) { + self.dictionary[key] = newValue + } + } + } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift new file mode 100644 index 000000000000..774c0427eaa2 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift @@ -0,0 +1,649 @@ +// URLSessionImplementations.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if !os(macOS) +import MobileCoreServices +#endif + +class URLSessionRequestBuilderFactory: RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type { + return URLSessionRequestBuilder.self + } + + func getBuilder() -> RequestBuilder.Type { + return URLSessionDecodableRequestBuilder.self + } +} + +// Store the URLSession to retain its reference +private var urlSessionStore = SynchronizedDictionary() + +open class URLSessionRequestBuilder: RequestBuilder { + + /** + May be assigned if you want to control the authentication challenges. + */ + public var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /** + May be assigned if you want to do any of those things: + - control the task completion + - intercept and handle errors like authorization + - retry the request. + */ + @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") + public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? + + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + } + + /** + May be overridden by a subclass if you want to control the URLSession + configuration. + */ + open func createURLSession() -> URLSession { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = buildHeaders() + let sessionDelegate = SessionDelegate() + sessionDelegate.credential = credential + sessionDelegate.taskDidReceiveChallenge = taskDidReceiveChallenge + return URLSession(configuration: configuration, delegate: sessionDelegate, delegateQueue: nil) + } + + /** + May be overridden by a subclass if you want to control the Content-Type + that is given to an uploaded form part. + + Return nil to use the default behavior (inferring the Content-Type from + the file extension). Return the desired Content-Type otherwise. + */ + open func contentTypeForFormPart(fileURL: URL) -> String? { + return nil + } + + /** + May be overridden by a subclass if you want to control the URLRequest + configuration (e.g. to override the cache policy). + */ + open func createURLRequest(urlSession: URLSession, method: HTTPMethod, encoding: ParameterEncoding, headers: [String: String]) throws -> URLRequest { + + guard let url = URL(string: URLString) else { + throw DownloadException.requestMissingURL + } + + var originalRequest = URLRequest(url: url) + + originalRequest.httpMethod = method.rawValue + + headers.forEach { key, value in + originalRequest.setValue(value, forHTTPHeaderField: key) + } + + buildHeaders().forEach { key, value in + originalRequest.setValue(value, forHTTPHeaderField: key) + } + + let modifiedRequest = try encoding.encode(originalRequest, with: parameters) + + return modifiedRequest + } + + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + let urlSessionId = UUID().uuidString + // Create a new manager for each request to customize its request header + let urlSession = createURLSession() + urlSessionStore[urlSessionId] = urlSession + + guard let xMethod = HTTPMethod(rawValue: method) else { + fatalError("Unsuported Http method - \(method)") + } + + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = FormURLEncoding() + } else { + fatalError("Unsuported Media Type - \(contentType)") + } + } + + let cleanupRequest = { + urlSessionStore[urlSessionId]?.finishTasksAndInvalidate() + urlSessionStore[urlSessionId] = nil + } + + do { + let request = try createURLRequest(urlSession: urlSession, method: xMethod, encoding: encoding, headers: headers) + + let dataTask = urlSession.dataTask(with: request) { data, response, error in + + if let taskCompletionShouldRetry = self.taskCompletionShouldRetry { + + taskCompletionShouldRetry(data, response, error) { shouldRetry in + + if shouldRetry { + cleanupRequest() + self.execute(apiResponseQueue, completion) + } else { + apiResponseQueue.async { + self.processRequestResponse(urlRequest: request, data: data, response: response, error: error, completion: completion) + cleanupRequest() + } + } + } + } else { + apiResponseQueue.async { + self.processRequestResponse(urlRequest: request, data: data, response: response, error: error, completion: completion) + cleanupRequest() + } + } + } + + if #available(iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0, *) { + onProgressReady?(dataTask.progress) + } + + dataTask.resume() + + } catch { + apiResponseQueue.async { + cleanupRequest() + completion(.failure(ErrorResponse.error(415, nil, nil, error))) + } + } + } + + fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + + if let error = error { + completion(.failure(ErrorResponse.error(-1, data, response, error))) + return + } + + guard let httpResponse = response as? HTTPURLResponse else { + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) + return + } + + guard httpResponse.isStatusCodeSuccessful else { + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + return + } + + switch T.self { + case is String.Type: + + let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" + + completion(.success(Response(response: httpResponse, body: body as? T))) + + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + + case is Void.Type: + + completion(.success(Response(response: httpResponse, body: nil))) + + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + + default: + + completion(.success(Response(response: httpResponse, body: data as? T))) + } + + } + + open func buildHeaders() -> [String: String] { + var httpHeaders: [String: String] = [:] + for (key, value) in headers { + httpHeaders[key] = value + } + for (key, value) in PetstoreClient.customHeaders { + httpHeaders[key] = value + } + return httpHeaders + } + + fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? { + + guard let contentDisposition = contentDisposition else { + return nil + } + + let items = contentDisposition.components(separatedBy: ";") + + var filename: String? + + for contentItem in items { + + let filenameKey = "filename=" + guard let range = contentItem.range(of: filenameKey) else { + break + } + + filename = contentItem + return filename? + .replacingCharacters(in: range, with: "") + .replacingOccurrences(of: "\"", with: "") + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + return filename + + } + + fileprivate func getPath(from url: URL) throws -> String { + + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + throw DownloadException.requestMissingPath + } + + if path.hasPrefix("/") { + path.remove(at: path.startIndex) + } + + return path + + } + + fileprivate func getURL(from urlRequest: URLRequest) throws -> URL { + + guard let url = urlRequest.url else { + throw DownloadException.requestMissingURL + } + + return url + } + +} + +open class URLSessionDecodableRequestBuilder: URLSessionRequestBuilder { + override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + + if let error = error { + completion(.failure(ErrorResponse.error(-1, data, response, error))) + return + } + + guard let httpResponse = response as? HTTPURLResponse else { + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) + return + } + + guard httpResponse.isStatusCodeSuccessful else { + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + return + } + + switch T.self { + case is String.Type: + + let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" + + completion(.success(Response(response: httpResponse, body: body as? T))) + + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + + case is Void.Type: + + completion(.success(Response(response: httpResponse, body: nil))) + + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + + default: + + guard let data = data, !data.isEmpty else { + completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) + return + } + + let decodeResult = CodableHelper.decode(T.self, from: data) + + switch decodeResult { + case let .success(decodableObj): + completion(.success(Response(response: httpResponse, body: decodableObj))) + case let .failure(error): + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, error))) + } + } + } +} + +private class SessionDelegate: NSObject, URLSessionDelegate, URLSessionDataDelegate { + + var credential: URLCredential? + + var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { + + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + + var credential: URLCredential? + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) + } else { + if challenge.previousFailureCount > 0 { + disposition = .rejectProtectionSpace + } else { + credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) + + if credential != nil { + disposition = .useCredential + } + } + } + + completionHandler(disposition, credential) + } +} + +public enum HTTPMethod: String { + case options = "OPTIONS" + case get = "GET" + case head = "HEAD" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" + case trace = "TRACE" + case connect = "CONNECT" +} + +public protocol ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest +} + +private class URLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + guard let parameters = parameters else { return urlRequest } + + guard let url = urlRequest.url else { + throw DownloadException.requestMissingURL + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + urlComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters) + urlRequest.url = urlComponents.url + } + + return urlRequest + } +} + +private class FormDataEncoding: ParameterEncoding { + + let contentTypeForFormPart: (_ fileURL: URL) -> String? + + init(contentTypeForFormPart: @escaping (_ fileURL: URL) -> String?) { + self.contentTypeForFormPart = contentTypeForFormPart + } + + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + guard let parameters = parameters, !parameters.isEmpty else { + return urlRequest + } + + let boundary = "Boundary-\(UUID().uuidString)" + + urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") + + for (key, value) in parameters { + switch value { + case let fileURL as URL: + + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) + + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") + } + } + + var body = urlRequest.httpBody.orEmpty + + body.append("\r\n--\(boundary)--\r\n") + + urlRequest.httpBody = body + + return urlRequest + } + + private func configureFileUploadRequest(urlRequest: URLRequest, boundary: String, name: String, fileURL: URL) throws -> URLRequest { + + var urlRequest = urlRequest + + var body = urlRequest.httpBody.orEmpty + + let fileData = try Data(contentsOf: fileURL) + + let mimetype = contentTypeForFormPart(fileURL) ?? mimeType(for: fileURL) + + let fileName = fileURL.lastPathComponent + + // If we already added something then we need an additional newline. + if body.count > 0 { + body.append("\r\n") + } + + // Value boundary. + body.append("--\(boundary)\r\n") + + // Value headers. + body.append("Content-Disposition: form-data; name=\"\(name)\"; filename=\"\(fileName)\"\r\n") + body.append("Content-Type: \(mimetype)\r\n") + + // Separate headers and body. + body.append("\r\n") + + // The value data. + body.append(fileData) + + urlRequest.httpBody = body + + return urlRequest + } + + private func configureDataUploadRequest(urlRequest: URLRequest, boundary: String, name: String, data: Data) -> URLRequest { + + var urlRequest = urlRequest + + var body = urlRequest.httpBody.orEmpty + + // If we already added something then we need an additional newline. + if body.count > 0 { + body.append("\r\n") + } + + // Value boundary. + body.append("--\(boundary)\r\n") + + // Value headers. + body.append("Content-Disposition: form-data; name=\"\(name)\"\r\n") + + // Separate headers and body. + body.append("\r\n") + + // The value data. + body.append(data) + + urlRequest.httpBody = body + + return urlRequest + + } + + func mimeType(for url: URL) -> String { + let pathExtension = url.pathExtension + + if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as NSString, nil)?.takeRetainedValue() { + if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() { + return mimetype as String + } + } + return "application/octet-stream" + } + +} + +private class FormURLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + var requestBodyComponents = URLComponents() + requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + + return urlRequest + } +} + +private extension Data { + /// Append string to Data + /// + /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8. + /// + /// - parameter string: The string to be added to the `Data`. + + mutating func append(_ string: String) { + if let data = string.data(using: .utf8) { + append(data) + } + } +} + +private extension Optional where Wrapped == Data { + var orEmpty: Data { + self ?? Data() + } +} + +extension JSONDataEncoding: ParameterEncoding {} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/Podfile b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/Podfile deleted file mode 100644 index 77432f9eee92..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/Podfile +++ /dev/null @@ -1,13 +0,0 @@ -platform :ios, '9.0' - -source 'https://cdn.cocoapods.org/' - -use_frameworks! - -target 'SwaggerClient' do - pod "PetstoreClient", :path => "../" - - target 'SwaggerClientTests' do - inherit! :search_paths - end -end diff --git a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/Podfile.lock deleted file mode 100644 index a621fdeec885..000000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/Podfile.lock +++ /dev/null @@ -1,16 +0,0 @@ -PODS: - - PetstoreClient (1.0.0) - -DEPENDENCIES: - - PetstoreClient (from `../`) - -EXTERNAL SOURCES: - PetstoreClient: - :path: "../" - -SPEC CHECKSUMS: - PetstoreClient: b26b235a3ece06dbf1da99dc67e48aa201659f21 - -PODFILE CHECKSUM: 509bec696cc1d8641751b52e4fe4bef04ac4542c - -COCOAPODS: 1.9.0 diff --git a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 9c371f929dbf..aab810debd09 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -3,12 +3,11 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 52; objects = { /* Begin PBXBuildFile section */ 1A501F48219C3DC600F372F6 /* DateFormatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A501F47219C3DC600F372F6 /* DateFormatTests.swift */; }; - 23B2E76564651097BE2FE501 /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7F98CC8B18E5FA9213F6A68D /* Pods_SwaggerClient.framework */; }; 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */; }; 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB961C692C6300B96B06 /* ViewController.swift */; }; 6D4EFB9A1C692C6300B96B06 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB981C692C6300B96B06 /* Main.storyboard */; }; @@ -18,9 +17,9 @@ 6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */; }; 6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */; }; A5465867259E09C600C3929B /* BearerDecodableRequestBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5465866259E09C600C3929B /* BearerDecodableRequestBuilder.swift */; }; + A5782C772664FBA800CAA106 /* PetstoreClient in Frameworks */ = {isa = PBXBuildFile; productRef = A5782C762664FBA800CAA106 /* PetstoreClient */; }; A5EA12642419439700E30FC3 /* FileUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA12622419439700E30FC3 /* FileUtils.swift */; }; A5EA12652419439700E30FC3 /* UIImage+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA12632419439700E30FC3 /* UIImage+Extras.swift */; }; - FB5CCC7EFA680BB2746B695B /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 83FDC034BBA2A07AE9975250 /* Pods_SwaggerClientTests.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -34,7 +33,6 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 081E9B893DEB1589CB807EA7 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; 1A501F47219C3DC600F372F6 /* DateFormatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateFormatTests.swift; sourceTree = ""; }; 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwaggerClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -48,15 +46,9 @@ 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = ""; }; 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = ""; }; 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; - 7F98CC8B18E5FA9213F6A68D /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 83FDC034BBA2A07AE9975250 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A5465866259E09C600C3929B /* BearerDecodableRequestBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BearerDecodableRequestBuilder.swift; sourceTree = ""; }; A5EA12622419439700E30FC3 /* FileUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileUtils.swift; sourceTree = ""; }; A5EA12632419439700E30FC3 /* UIImage+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIImage+Extras.swift"; sourceTree = ""; }; - ACB80AC61FA8D8916D4559AA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; - C07EC0A94AA0F86D60668B32 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - E43FC34A9681D65ED44EE914 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; - ED8576754DBB828CAE63EA87 /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -64,7 +56,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 23B2E76564651097BE2FE501 /* Pods_SwaggerClient.framework in Frameworks */, + A5782C772664FBA800CAA106 /* PetstoreClient in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -72,30 +64,15 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - FB5CCC7EFA680BB2746B695B /* Pods_SwaggerClientTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 203D4495376E4EB72474B091 /* Pods */ = { - isa = PBXGroup; - children = ( - 081E9B893DEB1589CB807EA7 /* Pods-SwaggerClient.debug.xcconfig */, - ACB80AC61FA8D8916D4559AA /* Pods-SwaggerClient.release.xcconfig */, - E43FC34A9681D65ED44EE914 /* Pods-SwaggerClientTests.debug.xcconfig */, - ED8576754DBB828CAE63EA87 /* Pods-SwaggerClientTests.release.xcconfig */, - ); - name = Pods; - sourceTree = ""; - }; 3FABC56EC0BA84CBF4F99564 /* Frameworks */ = { isa = PBXGroup; children = ( - C07EC0A94AA0F86D60668B32 /* Pods.framework */, - 7F98CC8B18E5FA9213F6A68D /* Pods_SwaggerClient.framework */, - 83FDC034BBA2A07AE9975250 /* Pods_SwaggerClientTests.framework */, ); name = Frameworks; sourceTree = ""; @@ -107,7 +84,6 @@ 6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */, 6D4EFB921C692C6300B96B06 /* Products */, 3FABC56EC0BA84CBF4F99564 /* Frameworks */, - 203D4495376E4EB72474B091 /* Pods */, ); sourceTree = ""; }; @@ -155,17 +131,18 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 5BC9214E8D9BA5A427A3775B /* [CP] Check Pods Manifest.lock */, 6D4EFB8D1C692C6300B96B06 /* Sources */, 6D4EFB8E1C692C6300B96B06 /* Frameworks */, 6D4EFB8F1C692C6300B96B06 /* Resources */, - FDCA0F14611FE114BFEBA8BB /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( ); name = SwaggerClient; + packageProductDependencies = ( + A5782C762664FBA800CAA106 /* PetstoreClient */, + ); productName = SwaggerClient; productReference = 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */; productType = "com.apple.product-type.application"; @@ -174,7 +151,6 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - EEDC5E683F9569976B7C1192 /* [CP] Check Pods Manifest.lock */, 6D4EFBA11C692C6300B96B06 /* Sources */, 6D4EFBA21C692C6300B96B06 /* Frameworks */, 6D4EFBA31C692C6300B96B06 /* Resources */, @@ -249,71 +225,6 @@ }; /* End PBXResourcesBuildPhase section */ -/* Begin PBXShellScriptBuildPhase section */ - 5BC9214E8D9BA5A427A3775B /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClient-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - EEDC5E683F9569976B7C1192 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClientTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - FDCA0F14611FE114BFEBA8BB /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/PetstoreClient/PetstoreClient.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PetstoreClient.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - /* Begin PBXSourcesBuildPhase section */ 6D4EFB8D1C692C6300B96B06 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -478,11 +389,13 @@ }; 6D4EFBAF1C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 081E9B893DEB1589CB807EA7 /* Pods-SwaggerClient.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -491,11 +404,13 @@ }; 6D4EFBB01C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = ACB80AC61FA8D8916D4559AA /* Pods-SwaggerClient.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -504,11 +419,14 @@ }; 6D4EFBB21C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = E43FC34A9681D65ED44EE914 /* Pods-SwaggerClientTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -518,11 +436,14 @@ }; 6D4EFBB31C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = ED8576754DBB828CAE63EA87 /* Pods-SwaggerClientTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -561,6 +482,13 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCSwiftPackageProductDependency section */ + A5782C762664FBA800CAA106 /* PetstoreClient */ = { + isa = XCSwiftPackageProductDependency; + productName = PetstoreClient; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 6D4EFB891C692C6300B96B06 /* Project object */; } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata index 9b3fa18954f7..00ec9b53a7f1 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata +++ b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata @@ -2,9 +2,9 @@ + location = "group:.."> + location = "group:SwaggerClient.xcodeproj"> diff --git a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 000000000000..d384b276b4bc --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md index 543869c0d2e0..553a46281aa0 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md @@ -379,7 +379,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) diff --git a/samples/client/petstore/swift5/urlsessionLibrary/project.yml b/samples/client/petstore/swift5/urlsessionLibrary/project.yml index 8e7102001b8d..af642519aeb4 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/project.yml +++ b/samples/client/petstore/swift5/urlsessionLibrary/project.yml @@ -4,11 +4,12 @@ targets: type: framework platform: iOS deploymentTarget: "9.0" - sources: [PetstoreClient] + sources: [Sources] info: path: ./Info.plist version: 1.0.0 settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - + dependencies: + - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/x-swift-hashable/.gitignore b/samples/client/petstore/swift5/x-swift-hashable/.gitignore new file mode 100644 index 000000000000..5e5d5cebcf47 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/.gitignore @@ -0,0 +1,63 @@ +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## Build generated +build/ +DerivedData + +## Various settings +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata + +## Other +*.xccheckout +*.moved-aside +*.xcuserstate +*.xcscmblueprint + +## Obj-C/Swift specific +*.hmap +*.ipa + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +.build/ + +# CocoaPods +# +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# +# Pods/ + +# Carthage +# +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build + +# fastlane +# +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md + +fastlane/report.xml +fastlane/screenshots diff --git a/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator-ignore b/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/FILES b/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/FILES new file mode 100644 index 000000000000..c81943baf2af --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/FILES @@ -0,0 +1,110 @@ +.gitignore +Cartfile +Package.swift +PetstoreClient.podspec +PetstoreClient/Classes/OpenAPIs/APIHelper.swift +PetstoreClient/Classes/OpenAPIs/APIs.swift +PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +PetstoreClient/Classes/OpenAPIs/CodableHelper.swift +PetstoreClient/Classes/OpenAPIs/Configuration.swift +PetstoreClient/Classes/OpenAPIs/Extensions.swift +PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift +PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift +PetstoreClient/Classes/OpenAPIs/Models.swift +PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +PetstoreClient/Classes/OpenAPIs/Models/Category.swift +PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +PetstoreClient/Classes/OpenAPIs/Models/Client.swift +PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +PetstoreClient/Classes/OpenAPIs/Models/File.swift +PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +PetstoreClient/Classes/OpenAPIs/Models/List.swift +PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +PetstoreClient/Classes/OpenAPIs/Models/Name.swift +PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +PetstoreClient/Classes/OpenAPIs/Models/Order.swift +PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +PetstoreClient/Classes/OpenAPIs/Models/Return.swift +PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +PetstoreClient/Classes/OpenAPIs/Models/User.swift +PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift +PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +README.md +docs/AdditionalPropertiesClass.md +docs/Animal.md +docs/AnimalFarm.md +docs/AnotherFakeAPI.md +docs/ApiResponse.md +docs/ArrayOfArrayOfNumberOnly.md +docs/ArrayOfNumberOnly.md +docs/ArrayTest.md +docs/Capitalization.md +docs/Cat.md +docs/CatAllOf.md +docs/Category.md +docs/ClassModel.md +docs/Client.md +docs/Dog.md +docs/DogAllOf.md +docs/EnumArrays.md +docs/EnumClass.md +docs/EnumTest.md +docs/FakeAPI.md +docs/FakeClassnameTags123API.md +docs/File.md +docs/FileSchemaTestClass.md +docs/FormatTest.md +docs/HasOnlyReadOnly.md +docs/List.md +docs/MapTest.md +docs/MixedPropertiesAndAdditionalPropertiesClass.md +docs/Model200Response.md +docs/Name.md +docs/NumberOnly.md +docs/Order.md +docs/OuterComposite.md +docs/OuterEnum.md +docs/Pet.md +docs/PetAPI.md +docs/ReadOnlyFirst.md +docs/Return.md +docs/SpecialModelName.md +docs/StoreAPI.md +docs/StringBooleanMap.md +docs/Tag.md +docs/TypeHolderDefault.md +docs/TypeHolderExample.md +docs/User.md +docs/UserAPI.md +git_push.sh +project.yml diff --git a/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/VERSION b/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/VERSION new file mode 100644 index 000000000000..6555596f9311 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/x-swift-hashable/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/x-swift-hashable/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000000..919434a6254f --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/Cartfile b/samples/client/petstore/swift5/x-swift-hashable/Cartfile new file mode 100644 index 000000000000..843f7adc7794 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/Cartfile @@ -0,0 +1,2 @@ + +github "Flight-School/AnyCodable" ~> 0.6.0 diff --git a/samples/client/petstore/swift5/x-swift-hashable/Package.resolved b/samples/client/petstore/swift5/x-swift-hashable/Package.resolved new file mode 100644 index 000000000000..85bb93ced12f --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "38b05fc9f86501ef8018aa90cf3d83bd97f74067", + "version": "0.4.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/Package.swift b/samples/client/petstore/swift5/x-swift-hashable/Package.swift new file mode 100644 index 000000000000..5cde507bdcf9 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/Package.swift @@ -0,0 +1,33 @@ +// swift-tools-version:5.1 + +import PackageDescription + +let package = Package( + name: "PetstoreClient", + platforms: [ + .iOS(.v9), + .macOS(.v10_11), + .tvOS(.v9), + .watchOS(.v3), + ], + products: [ + // Products define the executables and libraries produced by a package, and make them visible to other packages. + .library( + name: "PetstoreClient", + targets: ["PetstoreClient"] + ), + ], + dependencies: [ + // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.6.0")), + ], + targets: [ + // Targets are the basic building blocks of a package. A target can define a module or a test suite. + // Targets can depend on other targets in this package, and on products in packages which this package depends on. + .target( + name: "PetstoreClient", + dependencies: ["AnyCodable", ], + path: "PetstoreClient/Classes" + ), + ] +) diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient.podspec b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient.podspec new file mode 100644 index 000000000000..60f05891b241 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient.podspec @@ -0,0 +1,15 @@ +Pod::Spec.new do |s| + s.name = 'PetstoreClient' + s.ios.deployment_target = '9.0' + s.osx.deployment_target = '10.11' + s.tvos.deployment_target = '9.0' + s.watchos.deployment_target = '3.0' + s.version = '1.0.0' + s.source = { :git => 'git@github.com:OpenAPITools/openapi-generator.git', :tag => 'v1.0.0' } + s.authors = '' + s.license = 'Proprietary' + s.homepage = 'https://github.com/openapitools/openapi-generator' + s.summary = 'PetstoreClient' + s.source_files = 'PetstoreClient/Classes/**/*.swift' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.0' +end diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIHelper.swift new file mode 100644 index 000000000000..f7bb5274bd98 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -0,0 +1,71 @@ +// APIHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +public struct APIHelper { + public static func rejectNil(_ source: [String: Any?]) -> [String: Any]? { + let destination = source.reduce(into: [String: Any]()) { result, item in + if let value = item.value { + result[item.key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { + return source.reduce(into: [String: String]()) { result, item in + if let collection = item.value as? [Any?] { + result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + } else if let value: Any = item.value { + result[item.key] = "\(value)" + } + } + } + + public static func convertBoolToString(_ source: [String: Any]?) -> [String: Any]? { + guard let source = source else { + return nil + } + + return source.reduce(into: [String: Any]()) { result, item in + switch item.value { + case let x as Bool: + result[item.key] = x.description + default: + result[item.key] = item.value + } + } + } + + public static func mapValueToPathItem(_ source: Any) -> Any { + if let collection = source as? [Any?] { + return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + } + return source + } + + public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { + let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value as? [Any?] { + collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } else if let value = item.value { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs.swift new file mode 100644 index 000000000000..01bc6ff0d8d0 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -0,0 +1,65 @@ +// APIs.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { + public static var basePath = "http://petstore.swagger.io:80/v2" + public static var credential: URLCredential? + public static var customHeaders: [String: String] = [:] + public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory() + public static var apiResponseQueue: DispatchQueue = .main +} + +open class RequestBuilder { + var credential: URLCredential? + var headers: [String: String] + public let parameters: [String: Any]? + public let method: String + public let URLString: String + + /// Optional block to obtain a reference to the request's progress instance when available. + /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. + /// If you need to get the request's progress in older OS versions, please use Alamofire http client. + public var onProgressReady: ((Progress) -> Void)? + + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.headers = headers + + addHeaders(PetstoreClient.customHeaders) + } + + open func addHeaders(_ aHeaders: [String: String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + + public func addHeader(name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + open func addCredential() -> Self { + credential = PetstoreClient.credential + return self + } +} + +public protocol RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift similarity index 80% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 24b0015a270d..542fb6f69ba8 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -15,7 +15,7 @@ open class AnotherFakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -35,10 +35,10 @@ open class AnotherFakeAPI { */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -46,9 +46,9 @@ open class AnotherFakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift similarity index 85% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 58c4b8a093ce..9b75edc92ee6 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -14,7 +14,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -33,10 +33,10 @@ open class FakeAPI { */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -44,9 +44,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -55,7 +55,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -74,10 +74,10 @@ open class FakeAPI { */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -85,9 +85,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -96,7 +96,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -115,10 +115,10 @@ open class FakeAPI { */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -126,9 +126,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -137,7 +137,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -156,10 +156,10 @@ open class FakeAPI { */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -167,9 +167,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -178,7 +178,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -197,10 +197,10 @@ open class FakeAPI { */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -208,9 +208,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -220,7 +220,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -239,11 +239,11 @@ open class FakeAPI { */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) @@ -253,9 +253,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -265,7 +265,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -285,10 +285,10 @@ open class FakeAPI { */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -296,9 +296,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -321,7 +321,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -357,7 +357,7 @@ open class FakeAPI { */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), @@ -378,7 +378,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -386,9 +386,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -472,7 +472,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -499,7 +499,7 @@ open class FakeAPI { */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), @@ -508,8 +508,8 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), @@ -524,9 +524,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -541,7 +541,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -566,11 +566,11 @@ open class FakeAPI { */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), @@ -584,9 +584,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -596,7 +596,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -615,10 +615,10 @@ open class FakeAPI { */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -626,9 +626,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -639,7 +639,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -659,7 +659,7 @@ open class FakeAPI { */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), @@ -668,7 +668,7 @@ open class FakeAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -676,9 +676,9 @@ open class FakeAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift similarity index 81% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index fb3bb8ce00a7..fd7d845d3406 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -15,7 +15,7 @@ open class FakeClassnameTags123API { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -38,10 +38,10 @@ open class FakeClassnameTags123API { */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ open class FakeClassnameTags123API { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift similarity index 83% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 5cd3629127bf..d7d5bdfa2eaa 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -15,7 +15,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -37,10 +37,10 @@ open class PetAPI { */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -48,9 +48,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -61,7 +61,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -87,10 +87,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), @@ -98,9 +98,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -119,7 +119,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -142,11 +142,11 @@ open class PetAPI { */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) @@ -156,9 +156,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -169,7 +169,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -193,11 +193,11 @@ open class PetAPI { @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) @@ -207,9 +207,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -219,7 +219,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -245,10 +245,10 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -256,9 +256,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -268,7 +268,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -290,10 +290,10 @@ open class PetAPI { */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -301,9 +301,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -315,7 +315,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -342,7 +342,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), @@ -351,7 +351,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", @@ -359,9 +359,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -373,7 +373,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -400,7 +400,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), @@ -409,7 +409,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -417,9 +417,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -431,7 +431,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -458,7 +458,7 @@ open class PetAPI { let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), @@ -467,7 +467,7 @@ open class PetAPI { let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", @@ -475,9 +475,9 @@ open class PetAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift similarity index 81% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 95adcc200ae0..c80d4286b536 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -15,7 +15,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -38,10 +38,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -49,9 +49,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -60,7 +60,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -82,10 +82,10 @@ open class StoreAPI { */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -93,9 +93,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -105,7 +105,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -128,10 +128,10 @@ open class StoreAPI { let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -139,9 +139,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -151,7 +151,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -170,10 +170,10 @@ open class StoreAPI { */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -181,9 +181,9 @@ open class StoreAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift similarity index 79% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index cfd30068a9db..542dc212bd1b 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -15,7 +15,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -35,10 +35,10 @@ open class UserAPI { */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { let path = "/user" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -46,9 +46,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -58,7 +58,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -77,10 +77,10 @@ open class UserAPI { */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -88,9 +88,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -100,7 +100,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -119,10 +119,10 @@ open class UserAPI { */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -130,9 +130,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -142,7 +142,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -165,10 +165,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -176,9 +176,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -188,7 +188,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -210,10 +210,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -221,9 +221,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -234,7 +234,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -255,11 +255,11 @@ open class UserAPI { */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - var url = URLComponents(string: URLString) - url?.queryItems = APIHelper.mapValuesToQueryItems([ + var urlComponents = URLComponents(string: URLString) + urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) @@ -270,9 +270,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -281,7 +281,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -299,10 +299,10 @@ open class UserAPI { */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -310,9 +310,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** @@ -323,7 +323,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -347,10 +347,10 @@ open class UserAPI { let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path + let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let url = URLComponents(string: URLString) + let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : @@ -358,9 +358,9 @@ open class UserAPI { let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let requestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, headers: headerParameters) + return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift new file mode 100644 index 000000000000..09c82e53e132 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift @@ -0,0 +1,49 @@ +// +// CodableHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +open class CodableHelper { + private static var customDateFormatter: DateFormatter? + private static var defaultDateFormatter: DateFormatter = OpenISO8601DateFormatter() + + private static var customJSONDecoder: JSONDecoder? + private static var defaultJSONDecoder: JSONDecoder = { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .formatted(CodableHelper.dateFormatter) + return decoder + }() + + private static var customJSONEncoder: JSONEncoder? + private static var defaultJSONEncoder: JSONEncoder = { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .formatted(CodableHelper.dateFormatter) + encoder.outputFormatting = .prettyPrinted + return encoder + }() + + public static var dateFormatter: DateFormatter { + get { return customDateFormatter ?? defaultDateFormatter } + set { customDateFormatter = newValue } + } + public static var jsonDecoder: JSONDecoder { + get { return customJSONDecoder ?? defaultJSONDecoder } + set { customJSONDecoder = newValue } + } + public static var jsonEncoder: JSONEncoder { + get { return customJSONEncoder ?? defaultJSONEncoder } + set { customJSONEncoder = newValue } + } + + open class func decode(_ type: T.Type, from data: Data) -> Swift.Result where T: Decodable { + return Swift.Result { try jsonDecoder.decode(type, from: data) } + } + + open class func encode(_ value: T) -> Swift.Result where T: Encodable { + return Swift.Result { try jsonEncoder.encode(value) } + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Configuration.swift new file mode 100644 index 000000000000..18edabbed782 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -0,0 +1,14 @@ +// Configuration.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +open class Configuration { + // This value is used to configure the date formatter that is used to serialize dates into JSON format. + // You must set it prior to encoding any dates, and it will only be read once. + @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") + public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift new file mode 100644 index 000000000000..e23035dde30e --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -0,0 +1,188 @@ +// Extensions.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +extension Bool: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Float: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Int: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Int32: JSONEncodable { + func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } +} + +extension Int64: JSONEncodable { + func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } +} + +extension Double: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension String: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension RawRepresentable where RawValue: JSONEncodable { + func encodeToJSON() -> Any { return self.rawValue as Any } +} + +private func encodeIfPossible(_ object: T) -> Any { + if let encodableObject = object as? JSONEncodable { + return encodableObject.encodeToJSON() + } else { + return object as Any + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> Any { + return self.map(encodeIfPossible) + } +} + +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> Any { + var dictionary = [AnyHashable: Any]() + for (key, value) in self { + dictionary[key] = encodeIfPossible(value) + } + return dictionary as Any + } +} + +extension Data: JSONEncodable { + func encodeToJSON() -> Any { + return self.base64EncodedString(options: Data.Base64EncodingOptions()) + } +} + +extension Date: JSONEncodable { + func encodeToJSON() -> Any { + return CodableHelper.dateFormatter.string(from: self) as Any + } +} + +extension URL: JSONEncodable { + func encodeToJSON() -> Any { + return self + } +} + +extension UUID: JSONEncodable { + func encodeToJSON() -> Any { + return self.uuidString + } +} + +extension String: CodingKey { + + public var stringValue: String { + return self + } + + public init?(stringValue: String) { + self.init(stringLiteral: stringValue) + } + + public var intValue: Int? { + return nil + } + + public init?(intValue: Int) { + return nil + } + +} + +extension KeyedEncodingContainerProtocol { + + public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable { + var arrayContainer = nestedUnkeyedContainer(forKey: key) + try arrayContainer.encode(contentsOf: values) + } + + public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable { + if let values = values { + try encodeArray(values, forKey: key) + } + } + + public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable { + for (key, value) in pairs { + try encode(value, forKey: key) + } + } + + public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable { + if let pairs = pairs { + try encodeMap(pairs) + } + } + +} + +extension KeyedDecodingContainerProtocol { + + public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable { + var tmpArray = [T]() + + var nestedContainer = try nestedUnkeyedContainer(forKey: key) + while !nestedContainer.isAtEnd { + let arrayValue = try nestedContainer.decode(T.self) + tmpArray.append(arrayValue) + } + + return tmpArray + } + + public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable { + var tmpArray: [T]? + + if contains(key) { + tmpArray = try decodeArray(T.self, forKey: key) + } + + return tmpArray + } + + public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable { + var map: [Self.Key: T] = [:] + + for key in allKeys { + if !excludedKeys.contains(key) { + let value = try decode(T.self, forKey: key) + map[key] = value + } + } + + return map + } + +} + +extension HTTPURLResponse { + var isStatusCodeSuccessful: Bool { + return Array(200 ..< 300).contains(statusCode) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift new file mode 100644 index 000000000000..b79e9f5e64d5 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift @@ -0,0 +1,53 @@ +// +// JSONDataEncoding.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +public struct JSONDataEncoding { + + // MARK: Properties + + private static let jsonDataKey = "jsonData" + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. This should have a single key/value + /// pair with "jsonData" as the key and a Data object as the value. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) -> URLRequest { + var urlRequest = urlRequest + + guard let jsonData = parameters?[JSONDataEncoding.jsonDataKey] as? Data, !jsonData.isEmpty else { + return urlRequest + } + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = jsonData + + return urlRequest + } + + public static func encodingParameters(jsonData: Data?) -> [String: Any]? { + var returnedParams: [String: Any]? + if let jsonData = jsonData, !jsonData.isEmpty { + var params: [String: Any] = [:] + params[jsonDataKey] = jsonData + returnedParams = params + } + return returnedParams + } + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift new file mode 100644 index 000000000000..02f78ffb4705 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift @@ -0,0 +1,45 @@ +// +// JSONEncodingHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +open class JSONEncodingHelper { + + open class func encodingParameters(forEncodableObject encodableObj: T?) -> [String: Any]? { + var params: [String: Any]? + + // Encode the Encodable object + if let encodableObj = encodableObj { + let encodeResult = CodableHelper.encode(encodableObj) + do { + let data = try encodeResult.get() + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error.localizedDescription) + } + } + + return params + } + + open class func encodingParameters(forEncodableObject encodableObj: Any?) -> [String: Any]? { + var params: [String: Any]? + + if let encodableObj = encodableObj { + do { + let data = try JSONSerialization.data(withJSONObject: encodableObj, options: .prettyPrinted) + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error.localizedDescription) + return nil + } + } + + return params + } + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift new file mode 100644 index 000000000000..96e26a20f7d6 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -0,0 +1,54 @@ +// Models.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +protocol JSONEncodable { + func encodeToJSON() -> Any +} + +public enum ErrorResponse: Error { + case error(Int, Data?, URLResponse?, Error) +} + +public enum DownloadException: Error { + case responseDataMissing + case responseFailed + case requestMissing + case requestMissingPath + case requestMissingURL +} + +public enum DecodableRequestBuilderError: Error { + case emptyDataResponse + case nilHTTPResponse + case unsuccessfulHTTPStatusCode + case jsonDecoding(DecodingError) + case generalError(Error) +} + +open class Response { + public let statusCode: Int + public let header: [String: String] + public let body: T? + + public init(statusCode: Int, header: [String: String], body: T?) { + self.statusCode = statusCode + self.header = header + self.body = body + } + + public convenience init(response: HTTPURLResponse, body: T?) { + let rawHeader = response.allHeaderFields + var header = [String: String]() + for (key, value) in rawHeader { + if let key = key.base as? String, let value = value as? String { + header[key] = value + } + } + self.init(statusCode: response.statusCode, header: header, body: body) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesAnyType.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesAnyType.swift new file mode 100644 index 000000000000..7022f41580fb --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesAnyType.swift @@ -0,0 +1,57 @@ +// +// AdditionalPropertiesAnyType.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct AdditionalPropertiesAnyType: Codable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + public var additionalProperties: [String: AnyCodable] = [:] + + public subscript(key: String) -> AnyCodable? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: String.self) + + name = try container.decodeIfPresent(String.self, forKey: "name") + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + additionalProperties = try container.decodeMap(AnyCodable.self, excludedKeys: nonAdditionalPropertyKeys) + } + + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesArray.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesArray.swift new file mode 100644 index 000000000000..f0ac1d5c0e0f --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesArray.swift @@ -0,0 +1,57 @@ +// +// AdditionalPropertiesArray.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct AdditionalPropertiesArray: Codable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + public var additionalProperties: [String: [AnyCodable]] = [:] + + public subscript(key: String) -> [AnyCodable]? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: String.self) + + name = try container.decodeIfPresent(String.self, forKey: "name") + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + additionalProperties = try container.decodeMap([AnyCodable].self, excludedKeys: nonAdditionalPropertyKeys) + } + + +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesBoolean.swift similarity index 54% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesBoolean.swift index 77ab81f5f341..5879e1987646 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesBoolean.swift @@ -1,14 +1,23 @@ // -// StringBooleanMap.swift +// AdditionalPropertiesBoolean.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation +import AnyCodable -public struct StringBooleanMap: Codable, Hashable { +public struct AdditionalPropertiesBoolean: Codable { + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -27,10 +36,10 @@ public struct StringBooleanMap: Codable, Hashable { // Encodable protocol methods public func encode(to encoder: Encoder) throws { - - var container = encoder.container(keyedBy: String.self) - - try container.encodeMap(additionalProperties) + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) } // Decodable protocol methods @@ -38,8 +47,11 @@ public struct StringBooleanMap: Codable, Hashable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: String.self) + name = try container.decodeIfPresent(String.self, forKey: "name") var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } + } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift similarity index 58% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 733b7bc51594..9080af3e9608 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,8 +6,11 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif -public struct AdditionalPropertiesClass: Codable, Hashable { +public struct AdditionalPropertiesClass: Codable { public var mapString: [String: String]? public var mapMapString: [String: [String: String]]? @@ -22,4 +25,11 @@ public struct AdditionalPropertiesClass: Codable, Hashable { case mapMapString = "map_map_string" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapString, forKey: .mapString) + try container.encodeIfPresent(mapMapString, forKey: .mapMapString) + } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesInteger.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesInteger.swift new file mode 100644 index 000000000000..acfd7ae67bea --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesInteger.swift @@ -0,0 +1,57 @@ +// +// AdditionalPropertiesInteger.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct AdditionalPropertiesInteger: Codable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + public var additionalProperties: [String: Int] = [:] + + public subscript(key: String) -> Int? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: String.self) + + name = try container.decodeIfPresent(String.self, forKey: "name") + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + additionalProperties = try container.decodeMap(Int.self, excludedKeys: nonAdditionalPropertyKeys) + } + + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesNumber.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesNumber.swift new file mode 100644 index 000000000000..006997c5f6bf --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesNumber.swift @@ -0,0 +1,57 @@ +// +// AdditionalPropertiesNumber.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct AdditionalPropertiesNumber: Codable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + public var additionalProperties: [String: Double] = [:] + + public subscript(key: String) -> Double? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: String.self) + + name = try container.decodeIfPresent(String.self, forKey: "name") + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + additionalProperties = try container.decodeMap(Double.self, excludedKeys: nonAdditionalPropertyKeys) + } + + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesObject.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesObject.swift new file mode 100644 index 000000000000..adc288634476 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesObject.swift @@ -0,0 +1,57 @@ +// +// AdditionalPropertiesObject.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct AdditionalPropertiesObject: Codable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + public var additionalProperties: [String: [String: AnyCodable]] = [:] + + public subscript(key: String) -> [String: AnyCodable]? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: String.self) + + name = try container.decodeIfPresent(String.self, forKey: "name") + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + additionalProperties = try container.decodeMap([String: AnyCodable].self, excludedKeys: nonAdditionalPropertyKeys) + } + + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesString.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesString.swift new file mode 100644 index 000000000000..eba32fc30e11 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesString.swift @@ -0,0 +1,57 @@ +// +// AdditionalPropertiesString.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct AdditionalPropertiesString: Codable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + public var additionalProperties: [String: String] = [:] + + public subscript(key: String) -> String? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: String.self) + + name = try container.decodeIfPresent(String.self, forKey: "name") + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + additionalProperties = try container.decodeMap(String.self, excludedKeys: nonAdditionalPropertyKeys) + } + + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift new file mode 100644 index 000000000000..c26cc3b6a8d7 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -0,0 +1,35 @@ +// +// Animal.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Animal: Codable { + + public var className: String + public var color: String? = "red" + + public init(className: String, color: String? = "red") { + self.className = className + self.color = color + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift similarity index 75% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index e09b0e9efdc8..a0b09cb97615 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,5 +6,8 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift new file mode 100644 index 000000000000..7d81a45adbed --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -0,0 +1,39 @@ +// +// ApiResponse.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ApiResponse: Codable { + + public var code: Int? + public var type: String? + public var message: String? + + public init(code: Int? = nil, type: String? = nil, message: String? = nil) { + self.code = code + self.type = type + self.message = message + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case code + case type + case message + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(code, forKey: .code) + try container.encodeIfPresent(type, forKey: .type) + try container.encodeIfPresent(message, forKey: .message) + } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift similarity index 54% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 4710793fc9a6..d25598464fbe 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,8 +6,11 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif -public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { +public struct ArrayOfArrayOfNumberOnly: Codable { public var arrayArrayNumber: [[Double]]? @@ -19,4 +22,10 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { case arrayArrayNumber = "ArrayArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) + } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift similarity index 52% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index a41968d9b199..1d28ec680cc5 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,8 +6,11 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif -public struct ArrayOfNumberOnly: Codable, Hashable { +public struct ArrayOfNumberOnly: Codable { public var arrayNumber: [Double]? @@ -19,4 +22,10 @@ public struct ArrayOfNumberOnly: Codable, Hashable { case arrayNumber = "ArrayNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) + } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift similarity index 61% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index f442ea725451..6f1028d15077 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,8 +6,11 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif -public struct ArrayTest: Codable, Hashable { +public struct ArrayTest: Codable { public var arrayOfString: [String]? public var arrayArrayOfInteger: [[Int64]]? @@ -25,4 +28,12 @@ public struct ArrayTest: Codable, Hashable { case arrayArrayOfModel = "array_array_of_model" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayOfString, forKey: .arrayOfString) + try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) + try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) + } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/BigCat.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/BigCat.swift new file mode 100644 index 000000000000..842930f738d6 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/BigCat.swift @@ -0,0 +1,37 @@ +// +// BigCat.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct BigCat: Codable { + + public enum Kind: String, Codable, CaseIterable { + case lions = "lions" + case tigers = "tigers" + case leopards = "leopards" + case jaguars = "jaguars" + } + public var kind: Kind? + + public init(kind: Kind? = nil) { + self.kind = kind + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case kind + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(kind, forKey: .kind) + } + + + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/BigCatAllOf.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/BigCatAllOf.swift new file mode 100644 index 000000000000..b7c03fe88219 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/BigCatAllOf.swift @@ -0,0 +1,37 @@ +// +// BigCatAllOf.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct BigCatAllOf: Codable { + + public enum Kind: String, Codable, CaseIterable { + case lions = "lions" + case tigers = "tigers" + case leopards = "leopards" + case jaguars = "jaguars" + } + public var kind: Kind? + + public init(kind: Kind? = nil) { + self.kind = kind + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case kind + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(kind, forKey: .kind) + } + + + +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift similarity index 61% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index 44b50bbe0063..74ec197ecda2 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,8 +6,11 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif -public struct Capitalization: Codable, Hashable { +public struct Capitalization: Codable { public var smallCamel: String? public var capitalCamel: String? @@ -35,4 +38,15 @@ public struct Capitalization: Codable, Hashable { case ATT_NAME } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(smallCamel, forKey: .smallCamel) + try container.encodeIfPresent(capitalCamel, forKey: .capitalCamel) + try container.encodeIfPresent(smallSnake, forKey: .smallSnake) + try container.encodeIfPresent(capitalSnake, forKey: .capitalSnake) + try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) + try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) + } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift new file mode 100644 index 000000000000..8645c52b44f7 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -0,0 +1,39 @@ +// +// Cat.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Cat: Codable { + + public var className: String + public var color: String? = "red" + public var declawed: Bool? + + public init(className: String, color: String? = "red", declawed: Bool? = nil) { + self.className = className + self.color = color + self.declawed = declawed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(declawed, forKey: .declawed) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift new file mode 100644 index 000000000000..ed986d32cc6e --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -0,0 +1,31 @@ +// +// CatAllOf.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CatAllOf: Codable { + + public var declawed: Bool? + + public init(declawed: Bool? = nil) { + self.declawed = declawed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(declawed, forKey: .declawed) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Category.swift new file mode 100644 index 000000000000..398da60aa73b --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -0,0 +1,35 @@ +// +// Category.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Category: Codable, Hashable { + + public var id: Int64? + public var name: String? = "default-name" + + public init(id: Int64? = nil, name: String? = "default-name") { + self.id = id + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encode(name, forKey: .name) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift new file mode 100644 index 000000000000..c38e0db828f6 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -0,0 +1,32 @@ +// +// ClassModel.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Model for testing model with \"_class\" property */ +public struct ClassModel: Codable { + + public var _class: String? + + public init(_class: String? = nil) { + self._class = _class + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case _class + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_class, forKey: ._class) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Client.swift new file mode 100644 index 000000000000..170939891b6a --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -0,0 +1,31 @@ +// +// Client.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Client: Codable { + + public var client: String? + + public init(client: String? = nil) { + self.client = client + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case client + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(client, forKey: .client) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift new file mode 100644 index 000000000000..57ed7a20a3c1 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -0,0 +1,39 @@ +// +// Dog.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Dog: Codable { + + public var className: String + public var color: String? = "red" + public var breed: String? + + public init(className: String, color: String? = "red", breed: String? = nil) { + self.className = className + self.color = color + self.breed = breed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(breed, forKey: .breed) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift new file mode 100644 index 000000000000..5be7f8b08ca1 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -0,0 +1,31 @@ +// +// DogAllOf.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DogAllOf: Codable { + + public var breed: String? + + public init(breed: String? = nil) { + self.breed = breed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(breed, forKey: .breed) + } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift similarity index 66% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index aa13aa59f86a..67c2e914a2ec 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,8 +6,11 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif -public struct EnumArrays: Codable, Hashable { +public struct EnumArrays: Codable { public enum JustSymbol: String, Codable, CaseIterable { case greaterThanOrEqualTo = ">=" @@ -30,4 +33,11 @@ public struct EnumArrays: Codable, Hashable { case arrayEnum = "array_enum" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justSymbol, forKey: .justSymbol) + try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) + } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift similarity index 82% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index d4029d73f8af..6ea2895aee53 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift similarity index 71% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 8b62febdc959..a70a595f214b 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,8 +6,11 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif -public struct EnumTest: Codable, Hashable { +public struct EnumTest: Codable { public enum EnumString: String, Codable, CaseIterable { case upper = "UPPER" @@ -49,4 +52,14 @@ public struct EnumTest: Codable, Hashable { case outerEnum } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(enumString, forKey: .enumString) + try container.encode(enumStringRequired, forKey: .enumStringRequired) + try container.encodeIfPresent(enumInteger, forKey: .enumInteger) + try container.encodeIfPresent(enumNumber, forKey: .enumNumber) + try container.encodeIfPresent(outerEnum, forKey: .outerEnum) + } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/File.swift new file mode 100644 index 000000000000..69e3da33b3f6 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -0,0 +1,33 @@ +// +// File.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Must be named `File` for test. */ +public struct File: Codable { + + /** Test capitalization */ + public var sourceURI: String? + + public init(sourceURI: String? = nil) { + self.sourceURI = sourceURI + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case sourceURI + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(sourceURI, forKey: .sourceURI) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift new file mode 100644 index 000000000000..68387be7c4ca --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -0,0 +1,35 @@ +// +// FileSchemaTestClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct FileSchemaTestClass: Codable { + + public var file: File? + public var files: [File]? + + public init(file: File? = nil, files: [File]? = nil) { + self.file = file + self.files = files + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case file + case files + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(file, forKey: .file) + try container.encodeIfPresent(files, forKey: .files) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift new file mode 100644 index 000000000000..fcbb5c3f7be6 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -0,0 +1,79 @@ +// +// FormatTest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct FormatTest: Codable { + + public var integer: Int? + public var int32: Int? + public var int64: Int64? + public var number: Double + public var float: Float? + public var double: Double? + public var string: String? + public var byte: Data + public var binary: URL? + public var date: Date + public var dateTime: Date? + public var uuid: UUID? + public var password: String + + public init(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double? = nil, string: String? = nil, byte: Data, binary: URL? = nil, date: Date, dateTime: Date? = nil, uuid: UUID? = nil, password: String) { + self.integer = integer + self.int32 = int32 + self.int64 = int64 + self.number = number + self.float = float + self.double = double + self.string = string + self.byte = byte + self.binary = binary + self.date = date + self.dateTime = dateTime + self.uuid = uuid + self.password = password + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case integer + case int32 + case int64 + case number + case float + case double + case string + case byte + case binary + case date + case dateTime + case uuid + case password + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(integer, forKey: .integer) + try container.encodeIfPresent(int32, forKey: .int32) + try container.encodeIfPresent(int64, forKey: .int64) + try container.encode(number, forKey: .number) + try container.encodeIfPresent(float, forKey: .float) + try container.encodeIfPresent(double, forKey: .double) + try container.encodeIfPresent(string, forKey: .string) + try container.encode(byte, forKey: .byte) + try container.encodeIfPresent(binary, forKey: .binary) + try container.encode(date, forKey: .date) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encode(password, forKey: .password) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift new file mode 100644 index 000000000000..42fe810e04a1 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -0,0 +1,35 @@ +// +// HasOnlyReadOnly.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct HasOnlyReadOnly: Codable { + + public var bar: String? + public var foo: String? + + public init(bar: String? = nil, foo: String? = nil) { + self.bar = bar + self.foo = foo + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case foo + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(foo, forKey: .foo) + } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/List.swift similarity index 51% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/List.swift index f8f08e4c6c44..e5c7ec7f3d63 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,8 +6,11 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif -public struct List: Codable, Hashable { +public struct List: Codable { public var _123list: String? @@ -19,4 +22,10 @@ public struct List: Codable, Hashable { case _123list = "123-list" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_123list, forKey: ._123list) + } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift similarity index 65% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index bd4e7b97e81b..c1d8412cda0c 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,8 +6,11 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif -public struct MapTest: Codable, Hashable { +public struct MapTest: Codable { public enum MapOfEnumString: String, Codable, CaseIterable { case upper = "UPPER" @@ -32,4 +35,13 @@ public struct MapTest: Codable, Hashable { case indirectMap = "indirect_map" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapMapOfString, forKey: .mapMapOfString) + try container.encodeIfPresent(mapOfEnumString, forKey: .mapOfEnumString) + try container.encodeIfPresent(directMap, forKey: .directMap) + try container.encodeIfPresent(indirectMap, forKey: .indirectMap) + } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift new file mode 100644 index 000000000000..e2b084551587 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -0,0 +1,39 @@ +// +// MixedPropertiesAndAdditionalPropertiesClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct MixedPropertiesAndAdditionalPropertiesClass: Codable { + + public var uuid: UUID? + public var dateTime: Date? + public var map: [String: Animal]? + + public init(uuid: UUID? = nil, dateTime: Date? = nil, map: [String: Animal]? = nil) { + self.uuid = uuid + self.dateTime = dateTime + self.map = map + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case uuid + case dateTime + case map + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(map, forKey: .map) + } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift similarity index 55% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index d36d4e27352a..3e02e71a66fc 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name starting with number */ -public struct Model200Response: Codable, Hashable { +public struct Model200Response: Codable { public var name: Int? public var _class: String? @@ -23,4 +26,11 @@ public struct Model200Response: Codable, Hashable { case _class = "class" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(_class, forKey: ._class) + } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Name.swift similarity index 58% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 49cc57544179..9cef79be16ce 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing model name same as property name */ -public struct Name: Codable, Hashable { +public struct Name: Codable { public var name: Int public var snakeCase: Int? @@ -29,4 +32,13 @@ public struct Name: Codable, Hashable { case _123number = "123Number" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encodeIfPresent(snakeCase, forKey: .snakeCase) + try container.encodeIfPresent(property, forKey: .property) + try container.encodeIfPresent(_123number, forKey: ._123number) + } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift similarity index 52% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 6b024294e288..9da0be0af2bf 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,8 +6,11 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif -public struct NumberOnly: Codable, Hashable { +public struct NumberOnly: Codable { public var justNumber: Double? @@ -19,4 +22,10 @@ public struct NumberOnly: Codable, Hashable { case justNumber = "JustNumber" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justNumber, forKey: .justNumber) + } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Order.swift similarity index 50% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 8ef7cb79e2c8..adde2ac76243 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,8 +6,11 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif -public struct Order: Codable, Hashable { +public struct Order: Codable { public enum Status: String, Codable, CaseIterable { case placed = "placed" @@ -31,4 +34,24 @@ public struct Order: Codable, Hashable { self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case petId + case quantity + case shipDate + case status + case complete + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(petId, forKey: .petId) + try container.encodeIfPresent(quantity, forKey: .quantity) + try container.encodeIfPresent(shipDate, forKey: .shipDate) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(complete, forKey: .complete) + } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift similarity index 56% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 9865764ff9bb..0a520ef9ae79 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,8 +6,11 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif -public struct OuterComposite: Codable, Hashable { +public struct OuterComposite: Codable { public var myNumber: Double? public var myString: String? @@ -25,4 +28,12 @@ public struct OuterComposite: Codable, Hashable { case myBoolean = "my_boolean" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(myNumber, forKey: .myNumber) + try container.encodeIfPresent(myString, forKey: .myString) + try container.encodeIfPresent(myBoolean, forKey: .myBoolean) + } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift similarity index 83% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index c3b778cbbed4..76c34b3c2ce6 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift similarity index 52% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 1bc823d3e960..a87ab825ea0b 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,6 +6,9 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Pet: Codable, Hashable { @@ -31,4 +34,24 @@ public struct Pet: Codable, Hashable { self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case category + case name + case photoUrls + case tags + case status + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(category, forKey: .category) + try container.encode(name, forKey: .name) + try container.encode(photoUrls, forKey: .photoUrls) + try container.encodeIfPresent(tags, forKey: .tags) + try container.encodeIfPresent(status, forKey: .status) + } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift new file mode 100644 index 000000000000..eeaf9625e38a --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -0,0 +1,35 @@ +// +// ReadOnlyFirst.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ReadOnlyFirst: Codable { + + public var bar: String? + public var baz: String? + + public init(bar: String? = nil, baz: String? = nil) { + self.bar = bar + self.baz = baz + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case baz + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(baz, forKey: .baz) + } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Return.swift similarity index 54% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 5f539f461843..b1abd5c64859 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif /** Model for testing reserved words */ -public struct Return: Codable, Hashable { +public struct Return: Codable { public var _return: Int? @@ -20,4 +23,10 @@ public struct Return: Codable, Hashable { case _return = "return" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_return, forKey: ._return) + } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift similarity index 54% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index cb82d2ae3adc..65d9147f3e62 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,8 +6,11 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif -public struct SpecialModelName: Codable, Hashable { +public struct SpecialModelName: Codable { public var specialPropertyName: Int64? @@ -19,4 +22,10 @@ public struct SpecialModelName: Codable, Hashable { case specialPropertyName = "$special[property.name]" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) + } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift new file mode 100644 index 000000000000..9494292aaef9 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -0,0 +1,51 @@ +// +// StringBooleanMap.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct StringBooleanMap: Codable { + + + public enum CodingKeys: CodingKey, CaseIterable { + } + + public var additionalProperties: [String: Bool] = [:] + + public subscript(key: String) -> Bool? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + var nonAdditionalPropertyKeys = Set() + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift new file mode 100644 index 000000000000..cd5acc827db7 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -0,0 +1,35 @@ +// +// Tag.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Tag: Codable, Hashable { + + public var id: Int64? + public var name: String? + + public init(id: Int64? = nil, name: String? = nil) { + self.id = id + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(name, forKey: .name) + } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift similarity index 61% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index f1920ef37788..ac7d4626df75 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,8 +6,11 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif -public struct TypeHolderDefault: Codable, Hashable { +public struct TypeHolderDefault: Codable { public var stringItem: String = "what" public var numberItem: Double @@ -31,4 +34,14 @@ public struct TypeHolderDefault: Codable, Hashable { case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift similarity index 60% rename from samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index 1a23c1b486b8..2de070c49279 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,8 +6,11 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif -public struct TypeHolderExample: Codable, Hashable { +public struct TypeHolderExample: Codable { public var stringItem: String public var numberItem: Double @@ -31,4 +34,14 @@ public struct TypeHolderExample: Codable, Hashable { case arrayItem = "array_item" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/User.swift new file mode 100644 index 000000000000..c25aec1dc049 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -0,0 +1,60 @@ +// +// User.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct User: Codable { + + public var id: Int64? + public var username: String? + public var firstName: String? + public var lastName: String? + public var email: String? + public var password: String? + public var phone: String? + /** User Status */ + public var userStatus: Int? + + public init(id: Int64? = nil, username: String? = nil, firstName: String? = nil, lastName: String? = nil, email: String? = nil, password: String? = nil, phone: String? = nil, userStatus: Int? = nil) { + self.id = id + self.username = username + self.firstName = firstName + self.lastName = lastName + self.email = email + self.password = password + self.phone = phone + self.userStatus = userStatus + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case username + case firstName + case lastName + case email + case password + case phone + case userStatus + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(username, forKey: .username) + try container.encodeIfPresent(firstName, forKey: .firstName) + try container.encodeIfPresent(lastName, forKey: .lastName) + try container.encodeIfPresent(email, forKey: .email) + try container.encodeIfPresent(password, forKey: .password) + try container.encodeIfPresent(phone, forKey: .phone) + try container.encodeIfPresent(userStatus, forKey: .userStatus) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/XmlItem.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/XmlItem.swift new file mode 100644 index 000000000000..896202b00ec4 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/XmlItem.swift @@ -0,0 +1,143 @@ +// +// XmlItem.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct XmlItem: Codable { + + public var attributeString: String? + public var attributeNumber: Double? + public var attributeInteger: Int? + public var attributeBoolean: Bool? + public var wrappedArray: [Int]? + public var nameString: String? + public var nameNumber: Double? + public var nameInteger: Int? + public var nameBoolean: Bool? + public var nameArray: [Int]? + public var nameWrappedArray: [Int]? + public var prefixString: String? + public var prefixNumber: Double? + public var prefixInteger: Int? + public var prefixBoolean: Bool? + public var prefixArray: [Int]? + public var prefixWrappedArray: [Int]? + public var namespaceString: String? + public var namespaceNumber: Double? + public var namespaceInteger: Int? + public var namespaceBoolean: Bool? + public var namespaceArray: [Int]? + public var namespaceWrappedArray: [Int]? + public var prefixNsString: String? + public var prefixNsNumber: Double? + public var prefixNsInteger: Int? + public var prefixNsBoolean: Bool? + public var prefixNsArray: [Int]? + public var prefixNsWrappedArray: [Int]? + + public init(attributeString: String? = nil, attributeNumber: Double? = nil, attributeInteger: Int? = nil, attributeBoolean: Bool? = nil, wrappedArray: [Int]? = nil, nameString: String? = nil, nameNumber: Double? = nil, nameInteger: Int? = nil, nameBoolean: Bool? = nil, nameArray: [Int]? = nil, nameWrappedArray: [Int]? = nil, prefixString: String? = nil, prefixNumber: Double? = nil, prefixInteger: Int? = nil, prefixBoolean: Bool? = nil, prefixArray: [Int]? = nil, prefixWrappedArray: [Int]? = nil, namespaceString: String? = nil, namespaceNumber: Double? = nil, namespaceInteger: Int? = nil, namespaceBoolean: Bool? = nil, namespaceArray: [Int]? = nil, namespaceWrappedArray: [Int]? = nil, prefixNsString: String? = nil, prefixNsNumber: Double? = nil, prefixNsInteger: Int? = nil, prefixNsBoolean: Bool? = nil, prefixNsArray: [Int]? = nil, prefixNsWrappedArray: [Int]? = nil) { + self.attributeString = attributeString + self.attributeNumber = attributeNumber + self.attributeInteger = attributeInteger + self.attributeBoolean = attributeBoolean + self.wrappedArray = wrappedArray + self.nameString = nameString + self.nameNumber = nameNumber + self.nameInteger = nameInteger + self.nameBoolean = nameBoolean + self.nameArray = nameArray + self.nameWrappedArray = nameWrappedArray + self.prefixString = prefixString + self.prefixNumber = prefixNumber + self.prefixInteger = prefixInteger + self.prefixBoolean = prefixBoolean + self.prefixArray = prefixArray + self.prefixWrappedArray = prefixWrappedArray + self.namespaceString = namespaceString + self.namespaceNumber = namespaceNumber + self.namespaceInteger = namespaceInteger + self.namespaceBoolean = namespaceBoolean + self.namespaceArray = namespaceArray + self.namespaceWrappedArray = namespaceWrappedArray + self.prefixNsString = prefixNsString + self.prefixNsNumber = prefixNsNumber + self.prefixNsInteger = prefixNsInteger + self.prefixNsBoolean = prefixNsBoolean + self.prefixNsArray = prefixNsArray + self.prefixNsWrappedArray = prefixNsWrappedArray + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case attributeString = "attribute_string" + case attributeNumber = "attribute_number" + case attributeInteger = "attribute_integer" + case attributeBoolean = "attribute_boolean" + case wrappedArray = "wrapped_array" + case nameString = "name_string" + case nameNumber = "name_number" + case nameInteger = "name_integer" + case nameBoolean = "name_boolean" + case nameArray = "name_array" + case nameWrappedArray = "name_wrapped_array" + case prefixString = "prefix_string" + case prefixNumber = "prefix_number" + case prefixInteger = "prefix_integer" + case prefixBoolean = "prefix_boolean" + case prefixArray = "prefix_array" + case prefixWrappedArray = "prefix_wrapped_array" + case namespaceString = "namespace_string" + case namespaceNumber = "namespace_number" + case namespaceInteger = "namespace_integer" + case namespaceBoolean = "namespace_boolean" + case namespaceArray = "namespace_array" + case namespaceWrappedArray = "namespace_wrapped_array" + case prefixNsString = "prefix_ns_string" + case prefixNsNumber = "prefix_ns_number" + case prefixNsInteger = "prefix_ns_integer" + case prefixNsBoolean = "prefix_ns_boolean" + case prefixNsArray = "prefix_ns_array" + case prefixNsWrappedArray = "prefix_ns_wrapped_array" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(attributeString, forKey: .attributeString) + try container.encodeIfPresent(attributeNumber, forKey: .attributeNumber) + try container.encodeIfPresent(attributeInteger, forKey: .attributeInteger) + try container.encodeIfPresent(attributeBoolean, forKey: .attributeBoolean) + try container.encodeIfPresent(wrappedArray, forKey: .wrappedArray) + try container.encodeIfPresent(nameString, forKey: .nameString) + try container.encodeIfPresent(nameNumber, forKey: .nameNumber) + try container.encodeIfPresent(nameInteger, forKey: .nameInteger) + try container.encodeIfPresent(nameBoolean, forKey: .nameBoolean) + try container.encodeIfPresent(nameArray, forKey: .nameArray) + try container.encodeIfPresent(nameWrappedArray, forKey: .nameWrappedArray) + try container.encodeIfPresent(prefixString, forKey: .prefixString) + try container.encodeIfPresent(prefixNumber, forKey: .prefixNumber) + try container.encodeIfPresent(prefixInteger, forKey: .prefixInteger) + try container.encodeIfPresent(prefixBoolean, forKey: .prefixBoolean) + try container.encodeIfPresent(prefixArray, forKey: .prefixArray) + try container.encodeIfPresent(prefixWrappedArray, forKey: .prefixWrappedArray) + try container.encodeIfPresent(namespaceString, forKey: .namespaceString) + try container.encodeIfPresent(namespaceNumber, forKey: .namespaceNumber) + try container.encodeIfPresent(namespaceInteger, forKey: .namespaceInteger) + try container.encodeIfPresent(namespaceBoolean, forKey: .namespaceBoolean) + try container.encodeIfPresent(namespaceArray, forKey: .namespaceArray) + try container.encodeIfPresent(namespaceWrappedArray, forKey: .namespaceWrappedArray) + try container.encodeIfPresent(prefixNsString, forKey: .prefixNsString) + try container.encodeIfPresent(prefixNsNumber, forKey: .prefixNsNumber) + try container.encodeIfPresent(prefixNsInteger, forKey: .prefixNsInteger) + try container.encodeIfPresent(prefixNsBoolean, forKey: .prefixNsBoolean) + try container.encodeIfPresent(prefixNsArray, forKey: .prefixNsArray) + try container.encodeIfPresent(prefixNsWrappedArray, forKey: .prefixNsWrappedArray) + } + + + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift new file mode 100644 index 000000000000..e06208074cd9 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -0,0 +1,44 @@ +// +// OpenISO8601DateFormatter.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +// https://stackoverflow.com/a/50281094/976628 +public class OpenISO8601DateFormatter: DateFormatter { + static let withoutSeconds: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" + return formatter + }() + + private func setup() { + calendar = Calendar(identifier: .iso8601) + locale = Locale(identifier: "en_US_POSIX") + timeZone = TimeZone(secondsFromGMT: 0) + dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + } + + override init() { + super.init() + setup() + } + + required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + setup() + } + + override public func date(from string: String) -> Date? { + if let result = super.date(from: string) { + return result + } + return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift new file mode 100644 index 000000000000..acf7ff4031bd --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift @@ -0,0 +1,36 @@ +// SynchronizedDictionary.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +internal struct SynchronizedDictionary { + + private var dictionary = [K: V]() + private let queue = DispatchQueue( + label: "SynchronizedDictionary", + qos: DispatchQoS.userInitiated, + attributes: [DispatchQueue.Attributes.concurrent], + autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, + target: nil + ) + + internal subscript(key: K) -> V? { + get { + var value: V? + + queue.sync { + value = self.dictionary[key] + } + + return value + } + set { + queue.sync(flags: DispatchWorkItemFlags.barrier) { + self.dictionary[key] = newValue + } + } + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift new file mode 100644 index 000000000000..774c0427eaa2 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -0,0 +1,649 @@ +// URLSessionImplementations.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if !os(macOS) +import MobileCoreServices +#endif + +class URLSessionRequestBuilderFactory: RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type { + return URLSessionRequestBuilder.self + } + + func getBuilder() -> RequestBuilder.Type { + return URLSessionDecodableRequestBuilder.self + } +} + +// Store the URLSession to retain its reference +private var urlSessionStore = SynchronizedDictionary() + +open class URLSessionRequestBuilder: RequestBuilder { + + /** + May be assigned if you want to control the authentication challenges. + */ + public var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /** + May be assigned if you want to do any of those things: + - control the task completion + - intercept and handle errors like authorization + - retry the request. + */ + @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") + public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? + + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + } + + /** + May be overridden by a subclass if you want to control the URLSession + configuration. + */ + open func createURLSession() -> URLSession { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = buildHeaders() + let sessionDelegate = SessionDelegate() + sessionDelegate.credential = credential + sessionDelegate.taskDidReceiveChallenge = taskDidReceiveChallenge + return URLSession(configuration: configuration, delegate: sessionDelegate, delegateQueue: nil) + } + + /** + May be overridden by a subclass if you want to control the Content-Type + that is given to an uploaded form part. + + Return nil to use the default behavior (inferring the Content-Type from + the file extension). Return the desired Content-Type otherwise. + */ + open func contentTypeForFormPart(fileURL: URL) -> String? { + return nil + } + + /** + May be overridden by a subclass if you want to control the URLRequest + configuration (e.g. to override the cache policy). + */ + open func createURLRequest(urlSession: URLSession, method: HTTPMethod, encoding: ParameterEncoding, headers: [String: String]) throws -> URLRequest { + + guard let url = URL(string: URLString) else { + throw DownloadException.requestMissingURL + } + + var originalRequest = URLRequest(url: url) + + originalRequest.httpMethod = method.rawValue + + headers.forEach { key, value in + originalRequest.setValue(value, forHTTPHeaderField: key) + } + + buildHeaders().forEach { key, value in + originalRequest.setValue(value, forHTTPHeaderField: key) + } + + let modifiedRequest = try encoding.encode(originalRequest, with: parameters) + + return modifiedRequest + } + + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + let urlSessionId = UUID().uuidString + // Create a new manager for each request to customize its request header + let urlSession = createURLSession() + urlSessionStore[urlSessionId] = urlSession + + guard let xMethod = HTTPMethod(rawValue: method) else { + fatalError("Unsuported Http method - \(method)") + } + + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = FormURLEncoding() + } else { + fatalError("Unsuported Media Type - \(contentType)") + } + } + + let cleanupRequest = { + urlSessionStore[urlSessionId]?.finishTasksAndInvalidate() + urlSessionStore[urlSessionId] = nil + } + + do { + let request = try createURLRequest(urlSession: urlSession, method: xMethod, encoding: encoding, headers: headers) + + let dataTask = urlSession.dataTask(with: request) { data, response, error in + + if let taskCompletionShouldRetry = self.taskCompletionShouldRetry { + + taskCompletionShouldRetry(data, response, error) { shouldRetry in + + if shouldRetry { + cleanupRequest() + self.execute(apiResponseQueue, completion) + } else { + apiResponseQueue.async { + self.processRequestResponse(urlRequest: request, data: data, response: response, error: error, completion: completion) + cleanupRequest() + } + } + } + } else { + apiResponseQueue.async { + self.processRequestResponse(urlRequest: request, data: data, response: response, error: error, completion: completion) + cleanupRequest() + } + } + } + + if #available(iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0, *) { + onProgressReady?(dataTask.progress) + } + + dataTask.resume() + + } catch { + apiResponseQueue.async { + cleanupRequest() + completion(.failure(ErrorResponse.error(415, nil, nil, error))) + } + } + } + + fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + + if let error = error { + completion(.failure(ErrorResponse.error(-1, data, response, error))) + return + } + + guard let httpResponse = response as? HTTPURLResponse else { + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) + return + } + + guard httpResponse.isStatusCodeSuccessful else { + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + return + } + + switch T.self { + case is String.Type: + + let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" + + completion(.success(Response(response: httpResponse, body: body as? T))) + + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + + case is Void.Type: + + completion(.success(Response(response: httpResponse, body: nil))) + + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + + default: + + completion(.success(Response(response: httpResponse, body: data as? T))) + } + + } + + open func buildHeaders() -> [String: String] { + var httpHeaders: [String: String] = [:] + for (key, value) in headers { + httpHeaders[key] = value + } + for (key, value) in PetstoreClient.customHeaders { + httpHeaders[key] = value + } + return httpHeaders + } + + fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? { + + guard let contentDisposition = contentDisposition else { + return nil + } + + let items = contentDisposition.components(separatedBy: ";") + + var filename: String? + + for contentItem in items { + + let filenameKey = "filename=" + guard let range = contentItem.range(of: filenameKey) else { + break + } + + filename = contentItem + return filename? + .replacingCharacters(in: range, with: "") + .replacingOccurrences(of: "\"", with: "") + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + return filename + + } + + fileprivate func getPath(from url: URL) throws -> String { + + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + throw DownloadException.requestMissingPath + } + + if path.hasPrefix("/") { + path.remove(at: path.startIndex) + } + + return path + + } + + fileprivate func getURL(from urlRequest: URLRequest) throws -> URL { + + guard let url = urlRequest.url else { + throw DownloadException.requestMissingURL + } + + return url + } + +} + +open class URLSessionDecodableRequestBuilder: URLSessionRequestBuilder { + override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + + if let error = error { + completion(.failure(ErrorResponse.error(-1, data, response, error))) + return + } + + guard let httpResponse = response as? HTTPURLResponse else { + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) + return + } + + guard httpResponse.isStatusCodeSuccessful else { + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + return + } + + switch T.self { + case is String.Type: + + let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" + + completion(.success(Response(response: httpResponse, body: body as? T))) + + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + + case is Void.Type: + + completion(.success(Response(response: httpResponse, body: nil))) + + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + + default: + + guard let data = data, !data.isEmpty else { + completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) + return + } + + let decodeResult = CodableHelper.decode(T.self, from: data) + + switch decodeResult { + case let .success(decodableObj): + completion(.success(Response(response: httpResponse, body: decodableObj))) + case let .failure(error): + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, error))) + } + } + } +} + +private class SessionDelegate: NSObject, URLSessionDelegate, URLSessionDataDelegate { + + var credential: URLCredential? + + var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { + + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + + var credential: URLCredential? + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) + } else { + if challenge.previousFailureCount > 0 { + disposition = .rejectProtectionSpace + } else { + credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) + + if credential != nil { + disposition = .useCredential + } + } + } + + completionHandler(disposition, credential) + } +} + +public enum HTTPMethod: String { + case options = "OPTIONS" + case get = "GET" + case head = "HEAD" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" + case trace = "TRACE" + case connect = "CONNECT" +} + +public protocol ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest +} + +private class URLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + guard let parameters = parameters else { return urlRequest } + + guard let url = urlRequest.url else { + throw DownloadException.requestMissingURL + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + urlComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters) + urlRequest.url = urlComponents.url + } + + return urlRequest + } +} + +private class FormDataEncoding: ParameterEncoding { + + let contentTypeForFormPart: (_ fileURL: URL) -> String? + + init(contentTypeForFormPart: @escaping (_ fileURL: URL) -> String?) { + self.contentTypeForFormPart = contentTypeForFormPart + } + + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + guard let parameters = parameters, !parameters.isEmpty else { + return urlRequest + } + + let boundary = "Boundary-\(UUID().uuidString)" + + urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") + + for (key, value) in parameters { + switch value { + case let fileURL as URL: + + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) + + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") + } + } + + var body = urlRequest.httpBody.orEmpty + + body.append("\r\n--\(boundary)--\r\n") + + urlRequest.httpBody = body + + return urlRequest + } + + private func configureFileUploadRequest(urlRequest: URLRequest, boundary: String, name: String, fileURL: URL) throws -> URLRequest { + + var urlRequest = urlRequest + + var body = urlRequest.httpBody.orEmpty + + let fileData = try Data(contentsOf: fileURL) + + let mimetype = contentTypeForFormPart(fileURL) ?? mimeType(for: fileURL) + + let fileName = fileURL.lastPathComponent + + // If we already added something then we need an additional newline. + if body.count > 0 { + body.append("\r\n") + } + + // Value boundary. + body.append("--\(boundary)\r\n") + + // Value headers. + body.append("Content-Disposition: form-data; name=\"\(name)\"; filename=\"\(fileName)\"\r\n") + body.append("Content-Type: \(mimetype)\r\n") + + // Separate headers and body. + body.append("\r\n") + + // The value data. + body.append(fileData) + + urlRequest.httpBody = body + + return urlRequest + } + + private func configureDataUploadRequest(urlRequest: URLRequest, boundary: String, name: String, data: Data) -> URLRequest { + + var urlRequest = urlRequest + + var body = urlRequest.httpBody.orEmpty + + // If we already added something then we need an additional newline. + if body.count > 0 { + body.append("\r\n") + } + + // Value boundary. + body.append("--\(boundary)\r\n") + + // Value headers. + body.append("Content-Disposition: form-data; name=\"\(name)\"\r\n") + + // Separate headers and body. + body.append("\r\n") + + // The value data. + body.append(data) + + urlRequest.httpBody = body + + return urlRequest + + } + + func mimeType(for url: URL) -> String { + let pathExtension = url.pathExtension + + if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as NSString, nil)?.takeRetainedValue() { + if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() { + return mimetype as String + } + } + return "application/octet-stream" + } + +} + +private class FormURLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + var requestBodyComponents = URLComponents() + requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + + return urlRequest + } +} + +private extension Data { + /// Append string to Data + /// + /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8. + /// + /// - parameter string: The string to be added to the `Data`. + + mutating func append(_ string: String) { + if let data = string.data(using: .utf8) { + append(data) + } + } +} + +private extension Optional where Wrapped == Data { + var orEmpty: Data { + self ?? Data() + } +} + +extension JSONDataEncoding: ParameterEncoding {} diff --git a/samples/client/petstore/swift5/x-swift-hashable/README.md b/samples/client/petstore/swift5/x-swift-hashable/README.md new file mode 100644 index 000000000000..1725415f7e04 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/README.md @@ -0,0 +1,141 @@ +# Swift5 API client for PetstoreClient + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.Swift5ClientCodegen + +## Installation + +### Carthage + +Run `carthage update` + +### CocoaPods + +Run `pod install` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AnotherFakeAPI* | [**call123testSpecialTags**](docs/AnotherFakeAPI.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags +*FakeAPI* | [**fakeOuterBooleanSerialize**](docs/FakeAPI.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +*FakeAPI* | [**fakeOuterCompositeSerialize**](docs/FakeAPI.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +*FakeAPI* | [**fakeOuterNumberSerialize**](docs/FakeAPI.md#fakeouternumberserialize) | **POST** /fake/outer/number | +*FakeAPI* | [**fakeOuterStringSerialize**](docs/FakeAPI.md#fakeouterstringserialize) | **POST** /fake/outer/string | +*FakeAPI* | [**testBodyWithFileSchema**](docs/FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | +*FakeAPI* | [**testBodyWithQueryParams**](docs/FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | +*FakeAPI* | [**testClientModel**](docs/FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeAPI* | [**testEnumParameters**](docs/FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters +*FakeAPI* | [**testGroupParameters**](docs/FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +*FakeAPI* | [**testInlineAdditionalProperties**](docs/FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeAPI* | [**testJsonFormData**](docs/FakeAPI.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeClassnameTags123API* | [**testClassname**](docs/FakeClassnameTags123API.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case +*PetAPI* | [**addPet**](docs/PetAPI.md#addpet) | **POST** /pet | Add a new pet to the store +*PetAPI* | [**deletePet**](docs/PetAPI.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetAPI* | [**findPetsByStatus**](docs/PetAPI.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetAPI* | [**findPetsByTags**](docs/PetAPI.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetAPI* | [**getPetById**](docs/PetAPI.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetAPI* | [**updatePet**](docs/PetAPI.md#updatepet) | **PUT** /pet | Update an existing pet +*PetAPI* | [**updatePetWithForm**](docs/PetAPI.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetAPI* | [**uploadFile**](docs/PetAPI.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*PetAPI* | [**uploadFileWithRequiredFile**](docs/PetAPI.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +*StoreAPI* | [**deleteOrder**](docs/StoreAPI.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +*StoreAPI* | [**getInventory**](docs/StoreAPI.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreAPI* | [**getOrderById**](docs/StoreAPI.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +*StoreAPI* | [**placeOrder**](docs/StoreAPI.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserAPI* | [**createUser**](docs/UserAPI.md#createuser) | **POST** /user | Create user +*UserAPI* | [**createUsersWithArrayInput**](docs/UserAPI.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserAPI* | [**createUsersWithListInput**](docs/UserAPI.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserAPI* | [**deleteUser**](docs/UserAPI.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserAPI* | [**getUserByName**](docs/UserAPI.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserAPI* | [**loginUser**](docs/UserAPI.md#loginuser) | **GET** /user/login | Logs user into the system +*UserAPI* | [**logoutUser**](docs/UserAPI.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserAPI* | [**updateUser**](docs/UserAPI.md#updateuser) | **PUT** /user/{username} | Updated user + + +## Documentation For Models + + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ApiResponse](docs/ApiResponse.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayTest](docs/ArrayTest.md) + - [Capitalization](docs/Capitalization.md) + - [Cat](docs/Cat.md) + - [CatAllOf](docs/CatAllOf.md) + - [Category](docs/Category.md) + - [ClassModel](docs/ClassModel.md) + - [Client](docs/Client.md) + - [Dog](docs/Dog.md) + - [DogAllOf](docs/DogAllOf.md) + - [EnumArrays](docs/EnumArrays.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [File](docs/File.md) + - [FileSchemaTestClass](docs/FileSchemaTestClass.md) + - [FormatTest](docs/FormatTest.md) + - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [List](docs/List.md) + - [MapTest](docs/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model200Response.md) + - [Name](docs/Name.md) + - [NumberOnly](docs/NumberOnly.md) + - [Order](docs/Order.md) + - [OuterComposite](docs/OuterComposite.md) + - [OuterEnum](docs/OuterEnum.md) + - [Pet](docs/Pet.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Return](docs/Return.md) + - [SpecialModelName](docs/SpecialModelName.md) + - [StringBooleanMap](docs/StringBooleanMap.md) + - [Tag](docs/Tag.md) + - [TypeHolderDefault](docs/TypeHolderDefault.md) + - [TypeHolderExample](docs/TypeHolderExample.md) + - [User](docs/User.md) + + +## Documentation For Authorization + + +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +## api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + +## http_basic_test + +- **Type**: HTTP basic authentication + +## petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - **write:pets**: modify pets in your account + - **read:pets**: read your pets + + +## Author + + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesAnyType.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesAnyType.md new file mode 100644 index 000000000000..bae60ab148f2 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesAnyType.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesAnyType + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesArray.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesArray.md new file mode 100644 index 000000000000..a371b5e28f32 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesArray.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesArray + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesBoolean.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesBoolean.md new file mode 100644 index 000000000000..d5f0d6da11ee --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesBoolean.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesBoolean + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesClass.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesClass.md new file mode 100644 index 000000000000..1f222244134e --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapString** | **[String: String]** | | [optional] +**mapMapString** | [String: [String: String]] | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesInteger.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesInteger.md new file mode 100644 index 000000000000..629293abdfe9 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesInteger.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesInteger + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesNumber.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesNumber.md new file mode 100644 index 000000000000..65adfe78137c --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesNumber.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesNumber + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesObject.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesObject.md new file mode 100644 index 000000000000..99d69b7aae6a --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesObject.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesObject + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesString.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesString.md new file mode 100644 index 000000000000..5bb8122887c4 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesString.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesString + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/Animal.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Animal.md new file mode 100644 index 000000000000..69c601455cd8 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Animal.md @@ -0,0 +1,11 @@ +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] [default to "red"] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/AnimalFarm.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AnimalFarm.md new file mode 100644 index 000000000000..df6bab21dae8 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AnimalFarm.md @@ -0,0 +1,9 @@ +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/AnotherFakeAPI.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AnotherFakeAPI.md new file mode 100644 index 000000000000..aead5f1f980f --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AnotherFakeAPI.md @@ -0,0 +1,59 @@ +# AnotherFakeAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**call123testSpecialTags**](AnotherFakeAPI.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags + + +# **call123testSpecialTags** +```swift + open class func call123testSpecialTags(body: Client, completion: @escaping (_ data: Client?, _ error: Error?) -> Void) +``` + +To test special tags + +To test special tags and operation ID starting with number + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Client(client: "client_example") // Client | client model + +// To test special tags +AnotherFakeAPI.call123testSpecialTags(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md) | client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/ApiResponse.md b/samples/client/petstore/swift5/x-swift-hashable/docs/ApiResponse.md new file mode 100644 index 000000000000..c6d9768fe9bf --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/ApiResponse.md @@ -0,0 +1,12 @@ +# ApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Int** | | [optional] +**type** | **String** | | [optional] +**message** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/swift5/x-swift-hashable/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 000000000000..c6fceff5e08d --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayArrayNumber** | [[Double]] | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/ArrayOfNumberOnly.md b/samples/client/petstore/swift5/x-swift-hashable/docs/ArrayOfNumberOnly.md new file mode 100644 index 000000000000..f09f8fa6f70f --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayNumber** | **[Double]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/ArrayTest.md b/samples/client/petstore/swift5/x-swift-hashable/docs/ArrayTest.md new file mode 100644 index 000000000000..bf416b8330cc --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/ArrayTest.md @@ -0,0 +1,12 @@ +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **[String]** | | [optional] +**arrayArrayOfInteger** | [[Int64]] | | [optional] +**arrayArrayOfModel** | [[ReadOnlyFirst]] | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/BigCat.md b/samples/client/petstore/swift5/x-swift-hashable/docs/BigCat.md new file mode 100644 index 000000000000..cd904c7381a2 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/BigCat.md @@ -0,0 +1,10 @@ +# BigCat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/BigCatAllOf.md b/samples/client/petstore/swift5/x-swift-hashable/docs/BigCatAllOf.md new file mode 100644 index 000000000000..20da4caf5d01 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/BigCatAllOf.md @@ -0,0 +1,10 @@ +# BigCatAllOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/Capitalization.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Capitalization.md new file mode 100644 index 000000000000..95374216c773 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Capitalization.md @@ -0,0 +1,15 @@ +# Capitalization + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**smallCamel** | **String** | | [optional] +**capitalCamel** | **String** | | [optional] +**smallSnake** | **String** | | [optional] +**capitalSnake** | **String** | | [optional] +**sCAETHFlowPoints** | **String** | | [optional] +**ATT_NAME** | **String** | Name of the pet | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/Cat.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Cat.md new file mode 100644 index 000000000000..fb5949b15761 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Cat.md @@ -0,0 +1,10 @@ +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/CatAllOf.md b/samples/client/petstore/swift5/x-swift-hashable/docs/CatAllOf.md new file mode 100644 index 000000000000..79789be61c01 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/CatAllOf.md @@ -0,0 +1,10 @@ +# CatAllOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/Category.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Category.md new file mode 100644 index 000000000000..5ca5408c0f96 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Category.md @@ -0,0 +1,11 @@ +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**name** | **String** | | [default to "default-name"] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/ClassModel.md b/samples/client/petstore/swift5/x-swift-hashable/docs/ClassModel.md new file mode 100644 index 000000000000..e3912fdf0fd5 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/ClassModel.md @@ -0,0 +1,10 @@ +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_class** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/Client.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Client.md new file mode 100644 index 000000000000..0de1b238c36f --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Client.md @@ -0,0 +1,10 @@ +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/Dog.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Dog.md new file mode 100644 index 000000000000..4824786da049 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Dog.md @@ -0,0 +1,10 @@ +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/DogAllOf.md b/samples/client/petstore/swift5/x-swift-hashable/docs/DogAllOf.md new file mode 100644 index 000000000000..9302ef52e938 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/DogAllOf.md @@ -0,0 +1,10 @@ +# DogAllOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/EnumArrays.md b/samples/client/petstore/swift5/x-swift-hashable/docs/EnumArrays.md new file mode 100644 index 000000000000..b9a9807d3c8e --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/EnumArrays.md @@ -0,0 +1,11 @@ +# EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justSymbol** | **String** | | [optional] +**arrayEnum** | **[String]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/EnumClass.md b/samples/client/petstore/swift5/x-swift-hashable/docs/EnumClass.md new file mode 100644 index 000000000000..67f017becd0c --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/EnumClass.md @@ -0,0 +1,9 @@ +# EnumClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/EnumTest.md b/samples/client/petstore/swift5/x-swift-hashable/docs/EnumTest.md new file mode 100644 index 000000000000..bc9b036dd769 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/EnumTest.md @@ -0,0 +1,14 @@ +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | **String** | | [optional] +**enumStringRequired** | **String** | | +**enumInteger** | **Int** | | [optional] +**enumNumber** | **Double** | | [optional] +**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/FakeAPI.md b/samples/client/petstore/swift5/x-swift-hashable/docs/FakeAPI.md new file mode 100644 index 000000000000..553a46281aa0 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/FakeAPI.md @@ -0,0 +1,662 @@ +# FakeAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**fakeOuterBooleanSerialize**](FakeAPI.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +[**fakeOuterCompositeSerialize**](FakeAPI.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +[**fakeOuterNumberSerialize**](FakeAPI.md#fakeouternumberserialize) | **POST** /fake/outer/number | +[**fakeOuterStringSerialize**](FakeAPI.md#fakeouterstringserialize) | **POST** /fake/outer/string | +[**testBodyWithFileSchema**](FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | +[**testBodyWithQueryParams**](FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | +[**testClientModel**](FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumParameters**](FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters +[**testGroupParameters**](FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[**testInlineAdditionalProperties**](FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**testJsonFormData**](FakeAPI.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data + + +# **fakeOuterBooleanSerialize** +```swift + open class func fakeOuterBooleanSerialize(body: Bool? = nil, completion: @escaping (_ data: Bool?, _ error: Error?) -> Void) +``` + + + +Test serialization of outer boolean types + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = true // Bool | Input boolean as post body (optional) + +FakeAPI.fakeOuterBooleanSerialize(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **Bool** | Input boolean as post body | [optional] + +### Return type + +**Bool** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **fakeOuterCompositeSerialize** +```swift + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping (_ data: OuterComposite?, _ error: Error?) -> Void) +``` + + + +Test serialization of object with outer number type + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = OuterComposite(myNumber: 123, myString: "myString_example", myBoolean: false) // OuterComposite | Input composite as post body (optional) + +FakeAPI.fakeOuterCompositeSerialize(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**OuterComposite**](OuterComposite.md) | Input composite as post body | [optional] + +### Return type + +[**OuterComposite**](OuterComposite.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **fakeOuterNumberSerialize** +```swift + open class func fakeOuterNumberSerialize(body: Double? = nil, completion: @escaping (_ data: Double?, _ error: Error?) -> Void) +``` + + + +Test serialization of outer number types + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = 987 // Double | Input number as post body (optional) + +FakeAPI.fakeOuterNumberSerialize(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **Double** | Input number as post body | [optional] + +### Return type + +**Double** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **fakeOuterStringSerialize** +```swift + open class func fakeOuterStringSerialize(body: String? = nil, completion: @escaping (_ data: String?, _ error: Error?) -> Void) +``` + + + +Test serialization of outer string types + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = "body_example" // String | Input string as post body (optional) + +FakeAPI.fakeOuterStringSerialize(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **String** | Input string as post body | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **testBodyWithFileSchema** +```swift + open class func testBodyWithFileSchema(body: FileSchemaTestClass, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + + + +For this test, the body for this request much reference a schema named `File`. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = FileSchemaTestClass(file: File(sourceURI: "sourceURI_example"), files: [nil]) // FileSchemaTestClass | + +FakeAPI.testBodyWithFileSchema(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**FileSchemaTestClass**](FileSchemaTestClass.md) | | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **testBodyWithQueryParams** +```swift + open class func testBodyWithQueryParams(query: String, body: User, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + + + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let query = "query_example" // String | +let body = User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123) // User | + +FakeAPI.testBodyWithQueryParams(query: query, body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **query** | **String** | | + **body** | [**User**](User.md) | | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **testClientModel** +```swift + open class func testClientModel(body: Client, completion: @escaping (_ data: Client?, _ error: Error?) -> Void) +``` + +To test \"client\" model + +To test \"client\" model + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Client(client: "client_example") // Client | client model + +// To test \"client\" model +FakeAPI.testClientModel(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md) | client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **testEndpointParameters** +```swift + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let number = 987 // Double | None +let double = 987 // Double | None +let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None +let byte = Data([9, 8, 7]) // Data | None +let integer = 987 // Int | None (optional) +let int32 = 987 // Int | None (optional) +let int64 = 987 // Int64 | None (optional) +let float = 987 // Float | None (optional) +let string = "string_example" // String | None (optional) +let binary = URL(string: "https://example.com")! // URL | None (optional) +let date = Date() // Date | None (optional) +let dateTime = Date() // Date | None (optional) +let password = "password_example" // String | None (optional) +let callback = "callback_example" // String | None (optional) + +// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +FakeAPI.testEndpointParameters(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **Double** | None | + **double** | **Double** | None | + **patternWithoutDelimiter** | **String** | None | + **byte** | **Data** | None | + **integer** | **Int** | None | [optional] + **int32** | **Int** | None | [optional] + **int64** | **Int64** | None | [optional] + **float** | **Float** | None | [optional] + **string** | **String** | None | [optional] + **binary** | **URL** | None | [optional] + **date** | **Date** | None | [optional] + **dateTime** | **Date** | None | [optional] + **password** | **String** | None | [optional] + **callback** | **String** | None | [optional] + +### Return type + +Void (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **testEnumParameters** +```swift + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +To test enum parameters + +To test enum parameters + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let enumHeaderStringArray = ["enumHeaderStringArray_example"] // [String] | Header parameter enum test (string array) (optional) +let enumHeaderString = "enumHeaderString_example" // String | Header parameter enum test (string) (optional) (default to .efg) +let enumQueryStringArray = ["enumQueryStringArray_example"] // [String] | Query parameter enum test (string array) (optional) +let enumQueryString = "enumQueryString_example" // String | Query parameter enum test (string) (optional) (default to .efg) +let enumQueryInteger = 987 // Int | Query parameter enum test (double) (optional) +let enumQueryDouble = 987 // Double | Query parameter enum test (double) (optional) +let enumFormStringArray = ["inner_example"] // [String] | Form parameter enum test (string array) (optional) (default to .dollar) +let enumFormString = "enumFormString_example" // String | Form parameter enum test (string) (optional) (default to .efg) + +// To test enum parameters +FakeAPI.testEnumParameters(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumHeaderStringArray** | [**[String]**](String.md) | Header parameter enum test (string array) | [optional] + **enumHeaderString** | **String** | Header parameter enum test (string) | [optional] [default to .efg] + **enumQueryStringArray** | [**[String]**](String.md) | Query parameter enum test (string array) | [optional] + **enumQueryString** | **String** | Query parameter enum test (string) | [optional] [default to .efg] + **enumQueryInteger** | **Int** | Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double** | Query parameter enum test (double) | [optional] + **enumFormStringArray** | [**[String]**](String.md) | Form parameter enum test (string array) | [optional] [default to .dollar] + **enumFormString** | **String** | Form parameter enum test (string) | [optional] [default to .efg] + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **testGroupParameters** +```swift + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let requiredStringGroup = 987 // Int | Required String in group parameters +let requiredBooleanGroup = true // Bool | Required Boolean in group parameters +let requiredInt64Group = 987 // Int64 | Required Integer in group parameters +let stringGroup = 987 // Int | String in group parameters (optional) +let booleanGroup = true // Bool | Boolean in group parameters (optional) +let int64Group = 987 // Int64 | Integer in group parameters (optional) + +// Fake endpoint to test group parameters (optional) +FakeAPI.testGroupParameters(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requiredStringGroup** | **Int** | Required String in group parameters | + **requiredBooleanGroup** | **Bool** | Required Boolean in group parameters | + **requiredInt64Group** | **Int64** | Required Integer in group parameters | + **stringGroup** | **Int** | String in group parameters | [optional] + **booleanGroup** | **Bool** | Boolean in group parameters | [optional] + **int64Group** | **Int64** | Integer in group parameters | [optional] + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **testInlineAdditionalProperties** +```swift + open class func testInlineAdditionalProperties(param: [String: String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +test inline additionalProperties + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let param = "TODO" // [String: String] | request body + +// test inline additionalProperties +FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | [**[String: String]**](String.md) | request body | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **testJsonFormData** +```swift + open class func testJsonFormData(param: String, param2: String, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +test json serialization of form data + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let param = "param_example" // String | field1 +let param2 = "param2_example" // String | field2 + +// test json serialization of form data +FakeAPI.testJsonFormData(param: param, param2: param2) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **String** | field1 | + **param2** | **String** | field2 | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/FakeClassnameTags123API.md b/samples/client/petstore/swift5/x-swift-hashable/docs/FakeClassnameTags123API.md new file mode 100644 index 000000000000..9f24b46edbc3 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/FakeClassnameTags123API.md @@ -0,0 +1,59 @@ +# FakeClassnameTags123API + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testClassname**](FakeClassnameTags123API.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case + + +# **testClassname** +```swift + open class func testClassname(body: Client, completion: @escaping (_ data: Client?, _ error: Error?) -> Void) +``` + +To test class name in snake case + +To test class name in snake case + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Client(client: "client_example") // Client | client model + +// To test class name in snake case +FakeClassnameTags123API.testClassname(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md) | client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/File.md b/samples/client/petstore/swift5/x-swift-hashable/docs/File.md new file mode 100644 index 000000000000..3edfef17b794 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/File.md @@ -0,0 +1,10 @@ +# File + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**sourceURI** | **String** | Test capitalization | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/FileSchemaTestClass.md b/samples/client/petstore/swift5/x-swift-hashable/docs/FileSchemaTestClass.md new file mode 100644 index 000000000000..afdacc60b2c3 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/FileSchemaTestClass.md @@ -0,0 +1,11 @@ +# FileSchemaTestClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**file** | [**File**](File.md) | | [optional] +**files** | [File] | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/FormatTest.md b/samples/client/petstore/swift5/x-swift-hashable/docs/FormatTest.md new file mode 100644 index 000000000000..f74d94f6c46a --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/FormatTest.md @@ -0,0 +1,22 @@ +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Int** | | [optional] +**int32** | **Int** | | [optional] +**int64** | **Int64** | | [optional] +**number** | **Double** | | +**float** | **Float** | | [optional] +**double** | **Double** | | [optional] +**string** | **String** | | [optional] +**byte** | **Data** | | +**binary** | **URL** | | [optional] +**date** | **Date** | | +**dateTime** | **Date** | | [optional] +**uuid** | **UUID** | | [optional] +**password** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/HasOnlyReadOnly.md b/samples/client/petstore/swift5/x-swift-hashable/docs/HasOnlyReadOnly.md new file mode 100644 index 000000000000..57b6e3a17e67 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] [readonly] +**foo** | **String** | | [optional] [readonly] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/List.md b/samples/client/petstore/swift5/x-swift-hashable/docs/List.md new file mode 100644 index 000000000000..b77718302edf --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/List.md @@ -0,0 +1,10 @@ +# List + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123list** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/MapTest.md b/samples/client/petstore/swift5/x-swift-hashable/docs/MapTest.md new file mode 100644 index 000000000000..73f9e0d50acf --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/MapTest.md @@ -0,0 +1,13 @@ +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapMapOfString** | [String: [String: String]] | | [optional] +**mapOfEnumString** | **[String: String]** | | [optional] +**directMap** | **[String: Bool]** | | [optional] +**indirectMap** | [**StringBooleanMap**](StringBooleanMap.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/swift5/x-swift-hashable/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 000000000000..3fdfd03f0e31 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **UUID** | | [optional] +**dateTime** | **Date** | | [optional] +**map** | [String: Animal] | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/Model200Response.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Model200Response.md new file mode 100644 index 000000000000..5865ea690cc3 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Model200Response.md @@ -0,0 +1,11 @@ +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Int** | | [optional] +**_class** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/Name.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Name.md new file mode 100644 index 000000000000..f7b180292cd6 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Name.md @@ -0,0 +1,13 @@ +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Int** | | +**snakeCase** | **Int** | | [optional] [readonly] +**property** | **String** | | [optional] +**_123number** | **Int** | | [optional] [readonly] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/NumberOnly.md b/samples/client/petstore/swift5/x-swift-hashable/docs/NumberOnly.md new file mode 100644 index 000000000000..72bd361168b5 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/NumberOnly.md @@ -0,0 +1,10 @@ +# NumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justNumber** | **Double** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/Order.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Order.md new file mode 100644 index 000000000000..15487f01175c --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Order.md @@ -0,0 +1,15 @@ +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**petId** | **Int64** | | [optional] +**quantity** | **Int** | | [optional] +**shipDate** | **Date** | | [optional] +**status** | **String** | Order Status | [optional] +**complete** | **Bool** | | [optional] [default to false] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/OuterComposite.md b/samples/client/petstore/swift5/x-swift-hashable/docs/OuterComposite.md new file mode 100644 index 000000000000..d6b3583bc3ff --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/OuterComposite.md @@ -0,0 +1,12 @@ +# OuterComposite + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**myNumber** | **Double** | | [optional] +**myString** | **String** | | [optional] +**myBoolean** | **Bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/OuterEnum.md b/samples/client/petstore/swift5/x-swift-hashable/docs/OuterEnum.md new file mode 100644 index 000000000000..06d413b01680 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/OuterEnum.md @@ -0,0 +1,9 @@ +# OuterEnum + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/Pet.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Pet.md new file mode 100644 index 000000000000..5c05f98fad4a --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Pet.md @@ -0,0 +1,15 @@ +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **[String]** | | +**tags** | [Tag] | | [optional] +**status** | **String** | pet status in the store | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/PetAPI.md b/samples/client/petstore/swift5/x-swift-hashable/docs/PetAPI.md new file mode 100644 index 000000000000..27efe0833476 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/PetAPI.md @@ -0,0 +1,469 @@ +# PetAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetAPI.md#addpet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetAPI.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetAPI.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetAPI.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetAPI.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetAPI.md#updatepet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetAPI.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetAPI.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +[**uploadFileWithRequiredFile**](PetAPI.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) + + +# **addPet** +```swift + open class func addPet(body: Pet, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Add a new pet to the store + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Pet(id: 123, category: Category(id: 123, name: "name_example"), name: "name_example", photoUrls: ["photoUrls_example"], tags: [Tag(id: 123, name: "name_example")], status: "status_example") // Pet | Pet object that needs to be added to the store + +// Add a new pet to the store +PetAPI.addPet(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | + +### Return type + +Void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **deletePet** +```swift + open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Deletes a pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | Pet id to delete +let apiKey = "apiKey_example" // String | (optional) + +// Deletes a pet +PetAPI.deletePet(petId: petId, apiKey: apiKey) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | Pet id to delete | + **apiKey** | **String** | | [optional] + +### Return type + +Void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **findPetsByStatus** +```swift + open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) +``` + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let status = ["status_example"] // [String] | Status values that need to be considered for filter + +// Finds Pets by status +PetAPI.findPetsByStatus(status: status) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**[String]**](String.md) | Status values that need to be considered for filter | + +### Return type + +[**[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **findPetsByTags** +```swift + open class func findPetsByTags(tags: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) +``` + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let tags = ["inner_example"] // [String] | Tags to filter by + +// Finds Pets by tags +PetAPI.findPetsByTags(tags: tags) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**[String]**](String.md) | Tags to filter by | + +### Return type + +[**[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **getPetById** +```swift + open class func getPetById(petId: Int64, completion: @escaping (_ data: Pet?, _ error: Error?) -> Void) +``` + +Find pet by ID + +Returns a single pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet to return + +// Find pet by ID +PetAPI.getPetById(petId: petId) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **updatePet** +```swift + open class func updatePet(body: Pet, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Update an existing pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Pet(id: 123, category: Category(id: 123, name: "name_example"), name: "name_example", photoUrls: ["photoUrls_example"], tags: [Tag(id: 123, name: "name_example")], status: "status_example") // Pet | Pet object that needs to be added to the store + +// Update an existing pet +PetAPI.updatePet(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | + +### Return type + +Void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **updatePetWithForm** +```swift + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Updates a pet in the store with form data + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet that needs to be updated +let name = "name_example" // String | Updated name of the pet (optional) +let status = "status_example" // String | Updated status of the pet (optional) + +// Updates a pet in the store with form data +PetAPI.updatePetWithForm(petId: petId, name: name, status: status) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | ID of pet that needs to be updated | + **name** | **String** | Updated name of the pet | [optional] + **status** | **String** | Updated status of the pet | [optional] + +### Return type + +Void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **uploadFile** +```swift + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping (_ data: ApiResponse?, _ error: Error?) -> Void) +``` + +uploads an image + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet to update +let additionalMetadata = "additionalMetadata_example" // String | Additional data to pass to server (optional) +let file = URL(string: "https://example.com")! // URL | file to upload (optional) + +// uploads an image +PetAPI.uploadFile(petId: petId, additionalMetadata: additionalMetadata, file: file) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | ID of pet to update | + **additionalMetadata** | **String** | Additional data to pass to server | [optional] + **file** | **URL** | file to upload | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **uploadFileWithRequiredFile** +```swift + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, completion: @escaping (_ data: ApiResponse?, _ error: Error?) -> Void) +``` + +uploads an image (required) + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet to update +let requiredFile = URL(string: "https://example.com")! // URL | file to upload +let additionalMetadata = "additionalMetadata_example" // String | Additional data to pass to server (optional) + +// uploads an image (required) +PetAPI.uploadFileWithRequiredFile(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | ID of pet to update | + **requiredFile** | **URL** | file to upload | + **additionalMetadata** | **String** | Additional data to pass to server | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/ReadOnlyFirst.md b/samples/client/petstore/swift5/x-swift-hashable/docs/ReadOnlyFirst.md new file mode 100644 index 000000000000..ed537b87598b --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] [readonly] +**baz** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/Return.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Return.md new file mode 100644 index 000000000000..66d17c27c887 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Return.md @@ -0,0 +1,10 @@ +# Return + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Int** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/SpecialModelName.md b/samples/client/petstore/swift5/x-swift-hashable/docs/SpecialModelName.md new file mode 100644 index 000000000000..3ec27a38c2ac --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/SpecialModelName.md @@ -0,0 +1,10 @@ +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Int64** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/StoreAPI.md b/samples/client/petstore/swift5/x-swift-hashable/docs/StoreAPI.md new file mode 100644 index 000000000000..383dda5d3c71 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/StoreAPI.md @@ -0,0 +1,206 @@ +# StoreAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreAPI.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +[**getInventory**](StoreAPI.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreAPI.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +[**placeOrder**](StoreAPI.md#placeorder) | **POST** /store/order | Place an order for a pet + + +# **deleteOrder** +```swift + open class func deleteOrder(orderId: String, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let orderId = "orderId_example" // String | ID of the order that needs to be deleted + +// Delete purchase order by ID +StoreAPI.deleteOrder(orderId: orderId) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String** | ID of the order that needs to be deleted | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **getInventory** +```swift + open class func getInventory(completion: @escaping (_ data: [String: Int]?, _ error: Error?) -> Void) +``` + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + + +// Returns pet inventories by status +StoreAPI.getInventory() { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**[String: Int]** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **getOrderById** +```swift + open class func getOrderById(orderId: Int64, completion: @escaping (_ data: Order?, _ error: Error?) -> Void) +``` + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let orderId = 987 // Int64 | ID of pet that needs to be fetched + +// Find purchase order by ID +StoreAPI.getOrderById(orderId: orderId) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Int64** | ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **placeOrder** +```swift + open class func placeOrder(body: Order, completion: @escaping (_ data: Order?, _ error: Error?) -> Void) +``` + +Place an order for a pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Order(id: 123, petId: 123, quantity: 123, shipDate: Date(), status: "status_example", complete: false) // Order | order placed for purchasing the pet + +// Place an order for a pet +StoreAPI.placeOrder(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md) | order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/StringBooleanMap.md b/samples/client/petstore/swift5/x-swift-hashable/docs/StringBooleanMap.md new file mode 100644 index 000000000000..7abf11ec68b1 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/StringBooleanMap.md @@ -0,0 +1,9 @@ +# StringBooleanMap + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/Tag.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Tag.md new file mode 100644 index 000000000000..ff4ac8aa4519 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Tag.md @@ -0,0 +1,11 @@ +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**name** | **String** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/TypeHolderDefault.md b/samples/client/petstore/swift5/x-swift-hashable/docs/TypeHolderDefault.md new file mode 100644 index 000000000000..5161394bdc3e --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/TypeHolderDefault.md @@ -0,0 +1,14 @@ +# TypeHolderDefault + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stringItem** | **String** | | [default to "what"] +**numberItem** | **Double** | | +**integerItem** | **Int** | | +**boolItem** | **Bool** | | [default to true] +**arrayItem** | **[Int]** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/TypeHolderExample.md b/samples/client/petstore/swift5/x-swift-hashable/docs/TypeHolderExample.md new file mode 100644 index 000000000000..46d0471cd71a --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/TypeHolderExample.md @@ -0,0 +1,14 @@ +# TypeHolderExample + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stringItem** | **String** | | +**numberItem** | **Double** | | +**integerItem** | **Int** | | +**boolItem** | **Bool** | | +**arrayItem** | **[Int]** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/User.md b/samples/client/petstore/swift5/x-swift-hashable/docs/User.md new file mode 100644 index 000000000000..5a439de0ff95 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/User.md @@ -0,0 +1,17 @@ +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Int** | User Status | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/UserAPI.md b/samples/client/petstore/swift5/x-swift-hashable/docs/UserAPI.md new file mode 100644 index 000000000000..380813bc68c0 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/UserAPI.md @@ -0,0 +1,406 @@ +# UserAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserAPI.md#createuser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserAPI.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserAPI.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserAPI.md#deleteuser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserAPI.md#getuserbyname) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserAPI.md#loginuser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserAPI.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserAPI.md#updateuser) | **PUT** /user/{username} | Updated user + + +# **createUser** +```swift + open class func createUser(body: User, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Create user + +This can only be done by the logged in user. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123) // User | Created user object + +// Create user +UserAPI.createUser(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md) | Created user object | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **createUsersWithArrayInput** +```swift + open class func createUsersWithArrayInput(body: [User], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Creates list of users with given input array + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = [User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123)] // [User] | List of user object + +// Creates list of users with given input array +UserAPI.createUsersWithArrayInput(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[User]**](User.md) | List of user object | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **createUsersWithListInput** +```swift + open class func createUsersWithListInput(body: [User], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Creates list of users with given input array + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = [User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123)] // [User] | List of user object + +// Creates list of users with given input array +UserAPI.createUsersWithListInput(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[User]**](User.md) | List of user object | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **deleteUser** +```swift + open class func deleteUser(username: String, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Delete user + +This can only be done by the logged in user. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | The name that needs to be deleted + +// Delete user +UserAPI.deleteUser(username: username) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | The name that needs to be deleted | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **getUserByName** +```swift + open class func getUserByName(username: String, completion: @escaping (_ data: User?, _ error: Error?) -> Void) +``` + +Get user by user name + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | The name that needs to be fetched. Use user1 for testing. + +// Get user by user name +UserAPI.getUserByName(username: username) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **loginUser** +```swift + open class func loginUser(username: String, password: String, completion: @escaping (_ data: String?, _ error: Error?) -> Void) +``` + +Logs user into the system + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | The user name for login +let password = "password_example" // String | The password for login in clear text + +// Logs user into the system +UserAPI.loginUser(username: username, password: password) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | The user name for login | + **password** | **String** | The password for login in clear text | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **logoutUser** +```swift + open class func logoutUser(completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Logs out current logged in user session + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + + +// Logs out current logged in user session +UserAPI.logoutUser() { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **updateUser** +```swift + open class func updateUser(username: String, body: User, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Updated user + +This can only be done by the logged in user. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | name that need to be deleted +let body = User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123) // User | Updated user object + +// Updated user +UserAPI.updateUser(username: username, body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | name that need to be deleted | + **body** | [**User**](User.md) | Updated user object | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/XmlItem.md b/samples/client/petstore/swift5/x-swift-hashable/docs/XmlItem.md new file mode 100644 index 000000000000..1a4eb4e9c836 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/XmlItem.md @@ -0,0 +1,38 @@ +# XmlItem + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**attributeString** | **String** | | [optional] +**attributeNumber** | **Double** | | [optional] +**attributeInteger** | **Int** | | [optional] +**attributeBoolean** | **Bool** | | [optional] +**wrappedArray** | **[Int]** | | [optional] +**nameString** | **String** | | [optional] +**nameNumber** | **Double** | | [optional] +**nameInteger** | **Int** | | [optional] +**nameBoolean** | **Bool** | | [optional] +**nameArray** | **[Int]** | | [optional] +**nameWrappedArray** | **[Int]** | | [optional] +**prefixString** | **String** | | [optional] +**prefixNumber** | **Double** | | [optional] +**prefixInteger** | **Int** | | [optional] +**prefixBoolean** | **Bool** | | [optional] +**prefixArray** | **[Int]** | | [optional] +**prefixWrappedArray** | **[Int]** | | [optional] +**namespaceString** | **String** | | [optional] +**namespaceNumber** | **Double** | | [optional] +**namespaceInteger** | **Int** | | [optional] +**namespaceBoolean** | **Bool** | | [optional] +**namespaceArray** | **[Int]** | | [optional] +**namespaceWrappedArray** | **[Int]** | | [optional] +**prefixNsString** | **String** | | [optional] +**prefixNsNumber** | **Double** | | [optional] +**prefixNsInteger** | **Int** | | [optional] +**prefixNsBoolean** | **Bool** | | [optional] +**prefixNsArray** | **[Int]** | | [optional] +**prefixNsWrappedArray** | **[Int]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/git_push.sh b/samples/client/petstore/swift5/x-swift-hashable/git_push.sh new file mode 100644 index 000000000000..ced3be2b0c7b --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/git_push.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/swift5/x-swift-hashable/project.yml b/samples/client/petstore/swift5/x-swift-hashable/project.yml new file mode 100644 index 000000000000..0493cf65896e --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/project.yml @@ -0,0 +1,15 @@ +name: PetstoreClient +targets: + PetstoreClient: + type: framework + platform: iOS + deploymentTarget: "9.0" + sources: [PetstoreClient] + info: + path: ./Info.plist + version: 1.0.0 + settings: + APPLICATION_EXTENSION_API_ONLY: true + scheme: {} + dependencies: + - carthage: AnyCodable diff --git a/samples/client/petstore/tiny/cpp/.gitignore b/samples/client/petstore/tiny/cpp/.gitignore new file mode 100644 index 000000000000..89cc49cbd652 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/samples/client/petstore/tiny/cpp/.openapi-generator-ignore b/samples/client/petstore/tiny/cpp/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/tiny/cpp/.openapi-generator/FILES b/samples/client/petstore/tiny/cpp/.openapi-generator/FILES new file mode 100644 index 000000000000..1024d9450644 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/.openapi-generator/FILES @@ -0,0 +1,30 @@ +README.md +README.md +lib/Models/ApiResponse.cpp +lib/Models/ApiResponse.h +lib/Models/Category.cpp +lib/Models/Category.h +lib/Models/Helpers.cpp +lib/Models/Helpers.h +lib/Models/Order.cpp +lib/Models/Order.h +lib/Models/Pet.cpp +lib/Models/Pet.h +lib/Models/Tag.cpp +lib/Models/Tag.h +lib/Models/User.cpp +lib/Models/User.h +lib/service/AbstractService.cpp +lib/service/AbstractService.h +lib/service/PetApi.cpp +lib/service/PetApi.h +lib/service/Response.h +lib/service/StoreApi.cpp +lib/service/StoreApi.h +lib/service/UserApi.cpp +lib/service/UserApi.h +platformio.ini +pre_compiling_bourne.py +root.cert +src/main.cpp +test/RunTests.cpp diff --git a/samples/client/petstore/tiny/cpp/.openapi-generator/VERSION b/samples/client/petstore/tiny/cpp/.openapi-generator/VERSION new file mode 100644 index 000000000000..6555596f9311 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/tiny/cpp/README.md b/samples/client/petstore/tiny/cpp/README.md new file mode 100644 index 000000000000..e8bf721275b5 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/README.md @@ -0,0 +1,73 @@ +# Documentation for OpenAPI Petstore +This is a client generator for microcontrollers on the Espressif32 platform and the Arduino framework +After the client have been generated, you have to change these following variablies: +- root.cert | Provide your service root certificate. +- src/main.cpp | Change wifi name +- src/main.cpp | Change wifi password +- lib/service/AbstractService.h | Change to your url + +# Documentation for OpenAPI Petstore 1.0.0 Tiny client cpp (Arduino) + +The project is structured like this: +``` +samples/client/petstore/tiny/cpp/ +├── lib +│ ├── Models +│ ├── service +│ └── TestFiles +├── platformio.ini +├── pre_compiling_bourne.py +├── README.md +├── root.cert +├── src +│ └── main.cpp +└── test + └── RunTests.cpp +``` + +All URIs are relative to http://petstore.swagger.iohttp://petstore.swagger.io/v2 + +### PetApi +|Method | HTTP request | Description| +|------------- | ------------- | -------------| +|*addPet* | *POST* /pet | Add a new pet to the store.| +|*deletePet* | *DELETE* /pet/{petId} | Deletes a pet.| +|*findPetsByStatus* | *GET* /pet/findByStatus | Finds Pets by status.| +|*findPetsByTags* | *GET* /pet/findByTags | Finds Pets by tags.| +|*getPetById* | *GET* /pet/{petId} | Find pet by ID.| +|*updatePet* | *PUT* /pet | Update an existing pet.| +|*updatePetWithForm* | *POST* /pet/{petId} | Updates a pet in the store with form data.| +|*uploadFile* | *POST* /pet/{petId}/uploadImage | uploads an image.| + +### StoreApi +|Method | HTTP request | Description| +|------------- | ------------- | -------------| +|*deleteOrder* | *DELETE* /store/order/{orderId} | Delete purchase order by ID.| +|*getInventory* | *GET* /store/inventory | Returns pet inventories by status.| +|*getOrderById* | *GET* /store/order/{orderId} | Find purchase order by ID.| +|*placeOrder* | *POST* /store/order | Place an order for a pet.| + +### UserApi +|Method | HTTP request | Description| +|------------- | ------------- | -------------| +|*createUser* | *POST* /user | Create user.| +|*createUsersWithArrayInput* | *POST* /user/createWithArray | Creates list of users with given input array.| +|*createUsersWithListInput* | *POST* /user/createWithList | Creates list of users with given input array.| +|*deleteUser* | *DELETE* /user/{username} | Delete user.| +|*getUserByName* | *GET* /user/{username} | Get user by user name.| +|*loginUser* | *GET* /user/login | Logs user into the system.| +|*logoutUser* | *GET* /user/logout | Logs out current logged in user session.| +|*updateUser* | *PUT* /user/{username} | Updated user.| + + +## What are the Model files for the data structures/objects? +|Class | Description| +|------------- | -------------| +|*ApiResponse* | Describes the result of uploading an image resource| +|*Category* | A category for a pet| +|*Order* | An order for a pets from the pet store| +|*Pet* | A pet for sale in the pet store| +|*Tag* | A tag for a pet| +|*User* | A User who is purchasing from the pet store| + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.cpp b/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.cpp new file mode 100644 index 000000000000..e9be9e2b6187 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.cpp @@ -0,0 +1,139 @@ + + +#include "ApiResponse.h" + +using namespace Tiny; + +ApiResponse::ApiResponse() +{ + code = int(0); + type = std::string(); + message = std::string(); +} + +ApiResponse::ApiResponse(std::string jsonString) +{ + this->fromJson(jsonString); +} + +ApiResponse::~ApiResponse() +{ + +} + +void +ApiResponse::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *codeKey = "code"; + + if(object.has_key(codeKey)) + { + bourne::json value = object[codeKey]; + + + + jsonToValue(&code, value, "int"); + + + } + + const char *typeKey = "type"; + + if(object.has_key(typeKey)) + { + bourne::json value = object[typeKey]; + + + + jsonToValue(&type, value, "std::string"); + + + } + + const char *messageKey = "message"; + + if(object.has_key(messageKey)) + { + bourne::json value = object[messageKey]; + + + + jsonToValue(&message, value, "std::string"); + + + } + + +} + +bourne::json +ApiResponse::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["code"] = getCode(); + + + + + + + object["type"] = getType(); + + + + + + + object["message"] = getMessage(); + + + + return object; + +} + +int +ApiResponse::getCode() +{ + return code; +} + +void +ApiResponse::setCode(int code) +{ + this->code = code; +} + +std::string +ApiResponse::getType() +{ + return type; +} + +void +ApiResponse::setType(std::string type) +{ + this->type = type; +} + +std::string +ApiResponse::getMessage() +{ + return message; +} + +void +ApiResponse::setMessage(std::string message) +{ + this->message = message; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.h b/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.h new file mode 100644 index 000000000000..dbaf8abcaf38 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.h @@ -0,0 +1,78 @@ + +/* + * ApiResponse.h + * + * Describes the result of uploading an image resource + */ + +#ifndef TINY_CPP_CLIENT_ApiResponse_H_ +#define TINY_CPP_CLIENT_ApiResponse_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief Describes the result of uploading an image resource + * + * \ingroup Models + * + */ + +class ApiResponse{ +public: + + /*! \brief Constructor. + */ + ApiResponse(); + ApiResponse(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~ApiResponse(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + int getCode(); + + /*! \brief Set + */ + void setCode(int code); + /*! \brief Get + */ + std::string getType(); + + /*! \brief Set + */ + void setType(std::string type); + /*! \brief Get + */ + std::string getMessage(); + + /*! \brief Set + */ + void setMessage(std::string message); + + + private: + int code{}; + std::string type{}; + std::string message{}; +}; +} + +#endif /* TINY_CPP_CLIENT_ApiResponse_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Category.cpp b/samples/client/petstore/tiny/cpp/lib/Models/Category.cpp new file mode 100644 index 000000000000..950b06ffd44a --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Category.cpp @@ -0,0 +1,106 @@ + + +#include "Category.h" + +using namespace Tiny; + +Category::Category() +{ + id = long(0); + name = std::string(); +} + +Category::Category(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Category::~Category() +{ + +} + +void +Category::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *nameKey = "name"; + + if(object.has_key(nameKey)) + { + bourne::json value = object[nameKey]; + + + + jsonToValue(&name, value, "std::string"); + + + } + + +} + +bourne::json +Category::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["name"] = getName(); + + + + return object; + +} + +long +Category::getId() +{ + return id; +} + +void +Category::setId(long id) +{ + this->id = id; +} + +std::string +Category::getName() +{ + return name; +} + +void +Category::setName(std::string name) +{ + this->name = name; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Category.h b/samples/client/petstore/tiny/cpp/lib/Models/Category.h new file mode 100644 index 000000000000..9c90e3dd4160 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Category.h @@ -0,0 +1,70 @@ + +/* + * Category.h + * + * A category for a pet + */ + +#ifndef TINY_CPP_CLIENT_Category_H_ +#define TINY_CPP_CLIENT_Category_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief A category for a pet + * + * \ingroup Models + * + */ + +class Category{ +public: + + /*! \brief Constructor. + */ + Category(); + Category(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Category(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + std::string getName(); + + /*! \brief Set + */ + void setName(std::string name); + + + private: + long id{}; + std::string name{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Category_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Helpers.cpp b/samples/client/petstore/tiny/cpp/lib/Models/Helpers.cpp new file mode 100644 index 000000000000..c3935b37cde9 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Helpers.cpp @@ -0,0 +1,102 @@ +#include "Helpers.h" +#include +#include + +bool isprimitive(std::string type){ + if(type == "std::string" || + type == "int" || + type == "float" || + type == "long" || + type == "double" || + type == "bool" || + type == "std::map" || + type == "std::list") + { + return true; + } + return false; +} + + +void +jsonToValue(void* target, bourne::json value, std::string type) +{ + if (target == NULL || value.is_null()) { + return; + } + + else if (type.compare("bool") == 0) + { + bool* val = static_cast (target); + *val = value.to_bool(); + } + + else if (type.compare("int") == 0) + { + int* val = static_cast (target); + *val = value.to_int(); + } + + else if (type.compare("float") == 0) + { + float* val = static_cast (target); + *val = (float)(value.to_float()); + } + + else if (type.compare("long") == 0) + { + long* val = static_cast (target); + *val = (long)(value.to_int()); + } + + else if (type.compare("double") == 0) + { + double* val = static_cast (target); + *val = value.to_float(); + } + + else if (type.compare("std::string") == 0) + { + std::string* val = static_cast (target); + *val = value.to_string(); + } + else { + return; + } +} + +std::string +stringify(long input){ + std::stringstream stream; + stream << input; + return stream.str(); + +}; + +std::string +stringify(int input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(double input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(float input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(std::string input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Helpers.h b/samples/client/petstore/tiny/cpp/lib/Models/Helpers.h new file mode 100644 index 000000000000..5ef7d9afdf77 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Helpers.h @@ -0,0 +1,22 @@ +#ifndef TINY_CPP_CLIENT_HELPERS_H_ +#define TINY_CPP_CLIENT_HELPERS_H_ + +#include +#include "bourne/json.hpp" + +bool isprimitive(std::string type); + +void jsonToValue(void* target, bourne::json value, std::string type); + +std::string stringify(long input); + +std::string stringify(int input); + +std::string stringify(double input); + +std::string stringify(float input); + +std::string stringify(std::string input); + +#endif /* TINY_CPP_CLIENT_HELPERS_H_ */ + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Order.cpp b/samples/client/petstore/tiny/cpp/lib/Models/Order.cpp new file mode 100644 index 000000000000..b8b7e00d3fc8 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Order.cpp @@ -0,0 +1,238 @@ + + +#include "Order.h" + +using namespace Tiny; + +Order::Order() +{ + id = long(0); + petId = long(0); + quantity = int(0); + shipDate = std::string(); + status = std::string(); + complete = bool(false); +} + +Order::Order(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Order::~Order() +{ + +} + +void +Order::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *petIdKey = "petId"; + + if(object.has_key(petIdKey)) + { + bourne::json value = object[petIdKey]; + + + + jsonToValue(&petId, value, "long"); + + + } + + const char *quantityKey = "quantity"; + + if(object.has_key(quantityKey)) + { + bourne::json value = object[quantityKey]; + + + + jsonToValue(&quantity, value, "int"); + + + } + + const char *shipDateKey = "shipDate"; + + if(object.has_key(shipDateKey)) + { + bourne::json value = object[shipDateKey]; + + + + jsonToValue(&shipDate, value, "std::string"); + + + } + + const char *statusKey = "status"; + + if(object.has_key(statusKey)) + { + bourne::json value = object[statusKey]; + + + + jsonToValue(&status, value, "std::string"); + + + } + + const char *completeKey = "complete"; + + if(object.has_key(completeKey)) + { + bourne::json value = object[completeKey]; + + + + jsonToValue(&complete, value, "bool"); + + + } + + +} + +bourne::json +Order::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["petId"] = getPetId(); + + + + + + + object["quantity"] = getQuantity(); + + + + + + + object["shipDate"] = getShipDate(); + + + + + + + object["status"] = getStatus(); + + + + + + + object["complete"] = isComplete(); + + + + return object; + +} + +long +Order::getId() +{ + return id; +} + +void +Order::setId(long id) +{ + this->id = id; +} + +long +Order::getPetId() +{ + return petId; +} + +void +Order::setPetId(long petId) +{ + this->petId = petId; +} + +int +Order::getQuantity() +{ + return quantity; +} + +void +Order::setQuantity(int quantity) +{ + this->quantity = quantity; +} + +std::string +Order::getShipDate() +{ + return shipDate; +} + +void +Order::setShipDate(std::string shipDate) +{ + this->shipDate = shipDate; +} + +std::string +Order::getStatus() +{ + return status; +} + +void +Order::setStatus(std::string status) +{ + this->status = status; +} + +bool +Order::isComplete() +{ + return complete; +} + +void +Order::setComplete(bool complete) +{ + this->complete = complete; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Order.h b/samples/client/petstore/tiny/cpp/lib/Models/Order.h new file mode 100644 index 000000000000..6f36404f959a --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Order.h @@ -0,0 +1,102 @@ + +/* + * Order.h + * + * An order for a pets from the pet store + */ + +#ifndef TINY_CPP_CLIENT_Order_H_ +#define TINY_CPP_CLIENT_Order_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief An order for a pets from the pet store + * + * \ingroup Models + * + */ + +class Order{ +public: + + /*! \brief Constructor. + */ + Order(); + Order(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Order(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + long getPetId(); + + /*! \brief Set + */ + void setPetId(long petId); + /*! \brief Get + */ + int getQuantity(); + + /*! \brief Set + */ + void setQuantity(int quantity); + /*! \brief Get + */ + std::string getShipDate(); + + /*! \brief Set + */ + void setShipDate(std::string shipDate); + /*! \brief Get Order Status + */ + std::string getStatus(); + + /*! \brief Set Order Status + */ + void setStatus(std::string status); + /*! \brief Get + */ + bool isComplete(); + + /*! \brief Set + */ + void setComplete(bool complete); + + + private: + long id{}; + long petId{}; + int quantity{}; + std::string shipDate{}; + std::string status{}; + bool complete{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Order_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Pet.cpp b/samples/client/petstore/tiny/cpp/lib/Models/Pet.cpp new file mode 100644 index 000000000000..57f7781aef2a --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Pet.cpp @@ -0,0 +1,274 @@ + + +#include "Pet.h" + +using namespace Tiny; + +Pet::Pet() +{ + id = long(0); + category = Category(); + name = std::string(); + photoUrls = std::list(); + tags = std::list(); + status = std::string(); +} + +Pet::Pet(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Pet::~Pet() +{ + +} + +void +Pet::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *categoryKey = "category"; + + if(object.has_key(categoryKey)) + { + bourne::json value = object[categoryKey]; + + + + + Category* obj = &category; + obj->fromJson(value.dump()); + + } + + const char *nameKey = "name"; + + if(object.has_key(nameKey)) + { + bourne::json value = object[nameKey]; + + + + jsonToValue(&name, value, "std::string"); + + + } + + const char *photoUrlsKey = "photoUrls"; + + if(object.has_key(photoUrlsKey)) + { + bourne::json value = object[photoUrlsKey]; + + + std::list photoUrls_list; + std::string element; + for(auto& var : value.array_range()) + { + + jsonToValue(&element, var, "std::string"); + + + photoUrls_list.push_back(element); + } + photoUrls = photoUrls_list; + + + } + + const char *tagsKey = "tags"; + + if(object.has_key(tagsKey)) + { + bourne::json value = object[tagsKey]; + + + std::list tags_list; + Tag element; + for(auto& var : value.array_range()) + { + + + element.fromJson(var.dump()); + + tags_list.push_back(element); + } + tags = tags_list; + + + } + + const char *statusKey = "status"; + + if(object.has_key(statusKey)) + { + bourne::json value = object[statusKey]; + + + + jsonToValue(&status, value, "std::string"); + + + } + + +} + +bourne::json +Pet::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + + object["category"] = getCategory().toJson(); + + + + + + object["name"] = getName(); + + + + + + std::list photoUrls_list = getPhotoUrls(); + bourne::json photoUrls_arr = bourne::json::array(); + + for(auto& var : photoUrls_list) + { + photoUrls_arr.append(var); + } + object["photoUrls"] = photoUrls_arr; + + + + + + + + + std::list tags_list = getTags(); + bourne::json tags_arr = bourne::json::array(); + + for(auto& var : tags_list) + { + Tag obj = var; + tags_arr.append(obj.toJson()); + } + object["tags"] = tags_arr; + + + + + + + + object["status"] = getStatus(); + + + + return object; + +} + +long +Pet::getId() +{ + return id; +} + +void +Pet::setId(long id) +{ + this->id = id; +} + +Category +Pet::getCategory() +{ + return category; +} + +void +Pet::setCategory(Category category) +{ + this->category = category; +} + +std::string +Pet::getName() +{ + return name; +} + +void +Pet::setName(std::string name) +{ + this->name = name; +} + +std::list +Pet::getPhotoUrls() +{ + return photoUrls; +} + +void +Pet::setPhotoUrls(std::list photoUrls) +{ + this->photoUrls = photoUrls; +} + +std::list +Pet::getTags() +{ + return tags; +} + +void +Pet::setTags(std::list tags) +{ + this->tags = tags; +} + +std::string +Pet::getStatus() +{ + return status; +} + +void +Pet::setStatus(std::string status) +{ + this->status = status; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Pet.h b/samples/client/petstore/tiny/cpp/lib/Models/Pet.h new file mode 100644 index 000000000000..3329735f8a16 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Pet.h @@ -0,0 +1,105 @@ + +/* + * Pet.h + * + * A pet for sale in the pet store + */ + +#ifndef TINY_CPP_CLIENT_Pet_H_ +#define TINY_CPP_CLIENT_Pet_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" +#include "Category.h" +#include "Tag.h" +#include + +namespace Tiny { + + +/*! \brief A pet for sale in the pet store + * + * \ingroup Models + * + */ + +class Pet{ +public: + + /*! \brief Constructor. + */ + Pet(); + Pet(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Pet(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + Category getCategory(); + + /*! \brief Set + */ + void setCategory(Category category); + /*! \brief Get + */ + std::string getName(); + + /*! \brief Set + */ + void setName(std::string name); + /*! \brief Get + */ + std::list getPhotoUrls(); + + /*! \brief Set + */ + void setPhotoUrls(std::list photoUrls); + /*! \brief Get + */ + std::list getTags(); + + /*! \brief Set + */ + void setTags(std::list tags); + /*! \brief Get pet status in the store + */ + std::string getStatus(); + + /*! \brief Set pet status in the store + */ + void setStatus(std::string status); + + + private: + long id{}; + Category category; + std::string name{}; + std::list photoUrls; + std::list tags; + std::string status{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Pet_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Tag.cpp b/samples/client/petstore/tiny/cpp/lib/Models/Tag.cpp new file mode 100644 index 000000000000..e46d94258a1d --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Tag.cpp @@ -0,0 +1,106 @@ + + +#include "Tag.h" + +using namespace Tiny; + +Tag::Tag() +{ + id = long(0); + name = std::string(); +} + +Tag::Tag(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Tag::~Tag() +{ + +} + +void +Tag::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *nameKey = "name"; + + if(object.has_key(nameKey)) + { + bourne::json value = object[nameKey]; + + + + jsonToValue(&name, value, "std::string"); + + + } + + +} + +bourne::json +Tag::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["name"] = getName(); + + + + return object; + +} + +long +Tag::getId() +{ + return id; +} + +void +Tag::setId(long id) +{ + this->id = id; +} + +std::string +Tag::getName() +{ + return name; +} + +void +Tag::setName(std::string name) +{ + this->name = name; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Tag.h b/samples/client/petstore/tiny/cpp/lib/Models/Tag.h new file mode 100644 index 000000000000..e05bcdc92900 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Tag.h @@ -0,0 +1,70 @@ + +/* + * Tag.h + * + * A tag for a pet + */ + +#ifndef TINY_CPP_CLIENT_Tag_H_ +#define TINY_CPP_CLIENT_Tag_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief A tag for a pet + * + * \ingroup Models + * + */ + +class Tag{ +public: + + /*! \brief Constructor. + */ + Tag(); + Tag(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Tag(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + std::string getName(); + + /*! \brief Set + */ + void setName(std::string name); + + + private: + long id{}; + std::string name{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Tag_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/Models/User.cpp b/samples/client/petstore/tiny/cpp/lib/Models/User.cpp new file mode 100644 index 000000000000..ac84c40205a9 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/User.cpp @@ -0,0 +1,304 @@ + + +#include "User.h" + +using namespace Tiny; + +User::User() +{ + id = long(0); + username = std::string(); + firstName = std::string(); + lastName = std::string(); + email = std::string(); + password = std::string(); + phone = std::string(); + userStatus = int(0); +} + +User::User(std::string jsonString) +{ + this->fromJson(jsonString); +} + +User::~User() +{ + +} + +void +User::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *usernameKey = "username"; + + if(object.has_key(usernameKey)) + { + bourne::json value = object[usernameKey]; + + + + jsonToValue(&username, value, "std::string"); + + + } + + const char *firstNameKey = "firstName"; + + if(object.has_key(firstNameKey)) + { + bourne::json value = object[firstNameKey]; + + + + jsonToValue(&firstName, value, "std::string"); + + + } + + const char *lastNameKey = "lastName"; + + if(object.has_key(lastNameKey)) + { + bourne::json value = object[lastNameKey]; + + + + jsonToValue(&lastName, value, "std::string"); + + + } + + const char *emailKey = "email"; + + if(object.has_key(emailKey)) + { + bourne::json value = object[emailKey]; + + + + jsonToValue(&email, value, "std::string"); + + + } + + const char *passwordKey = "password"; + + if(object.has_key(passwordKey)) + { + bourne::json value = object[passwordKey]; + + + + jsonToValue(&password, value, "std::string"); + + + } + + const char *phoneKey = "phone"; + + if(object.has_key(phoneKey)) + { + bourne::json value = object[phoneKey]; + + + + jsonToValue(&phone, value, "std::string"); + + + } + + const char *userStatusKey = "userStatus"; + + if(object.has_key(userStatusKey)) + { + bourne::json value = object[userStatusKey]; + + + + jsonToValue(&userStatus, value, "int"); + + + } + + +} + +bourne::json +User::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["username"] = getUsername(); + + + + + + + object["firstName"] = getFirstName(); + + + + + + + object["lastName"] = getLastName(); + + + + + + + object["email"] = getEmail(); + + + + + + + object["password"] = getPassword(); + + + + + + + object["phone"] = getPhone(); + + + + + + + object["userStatus"] = getUserStatus(); + + + + return object; + +} + +long +User::getId() +{ + return id; +} + +void +User::setId(long id) +{ + this->id = id; +} + +std::string +User::getUsername() +{ + return username; +} + +void +User::setUsername(std::string username) +{ + this->username = username; +} + +std::string +User::getFirstName() +{ + return firstName; +} + +void +User::setFirstName(std::string firstName) +{ + this->firstName = firstName; +} + +std::string +User::getLastName() +{ + return lastName; +} + +void +User::setLastName(std::string lastName) +{ + this->lastName = lastName; +} + +std::string +User::getEmail() +{ + return email; +} + +void +User::setEmail(std::string email) +{ + this->email = email; +} + +std::string +User::getPassword() +{ + return password; +} + +void +User::setPassword(std::string password) +{ + this->password = password; +} + +std::string +User::getPhone() +{ + return phone; +} + +void +User::setPhone(std::string phone) +{ + this->phone = phone; +} + +int +User::getUserStatus() +{ + return userStatus; +} + +void +User::setUserStatus(int userStatus) +{ + this->userStatus = userStatus; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/User.h b/samples/client/petstore/tiny/cpp/lib/Models/User.h new file mode 100644 index 000000000000..84de5204ced8 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/User.h @@ -0,0 +1,118 @@ + +/* + * User.h + * + * A User who is purchasing from the pet store + */ + +#ifndef TINY_CPP_CLIENT_User_H_ +#define TINY_CPP_CLIENT_User_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief A User who is purchasing from the pet store + * + * \ingroup Models + * + */ + +class User{ +public: + + /*! \brief Constructor. + */ + User(); + User(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~User(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + std::string getUsername(); + + /*! \brief Set + */ + void setUsername(std::string username); + /*! \brief Get + */ + std::string getFirstName(); + + /*! \brief Set + */ + void setFirstName(std::string firstName); + /*! \brief Get + */ + std::string getLastName(); + + /*! \brief Set + */ + void setLastName(std::string lastName); + /*! \brief Get + */ + std::string getEmail(); + + /*! \brief Set + */ + void setEmail(std::string email); + /*! \brief Get + */ + std::string getPassword(); + + /*! \brief Set + */ + void setPassword(std::string password); + /*! \brief Get + */ + std::string getPhone(); + + /*! \brief Set + */ + void setPhone(std::string phone); + /*! \brief Get User Status + */ + int getUserStatus(); + + /*! \brief Set User Status + */ + void setUserStatus(int userStatus); + + + private: + long id{}; + std::string username{}; + std::string firstName{}; + std::string lastName{}; + std::string email{}; + std::string password{}; + std::string phone{}; + int userStatus{}; +}; +} + +#endif /* TINY_CPP_CLIENT_User_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/ApiResponseTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/ApiResponseTest.cpp new file mode 100644 index 000000000000..160f4217f5df --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/ApiResponseTest.cpp @@ -0,0 +1,139 @@ + +#include "ApiResponse.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_ApiResponse_code_is_assigned_from_json() +{ + bourne::json input = + { + "code", 1 + }; + + ApiResponse obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getCode()); + + + + + + + + +} + + +void test_ApiResponse_type_is_assigned_from_json() +{ + + + bourne::json input = + { + "type", "hello" + }; + + ApiResponse obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getType().c_str()); + + + + + + +} + + +void test_ApiResponse_message_is_assigned_from_json() +{ + + + bourne::json input = + { + "message", "hello" + }; + + ApiResponse obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getMessage().c_str()); + + + + + + +} + + + +void test_ApiResponse_code_is_converted_to_json() +{ + bourne::json input = + { + "code", 1 + }; + + ApiResponse obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["code"] == output["code"]); + + + + +} + + +void test_ApiResponse_type_is_converted_to_json() +{ + + bourne::json input = + { + "type", "hello" + }; + + ApiResponse obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["type"] == output["type"]); + + + +} + + +void test_ApiResponse_message_is_converted_to_json() +{ + + bourne::json input = + { + "message", "hello" + }; + + ApiResponse obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["message"] == output["message"]); + + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/CategoryTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/CategoryTest.cpp new file mode 100644 index 000000000000..2951856e6a58 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/CategoryTest.cpp @@ -0,0 +1,97 @@ + +#include "Category.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Category_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Category obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_Category_name_is_assigned_from_json() +{ + + + bourne::json input = + { + "name", "hello" + }; + + Category obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getName().c_str()); + + + + + + +} + + + +void test_Category_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Category obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_Category_name_is_converted_to_json() +{ + + bourne::json input = + { + "name", "hello" + }; + + Category obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["name"] == output["name"]); + + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/OrderTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/OrderTest.cpp new file mode 100644 index 000000000000..13125fc8fc5a --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/OrderTest.cpp @@ -0,0 +1,245 @@ + +#include "Order.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Order_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_Order_petId_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "petId", 1 + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getPetId()); + + +} + + +void test_Order_quantity_is_assigned_from_json() +{ + bourne::json input = + { + "quantity", 1 + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getQuantity()); + + + + + + + + +} + + +void test_Order_shipDate_is_assigned_from_json() +{ + + + + + + + + +} + + +void test_Order_status_is_assigned_from_json() +{ + + + bourne::json input = + { + "status", "hello" + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getStatus().c_str()); + + + + + + +} + + +void test_Order_complete_is_assigned_from_json() +{ + + + + + bourne::json input = + { + "complete", true + }; + + Order obj(input.dump()); + + TEST_ASSERT(true == obj.isComplete()); + + + + +} + + + +void test_Order_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_Order_petId_is_converted_to_json() +{ + + + + bourne::json input = + { + "petId", 1 + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["petId"] == output["petId"]); + +} + + +void test_Order_quantity_is_converted_to_json() +{ + bourne::json input = + { + "quantity", 1 + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["quantity"] == output["quantity"]); + + + + +} + + +void test_Order_shipDate_is_converted_to_json() +{ + + + + +} + + +void test_Order_status_is_converted_to_json() +{ + + bourne::json input = + { + "status", "hello" + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["status"] == output["status"]); + + + +} + + +void test_Order_complete_is_converted_to_json() +{ + + + bourne::json input = + { + "complete", true + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["complete"] == output["complete"]); + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/PetTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/PetTest.cpp new file mode 100644 index 000000000000..04dad4640939 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/PetTest.cpp @@ -0,0 +1,145 @@ + +#include "Pet.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Pet_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Pet obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + + +void test_Pet_name_is_assigned_from_json() +{ + + + bourne::json input = + { + "name", "hello" + }; + + Pet obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getName().c_str()); + + + + + + +} + + + + +void test_Pet_status_is_assigned_from_json() +{ + + + bourne::json input = + { + "status", "hello" + }; + + Pet obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getStatus().c_str()); + + + + + + +} + + + +void test_Pet_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Pet obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + + +void test_Pet_name_is_converted_to_json() +{ + + bourne::json input = + { + "name", "hello" + }; + + Pet obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["name"] == output["name"]); + + + +} + + + + +void test_Pet_status_is_converted_to_json() +{ + + bourne::json input = + { + "status", "hello" + }; + + Pet obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["status"] == output["status"]); + + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/TagTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/TagTest.cpp new file mode 100644 index 000000000000..41ea1d0095dd --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/TagTest.cpp @@ -0,0 +1,97 @@ + +#include "Tag.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Tag_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Tag obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_Tag_name_is_assigned_from_json() +{ + + + bourne::json input = + { + "name", "hello" + }; + + Tag obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getName().c_str()); + + + + + + +} + + + +void test_Tag_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Tag obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_Tag_name_is_converted_to_json() +{ + + bourne::json input = + { + "name", "hello" + }; + + Tag obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["name"] == output["name"]); + + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/UserTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/UserTest.cpp new file mode 100644 index 000000000000..689ee582bee3 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/UserTest.cpp @@ -0,0 +1,349 @@ + +#include "User.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_User_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_User_username_is_assigned_from_json() +{ + + + bourne::json input = + { + "username", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getUsername().c_str()); + + + + + + +} + + +void test_User_firstName_is_assigned_from_json() +{ + + + bourne::json input = + { + "firstName", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getFirstName().c_str()); + + + + + + +} + + +void test_User_lastName_is_assigned_from_json() +{ + + + bourne::json input = + { + "lastName", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getLastName().c_str()); + + + + + + +} + + +void test_User_email_is_assigned_from_json() +{ + + + bourne::json input = + { + "email", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getEmail().c_str()); + + + + + + +} + + +void test_User_password_is_assigned_from_json() +{ + + + bourne::json input = + { + "password", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getPassword().c_str()); + + + + + + +} + + +void test_User_phone_is_assigned_from_json() +{ + + + bourne::json input = + { + "phone", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getPhone().c_str()); + + + + + + +} + + +void test_User_userStatus_is_assigned_from_json() +{ + bourne::json input = + { + "userStatus", 1 + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getUserStatus()); + + + + + + + + +} + + + +void test_User_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_User_username_is_converted_to_json() +{ + + bourne::json input = + { + "username", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["username"] == output["username"]); + + + +} + + +void test_User_firstName_is_converted_to_json() +{ + + bourne::json input = + { + "firstName", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["firstName"] == output["firstName"]); + + + +} + + +void test_User_lastName_is_converted_to_json() +{ + + bourne::json input = + { + "lastName", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["lastName"] == output["lastName"]); + + + +} + + +void test_User_email_is_converted_to_json() +{ + + bourne::json input = + { + "email", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["email"] == output["email"]); + + + +} + + +void test_User_password_is_converted_to_json() +{ + + bourne::json input = + { + "password", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["password"] == output["password"]); + + + +} + + +void test_User_phone_is_converted_to_json() +{ + + bourne::json input = + { + "phone", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["phone"] == output["phone"]); + + + +} + + +void test_User_userStatus_is_converted_to_json() +{ + bourne::json input = + { + "userStatus", 1 + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["userStatus"] == output["userStatus"]); + + + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/service/AbstractService.cpp b/samples/client/petstore/tiny/cpp/lib/service/AbstractService.cpp new file mode 100644 index 000000000000..ac7e992cecc2 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/AbstractService.cpp @@ -0,0 +1,8 @@ +#include "AbstractService.h" +#include "Arduino.h" + + + +void Tiny::AbstractService::begin(std::string url){ + http.begin(String(url.c_str()), test_root_ca); //HTTPS connection +} diff --git a/samples/client/petstore/tiny/cpp/lib/service/AbstractService.h b/samples/client/petstore/tiny/cpp/lib/service/AbstractService.h new file mode 100644 index 000000000000..07214896d7f2 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/AbstractService.h @@ -0,0 +1,28 @@ +#ifndef TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ +#define TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ + +#include "HTTPClient.h" +#include "Response.h" +namespace Tiny { + +/** +* Class +* Generated with openapi::tiny-cpp-client +*/ +class AbstractService { +public: +HTTPClient http; +std::string basepath = "https://petstore3.swagger.io/api/v3"; // TODO: change to your url + +void begin(std::string url); + +// Go and comment out a certificate in root.cert, if you get an error here +// Certificate from file +const char* test_root_ca = +#include "../../root.cert" +; + +}; // end class +}// namespace Tinyclient + +#endif /* TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/service/PetApi.cpp b/samples/client/petstore/tiny/cpp/lib/service/PetApi.cpp new file mode 100644 index 000000000000..1fa081a04b4d --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/PetApi.cpp @@ -0,0 +1,418 @@ +#include "PetApi.h" + +using namespace Tiny; + + + + Response< + Pet + > + PetApi:: + addPet( + + Pet pet + + ) + { + std::string url = basepath + "/pet"; // + // Query | + // Headers | + // Form | + // Body | pet + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + + payload = pet.toJson().dump(); + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Pet obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + String + > + PetApi:: + deletePet( + + long petId + , + + std::string apiKey + + ) + { + std::string url = basepath + "/pet/{petId}"; //petId + // Query | + // Headers | apiKey + // Form | + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | DELETE + int httpCode = http.sendRequest("DELETE", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + std::list + > + PetApi:: + findPetsByStatus( + std::list status + + + ) + { + std::string url = basepath + "/pet/findByStatus"; // + // Query | status + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + std::list obj = std::list(); + bourne::json jsonPayload(output_string); + + + + + + + + + + for(auto& var : jsonPayload.array_range()) + { + Pet tmp(var.dump()); + obj.push_back(tmp); + } + + + + + + + + + Response> response(obj, httpCode); + return response; + } + + Response< + std::list + > + PetApi:: + findPetsByTags( + std::list tags + + + ) + { + std::string url = basepath + "/pet/findByTags"; // + // Query | tags + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + std::list obj = std::list(); + bourne::json jsonPayload(output_string); + + + + + + + + + + for(auto& var : jsonPayload.array_range()) + { + Pet tmp(var.dump()); + obj.push_back(tmp); + } + + + + + + + + + Response> response(obj, httpCode); + return response; + } + + Response< + Pet + > + PetApi:: + getPetById( + + long petId + + ) + { + std::string url = basepath + "/pet/{petId}"; //petId + // Query | + // Headers | + // Form | + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Pet obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + Pet + > + PetApi:: + updatePet( + + Pet pet + + ) + { + std::string url = basepath + "/pet"; // + // Query | + // Headers | + // Form | + // Body | pet + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | PUT + http.addHeader("Content-Type", "application/json"); + + + + payload = pet.toJson().dump(); + + int httpCode = http.sendRequest("PUT", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Pet obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + String + > + PetApi:: + updatePetWithForm( + + long petId + , + + std::string name + , + + std::string status + + ) + { + std::string url = basepath + "/pet/{petId}"; //petId + // Query | + // Headers | + // Form | name status + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + ApiResponse + > + PetApi:: + uploadFile( + + long petId + , + + std::string additionalMetadata + , + + std::string file + + ) + { + std::string url = basepath + "/pet/{petId}/uploadImage"; //petId + // Query | + // Headers | + // Form | additionalMetadata file + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + ApiResponse obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + + + diff --git a/samples/client/petstore/tiny/cpp/lib/service/PetApi.h b/samples/client/petstore/tiny/cpp/lib/service/PetApi.h new file mode 100644 index 000000000000..abcb0af0de90 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/PetApi.h @@ -0,0 +1,163 @@ +#ifndef TINY_CPP_CLIENT_PetApi_H_ +#define TINY_CPP_CLIENT_PetApi_H_ + + +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +#include "ApiResponse.h" +#include "Pet.h" + +namespace Tiny { + +/** + * Class + * Generated with openapi::tiny-cpp-client + */ + +class PetApi : public AbstractService { +public: + PetApi() = default; + + virtual ~PetApi() = default; + + /** + * Add a new pet to the store. + * + * + * \param pet Pet object that needs to be added to the store *Required* + */ + Response< + Pet + > + addPet( + + Pet pet + + ); + /** + * Deletes a pet. + * + * + * \param petId Pet id to delete *Required* + * \param apiKey + */ + Response< + String + > + deletePet( + + long petId + , + + std::string apiKey + + ); + /** + * Finds Pets by status. + * + * Multiple status values can be provided with comma separated strings + * \param status Status values that need to be considered for filter *Required* + */ + Response< + std::list + > + findPetsByStatus( + std::list status + + + ); + /** + * Finds Pets by tags. + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * \param tags Tags to filter by *Required* + */ + Response< + std::list + > + findPetsByTags( + std::list tags + + + ); + /** + * Find pet by ID. + * + * Returns a single pet + * \param petId ID of pet to return *Required* + */ + Response< + Pet + > + getPetById( + + long petId + + ); + /** + * Update an existing pet. + * + * + * \param pet Pet object that needs to be added to the store *Required* + */ + Response< + Pet + > + updatePet( + + Pet pet + + ); + /** + * Updates a pet in the store with form data. + * + * + * \param petId ID of pet that needs to be updated *Required* + * \param name Updated name of the pet + * \param status Updated status of the pet + */ + Response< + String + > + updatePetWithForm( + + long petId + , + + std::string name + , + + std::string status + + ); + /** + * uploads an image. + * + * + * \param petId ID of pet to update *Required* + * \param additionalMetadata Additional data to pass to server + * \param file file to upload + */ + Response< + ApiResponse + > + uploadFile( + + long petId + , + + std::string additionalMetadata + , + + std::string file + + ); +}; + +} + +#endif /* TINY_CPP_CLIENT_PetApi_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/tiny/cpp/lib/service/Response.h b/samples/client/petstore/tiny/cpp/lib/service/Response.h new file mode 100644 index 000000000000..9b7b616b8f1b --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/Response.h @@ -0,0 +1,25 @@ +#ifndef TINY_CPP_CLIENT_RESPONSE_H_ +#define TINY_CPP_CLIENT_RESPONSE_H_ +#include + +namespace Tiny { + +/** +* Class +* Generated with openapi::tiny-cpp-client +*/ +template + class Response { + public: + + Response(T _obj, int _code){ + obj = _obj; + code = _code; + } + + int code; + T obj; + }; + } // namespace Tinyclient + +#endif /* TINY_CPP_CLIENT_RESPONSE_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/service/StoreApi.cpp b/samples/client/petstore/tiny/cpp/lib/service/StoreApi.cpp new file mode 100644 index 000000000000..210eb8277ac6 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/StoreApi.cpp @@ -0,0 +1,185 @@ +#include "StoreApi.h" + +using namespace Tiny; + + + + Response< + String + > + StoreApi:: + deleteOrder( + + std::string orderId + + ) + { + std::string url = basepath + "/store/order/{orderId}"; //orderId + // Query | + // Headers | + // Form | + // Body | + + std::string s_orderId("{"); + s_orderId.append("orderId"); + s_orderId.append("}"); + + int pos = url.find(s_orderId); + + url.erase(pos, s_orderId.length()); + url.insert(pos, stringify(orderId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | DELETE + int httpCode = http.sendRequest("DELETE", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + StoreApi:: + getInventory( + ) + { + std::string url = basepath + "/store/inventory"; // + // Query | + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + //TODO: Implement map logic here + + + + + //TODO: No support for maps. + Response response(output, httpCode); + return response; + } + + Response< + Order + > + StoreApi:: + getOrderById( + + long orderId + + ) + { + std::string url = basepath + "/store/order/{orderId}"; //orderId + // Query | + // Headers | + // Form | + // Body | + + std::string s_orderId("{"); + s_orderId.append("orderId"); + s_orderId.append("}"); + + int pos = url.find(s_orderId); + + url.erase(pos, s_orderId.length()); + url.insert(pos, stringify(orderId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Order obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + Order + > + StoreApi:: + placeOrder( + + Order order + + ) + { + std::string url = basepath + "/store/order"; // + // Query | + // Headers | + // Form | + // Body | order + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + + payload = order.toJson().dump(); + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Order obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + + + diff --git a/samples/client/petstore/tiny/cpp/lib/service/StoreApi.h b/samples/client/petstore/tiny/cpp/lib/service/StoreApi.h new file mode 100644 index 000000000000..1bf0db023737 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/StoreApi.h @@ -0,0 +1,83 @@ +#ifndef TINY_CPP_CLIENT_StoreApi_H_ +#define TINY_CPP_CLIENT_StoreApi_H_ + + +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +#include +#include "Order.h" + +namespace Tiny { + +/** + * Class + * Generated with openapi::tiny-cpp-client + */ + +class StoreApi : public AbstractService { +public: + StoreApi() = default; + + virtual ~StoreApi() = default; + + /** + * Delete purchase order by ID. + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * \param orderId ID of the order that needs to be deleted *Required* + */ + Response< + String + > + deleteOrder( + + std::string orderId + + ); + /** + * Returns pet inventories by status. + * + * Returns a map of status codes to quantities + */ + Response< + String + > + getInventory( + ); + /** + * Find purchase order by ID. + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * \param orderId ID of pet that needs to be fetched *Required* + */ + Response< + Order + > + getOrderById( + + long orderId + + ); + /** + * Place an order for a pet. + * + * + * \param order order placed for purchasing the pet *Required* + */ + Response< + Order + > + placeOrder( + + Order order + + ); +}; + +} + +#endif /* TINY_CPP_CLIENT_StoreApi_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/tiny/cpp/lib/service/UserApi.cpp b/samples/client/petstore/tiny/cpp/lib/service/UserApi.cpp new file mode 100644 index 000000000000..d1cf12b80a9e --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/UserApi.cpp @@ -0,0 +1,366 @@ +#include "UserApi.h" + +using namespace Tiny; + + + + Response< + String + > + UserApi:: + createUser( + + User user + + ) + { + std::string url = basepath + "/user"; // + // Query | + // Headers | + // Form | + // Body | user + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + + payload = user.toJson().dump(); + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + createUsersWithArrayInput( + std::list user + + + ) + { + std::string url = basepath + "/user/createWithArray"; // + // Query | + // Headers | + // Form | + // Body | user + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + bourne::json tmp_arr = bourne::json::array(); + for(auto& var : user) + { + auto tmp = var.toJson(); + tmp_arr.append(tmp); + + } + payload = tmp_arr.dump(); + + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + createUsersWithListInput( + std::list user + + + ) + { + std::string url = basepath + "/user/createWithList"; // + // Query | + // Headers | + // Form | + // Body | user + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + bourne::json tmp_arr = bourne::json::array(); + for(auto& var : user) + { + auto tmp = var.toJson(); + tmp_arr.append(tmp); + + } + payload = tmp_arr.dump(); + + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + deleteUser( + + std::string username + + ) + { + std::string url = basepath + "/user/{username}"; //username + // Query | + // Headers | + // Form | + // Body | + + std::string s_username("{"); + s_username.append("username"); + s_username.append("}"); + + int pos = url.find(s_username); + + url.erase(pos, s_username.length()); + url.insert(pos, stringify(username)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | DELETE + int httpCode = http.sendRequest("DELETE", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + User + > + UserApi:: + getUserByName( + + std::string username + + ) + { + std::string url = basepath + "/user/{username}"; //username + // Query | + // Headers | + // Form | + // Body | + + std::string s_username("{"); + s_username.append("username"); + s_username.append("}"); + + int pos = url.find(s_username); + + url.erase(pos, s_username.length()); + url.insert(pos, stringify(username)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + User obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + std::string + > + UserApi:: + loginUser( + + std::string username + , + + std::string password + + ) + { + std::string url = basepath + "/user/login"; // + // Query | username password + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + bourne::json jsonPayload(output_string); + std::string obj; + jsonToValue(&obj, jsonPayload, "std::string"); + + + + Response response(obj, httpCode); + return response; + } + + Response< + String + > + UserApi:: + logoutUser( + ) + { + std::string url = basepath + "/user/logout"; // + // Query | + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + updateUser( + + std::string username + , + + User user + + ) + { + std::string url = basepath + "/user/{username}"; //username + // Query | + // Headers | + // Form | + // Body | user + + std::string s_username("{"); + s_username.append("username"); + s_username.append("}"); + + int pos = url.find(s_username); + + url.erase(pos, s_username.length()); + url.insert(pos, stringify(username)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | PUT + http.addHeader("Content-Type", "application/json"); + + + + payload = user.toJson().dump(); + + int httpCode = http.sendRequest("PUT", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + + + diff --git a/samples/client/petstore/tiny/cpp/lib/service/UserApi.h b/samples/client/petstore/tiny/cpp/lib/service/UserApi.h new file mode 100644 index 000000000000..afdaefa0f8c9 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/UserApi.h @@ -0,0 +1,147 @@ +#ifndef TINY_CPP_CLIENT_UserApi_H_ +#define TINY_CPP_CLIENT_UserApi_H_ + + +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +#include "User.h" +#include + +namespace Tiny { + +/** + * Class + * Generated with openapi::tiny-cpp-client + */ + +class UserApi : public AbstractService { +public: + UserApi() = default; + + virtual ~UserApi() = default; + + /** + * Create user. + * + * This can only be done by the logged in user. + * \param user Created user object *Required* + */ + Response< + String + > + createUser( + + User user + + ); + /** + * Creates list of users with given input array. + * + * + * \param user List of user object *Required* + */ + Response< + String + > + createUsersWithArrayInput( + std::list user + + + ); + /** + * Creates list of users with given input array. + * + * + * \param user List of user object *Required* + */ + Response< + String + > + createUsersWithListInput( + std::list user + + + ); + /** + * Delete user. + * + * This can only be done by the logged in user. + * \param username The name that needs to be deleted *Required* + */ + Response< + String + > + deleteUser( + + std::string username + + ); + /** + * Get user by user name. + * + * + * \param username The name that needs to be fetched. Use user1 for testing. *Required* + */ + Response< + User + > + getUserByName( + + std::string username + + ); + /** + * Logs user into the system. + * + * + * \param username The user name for login *Required* + * \param password The password for login in clear text *Required* + */ + Response< + std::string + > + loginUser( + + std::string username + , + + std::string password + + ); + /** + * Logs out current logged in user session. + * + * + */ + Response< + String + > + logoutUser( + ); + /** + * Updated user. + * + * This can only be done by the logged in user. + * \param username name that need to be deleted *Required* + * \param user Updated user object *Required* + */ + Response< + String + > + updateUser( + + std::string username + , + + User user + + ); +}; + +} + +#endif /* TINY_CPP_CLIENT_UserApi_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/tiny/cpp/platformio.ini b/samples/client/petstore/tiny/cpp/platformio.ini new file mode 100644 index 000000000000..00781178d10b --- /dev/null +++ b/samples/client/petstore/tiny/cpp/platformio.ini @@ -0,0 +1,7 @@ +[env:esp32] +platform = espressif32 +board = nodemcu-32s +framework = arduino +lib_deps = https://github.com/steinwurf/bourne.git +extra_scripts = pre_compiling_bourne.py + diff --git a/samples/client/petstore/tiny/cpp/pre_compiling_bourne.py b/samples/client/petstore/tiny/cpp/pre_compiling_bourne.py new file mode 100644 index 000000000000..96356dcdf158 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/pre_compiling_bourne.py @@ -0,0 +1,25 @@ +Import("env") + +## Compatibility for bourne to work on microcontrollers +# We insert '#define _GLIBCXX_USE_C99' in files that use std::stoll or std::to_string +def insert_c99_into(file): + import fileinput + + path = env['PROJECT_LIBDEPS_DIR'] + "/" + env['PIOENV'] + "/bourne/src/bourne/" + file + value = '#define _GLIBCXX_USE_C99 1\n' + + for line in fileinput.FileInput(path,inplace=1): + if line.startswith('#define _GLIBCXX_USE_C99'): + continue + elif line.startswith('// D'): + line=line.replace(line,line+value) + print(line, end='') + +def fix_parser(): + insert_c99_into('detail/parser.cpp') + +def fix_json(): + insert_c99_into('json.cpp') + +fix_parser() +fix_json() \ No newline at end of file diff --git a/samples/client/petstore/tiny/cpp/root.cert b/samples/client/petstore/tiny/cpp/root.cert new file mode 100644 index 000000000000..bad9c08efad1 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/root.cert @@ -0,0 +1,53 @@ +// TODO: Provide your service root certificate. +// Below is two examples of root certificates. + +// Let's encrypt root certificate +/** +"-----BEGIN CERTIFICATE-----\n" \ +"MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n" \ +"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" \ +"d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n" \ +"QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n" \ +"MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n" \ +"b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n" \ +"9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n" \ +"CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n" \ +"nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n" \ +"43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n" \ +"T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n" \ +"gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n" \ +"BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n" \ +"TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n" \ +"DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n" \ +"hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n" \ +"06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n" \ +"PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n" \ +"YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n" \ +"CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n" \ +"-----END CERTIFICATE-----\n" +*/ + +// Amazon_Root_CA_1.pem +/** +"-----BEGIN CERTIFICATE-----\n" \ +"MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\n" \ +"ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n" \ +"b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\n" \ +"MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\n" \ +"b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\n" \ +"ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\n" \ +"9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\n" \ +"IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\n" \ +"VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L\n" \ +"93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm\n" \ +"jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n" \ +"AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\n" \ +"A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\n" \ +"U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\n" \ +"N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv\n" \ +"o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\n" \ +"5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\n" \ +"rqXRfboQnoZsG4q5WTP468SQvvG5\n" \ +"-----END CERTIFICATE-----\n" \ +*/ + diff --git a/samples/client/petstore/tiny/cpp/src/main.cpp b/samples/client/petstore/tiny/cpp/src/main.cpp new file mode 100644 index 000000000000..34ba455fbdd3 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/src/main.cpp @@ -0,0 +1,37 @@ +#include "PetApi.h" + +const char* ssid = "your wifi name"; // TODO Change wifi name +const char* password = "Your wifi password"; //TODO Change wifi password + + +void setup(){ + //Initialize serial and wait for port to open: + Serial.begin(9600); + delay(100); + + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + WiFi.begin(ssid, password); + + // attempt to connect to Wifi network: + while (WiFi.status() != WL_CONNECTED) { + Serial.print("."); + // wait 1 second for re-trying + delay(1000); + } + + Serial.print("Connected to "); + Serial.println(ssid); + + //Print LAN IP. + Serial.print("IP address set: "); + Serial.println(WiFi.localIP()); + + Tiny::PetApi petapi; + auto resp = petapi.getPetById(10); + Serial.println(resp.code); + Tiny::Pet pet = resp.obj; + Serial.println(pet.toJson().dump().c_str()); +} + +void loop(){} diff --git a/samples/client/petstore/tiny/cpp/test/RunTests.cpp b/samples/client/petstore/tiny/cpp/test/RunTests.cpp new file mode 100644 index 000000000000..4caafb4ee441 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/test/RunTests.cpp @@ -0,0 +1,204 @@ + +#include "ApiResponseTest.cpp" + +#include "CategoryTest.cpp" + +#include "OrderTest.cpp" + +#include "PetTest.cpp" + +#include "TagTest.cpp" + +#include "UserTest.cpp" + + + +void setUp(){} + +void tearDown(){} + +void runTests(){ + + + RUN_TEST(test_ApiResponse_code_is_assigned_from_json); + + + RUN_TEST(test_ApiResponse_type_is_assigned_from_json); + + + RUN_TEST(test_ApiResponse_message_is_assigned_from_json); + + + + RUN_TEST(test_Category_id_is_assigned_from_json); + + + RUN_TEST(test_Category_name_is_assigned_from_json); + + + + RUN_TEST(test_Order_id_is_assigned_from_json); + + + RUN_TEST(test_Order_petId_is_assigned_from_json); + + + RUN_TEST(test_Order_quantity_is_assigned_from_json); + + + RUN_TEST(test_Order_shipDate_is_assigned_from_json); + + + RUN_TEST(test_Order_status_is_assigned_from_json); + + + RUN_TEST(test_Order_complete_is_assigned_from_json); + + + + RUN_TEST(test_Pet_id_is_assigned_from_json); + + + + RUN_TEST(test_Pet_name_is_assigned_from_json); + + + + + RUN_TEST(test_Pet_status_is_assigned_from_json); + + + + RUN_TEST(test_Tag_id_is_assigned_from_json); + + + RUN_TEST(test_Tag_name_is_assigned_from_json); + + + + RUN_TEST(test_User_id_is_assigned_from_json); + + + RUN_TEST(test_User_username_is_assigned_from_json); + + + RUN_TEST(test_User_firstName_is_assigned_from_json); + + + RUN_TEST(test_User_lastName_is_assigned_from_json); + + + RUN_TEST(test_User_email_is_assigned_from_json); + + + RUN_TEST(test_User_password_is_assigned_from_json); + + + RUN_TEST(test_User_phone_is_assigned_from_json); + + + RUN_TEST(test_User_userStatus_is_assigned_from_json); + + + + + + RUN_TEST(test_ApiResponse_code_is_converted_to_json); + + + RUN_TEST(test_ApiResponse_type_is_converted_to_json); + + + RUN_TEST(test_ApiResponse_message_is_converted_to_json); + + + + RUN_TEST(test_Category_id_is_converted_to_json); + + + RUN_TEST(test_Category_name_is_converted_to_json); + + + + RUN_TEST(test_Order_id_is_converted_to_json); + + + RUN_TEST(test_Order_petId_is_converted_to_json); + + + RUN_TEST(test_Order_quantity_is_converted_to_json); + + + RUN_TEST(test_Order_shipDate_is_converted_to_json); + + + RUN_TEST(test_Order_status_is_converted_to_json); + + + RUN_TEST(test_Order_complete_is_converted_to_json); + + + + RUN_TEST(test_Pet_id_is_converted_to_json); + + + + RUN_TEST(test_Pet_name_is_converted_to_json); + + + + + RUN_TEST(test_Pet_status_is_converted_to_json); + + + + RUN_TEST(test_Tag_id_is_converted_to_json); + + + RUN_TEST(test_Tag_name_is_converted_to_json); + + + + RUN_TEST(test_User_id_is_converted_to_json); + + + RUN_TEST(test_User_username_is_converted_to_json); + + + RUN_TEST(test_User_firstName_is_converted_to_json); + + + RUN_TEST(test_User_lastName_is_converted_to_json); + + + RUN_TEST(test_User_email_is_converted_to_json); + + + RUN_TEST(test_User_password_is_converted_to_json); + + + RUN_TEST(test_User_phone_is_converted_to_json); + + + RUN_TEST(test_User_userStatus_is_converted_to_json); + + + + +} + +int main(void) { + UNITY_BEGIN(); + runTests(); + return UNITY_END(); +} + +void setup() { + UNITY_BEGIN(); + runTests(); + UNITY_END(); +} + +void loop() { + +} diff --git a/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/default/configuration.ts index 38126642420d..6fc0f80d973f 100644 --- a/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/default/configuration.ts +++ b/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/default/configuration.ts @@ -61,7 +61,11 @@ export class Configuration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/with-npm/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/with-npm/configuration.ts b/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/with-npm/configuration.ts index 38126642420d..6fc0f80d973f 100644 --- a/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/with-npm/configuration.ts +++ b/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/with-npm/configuration.ts @@ -61,7 +61,11 @@ export class Configuration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/default/configuration.ts index 38126642420d..6fc0f80d973f 100644 --- a/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/default/configuration.ts +++ b/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/default/configuration.ts @@ -61,7 +61,11 @@ export class Configuration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/with-npm/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/with-npm/configuration.ts b/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/with-npm/configuration.ts index 38126642420d..6fc0f80d973f 100644 --- a/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/with-npm/configuration.ts +++ b/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/with-npm/configuration.ts @@ -61,7 +61,11 @@ export class Configuration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/configuration.ts index 38126642420d..6fc0f80d973f 100644 --- a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/configuration.ts +++ b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/configuration.ts @@ -61,7 +61,11 @@ export class Configuration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/configuration.ts b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/configuration.ts index 38126642420d..6fc0f80d973f 100644 --- a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/configuration.ts +++ b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/configuration.ts @@ -61,7 +61,11 @@ export class Configuration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/configuration.ts index 38126642420d..6fc0f80d973f 100644 --- a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/configuration.ts +++ b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/configuration.ts @@ -61,7 +61,11 @@ export class Configuration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/configuration.ts b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/configuration.ts index 38126642420d..6fc0f80d973f 100644 --- a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/configuration.ts +++ b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/configuration.ts @@ -61,7 +61,11 @@ export class Configuration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/configuration.ts index 38126642420d..6fc0f80d973f 100644 --- a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/configuration.ts +++ b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/configuration.ts @@ -61,7 +61,11 @@ export class Configuration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/configuration.ts b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/configuration.ts index 38126642420d..6fc0f80d973f 100644 --- a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/configuration.ts +++ b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/configuration.ts @@ -61,7 +61,11 @@ export class Configuration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/configuration.ts index 38126642420d..6fc0f80d973f 100644 --- a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/configuration.ts +++ b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/configuration.ts @@ -61,7 +61,11 @@ export class Configuration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/configuration.ts b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/configuration.ts index 38126642420d..6fc0f80d973f 100644 --- a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/configuration.ts +++ b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/configuration.ts @@ -61,7 +61,11 @@ export class Configuration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/configuration.ts b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/configuration.ts index 38126642420d..6fc0f80d973f 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/configuration.ts +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/configuration.ts @@ -61,7 +61,11 @@ export class Configuration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/configuration.ts b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/configuration.ts index 38126642420d..6fc0f80d973f 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/configuration.ts +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/configuration.ts @@ -61,7 +61,11 @@ export class Configuration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/configuration.ts b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/configuration.ts index 1bd306a523eb..900c26d8ebfe 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/configuration.ts +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/configuration.ts @@ -61,7 +61,11 @@ export class PetStoreConfiguration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/configuration.ts index 38126642420d..6fc0f80d973f 100644 --- a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/configuration.ts +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/configuration.ts @@ -61,7 +61,11 @@ export class Configuration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/default/configuration.ts index 38126642420d..6fc0f80d973f 100644 --- a/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/default/configuration.ts +++ b/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/default/configuration.ts @@ -61,7 +61,11 @@ export class Configuration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/with-npm/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/with-npm/configuration.ts b/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/with-npm/configuration.ts index 38126642420d..6fc0f80d973f 100644 --- a/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/with-npm/configuration.ts +++ b/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/with-npm/configuration.ts @@ -61,7 +61,11 @@ export class Configuration { // init default api_key credential if (!this.credentials['api_key']) { this.credentials['api_key'] = () => { - return this.apiKeys['api_key'] || this.apiKeys['api_key']; + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } }; } diff --git a/samples/client/petstore/typescript-aurelia/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-aurelia/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-aurelia/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-aurelia/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/composed-schemas/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/composed-schemas/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-axios/builds/composed-schemas/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/composed-schemas/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-axios/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/default/api.ts b/samples/client/petstore/typescript-axios/builds/default/api.ts index 856fb0a48298..0ce81cf11744 100644 --- a/samples/client/petstore/typescript-axios/builds/default/api.ts +++ b/samples/client/petstore/typescript-axios/builds/default/api.ts @@ -383,6 +383,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags: async (tags: Array, options: any = {}): Promise => { @@ -649,6 +650,7 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ async findPetsByTags(tags: Array, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { @@ -749,6 +751,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags(tags: Array, options?: any): AxiosPromise> { @@ -850,6 +853,7 @@ export class PetApi extends BaseAPI { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApi */ diff --git a/samples/client/petstore/typescript-axios/builds/es6-target/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/es6-target/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-axios/builds/es6-target/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/es6-target/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/es6-target/api.ts b/samples/client/petstore/typescript-axios/builds/es6-target/api.ts index 856fb0a48298..0ce81cf11744 100644 --- a/samples/client/petstore/typescript-axios/builds/es6-target/api.ts +++ b/samples/client/petstore/typescript-axios/builds/es6-target/api.ts @@ -383,6 +383,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags: async (tags: Array, options: any = {}): Promise => { @@ -649,6 +650,7 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ async findPetsByTags(tags: Array, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { @@ -749,6 +751,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags(tags: Array, options?: any): AxiosPromise> { @@ -850,6 +853,7 @@ export class PetApi extends BaseAPI { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApi */ diff --git a/samples/client/petstore/typescript-axios/builds/with-complex-headers/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/with-complex-headers/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-axios/builds/with-complex-headers/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/with-complex-headers/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/with-complex-headers/api.ts b/samples/client/petstore/typescript-axios/builds/with-complex-headers/api.ts index 85c32a979e2d..15fa56e5e78b 100644 --- a/samples/client/petstore/typescript-axios/builds/with-complex-headers/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-complex-headers/api.ts @@ -394,6 +394,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags: async (tags: Array, options: any = {}): Promise => { @@ -662,6 +663,7 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ async findPetsByTags(tags: Array, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { @@ -764,6 +766,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags(tags: Array, options?: any): AxiosPromise> { @@ -867,6 +870,7 @@ export class PetApi extends BaseAPI { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApi */ diff --git a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts index 44ad2dc5a0a3..c9fba6a5167f 100644 --- a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts @@ -1961,7 +1961,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) } if (enumFormStringArray) { - localVarFormParams.set(enumFormStringArray.join(COLLECTION_FORMATS.csv)); + localVarFormParams.set('enum_form_string_array', enumFormStringArray.join(COLLECTION_FORMATS.csv)); } @@ -3089,6 +3089,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags: async (tags: Array, options: any = {}): Promise => { @@ -3413,6 +3414,7 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ async findPetsByTags(tags: Array, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { @@ -3526,6 +3528,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags(tags: Array, options?: any): AxiosPromise> { @@ -3639,6 +3642,7 @@ export class PetApi extends BaseAPI { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApi */ diff --git a/samples/client/petstore/typescript-axios/builds/with-interfaces/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/with-interfaces/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-axios/builds/with-interfaces/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/with-interfaces/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts b/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts index 0368b1d57036..c6cda5b65033 100644 --- a/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts @@ -383,6 +383,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags: async (tags: Array, options: any = {}): Promise => { @@ -649,6 +650,7 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ async findPetsByTags(tags: Array, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { @@ -749,6 +751,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags(tags: Array, options?: any): AxiosPromise> { @@ -843,6 +846,7 @@ export interface PetApiInterface { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApiInterface */ @@ -943,6 +947,7 @@ export class PetApi extends BaseAPI implements PetApiInterface { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApi */ diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/pet-api.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/pet-api.ts index fc66c5184fab..03545d554fcf 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/pet-api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/pet-api.ts @@ -159,6 +159,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags: async (tags: Array, options: any = {}): Promise => { @@ -425,6 +426,7 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ async findPetsByTags(tags: Array, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { @@ -525,6 +527,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags(tags: Array, options?: any): AxiosPromise> { @@ -626,6 +629,7 @@ export class PetApi extends BaseAPI { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApi */ diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/with-npm-version/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version/api.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version/api.ts index 856fb0a48298..0ce81cf11744 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version/api.ts @@ -383,6 +383,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags: async (tags: Array, options: any = {}): Promise => { @@ -649,6 +650,7 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ async findPetsByTags(tags: Array, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { @@ -749,6 +751,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags(tags: Array, options?: any): AxiosPromise> { @@ -850,6 +853,7 @@ export class PetApi extends BaseAPI { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApi */ diff --git a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/api.ts b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/api.ts index ec1563347136..1f8764baaf07 100644 --- a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/api.ts @@ -383,6 +383,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags: async (tags: Array, options: any = {}): Promise => { @@ -649,6 +650,7 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ async findPetsByTags(tags: Array, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { @@ -749,6 +751,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags(tags: Array, options?: any): AxiosPromise> { @@ -996,6 +999,7 @@ export class PetApi extends BaseAPI { * @summary Finds Pets by tags * @param {PetApiFindPetsByTagsRequest} requestParameters Request parameters. * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApi */ diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/default-v3.0/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/apis/FakeApi.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/apis/FakeApi.ts index 358d9a5b09bb..5985139ab238 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/apis/FakeApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/apis/FakeApi.ts @@ -64,6 +64,10 @@ export interface FakePropertyEnumIntegerSerializeRequest { outerObjectWithEnumProperty: OuterObjectWithEnumProperty; } +export interface TestBodyWithBinaryRequest { + body: Blob | null; +} + export interface TestBodyWithFileSchemaRequest { fileSchemaTestClass: FileSchemaTestClass; } @@ -352,7 +356,39 @@ export class FakeApi extends runtime.BaseAPI { } /** - * For this test, the body for this request much reference a schema named `File`. + * For this test, the body has to be a binary file. + */ + async testBodyWithBinaryRaw(requestParameters: TestBodyWithBinaryRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling testBodyWithBinary.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'image/png'; + + const response = await this.request({ + path: `/fake/body-with-binary`, + method: 'PUT', + headers: headerParameters, + query: queryParameters, + body: requestParameters.body as any, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * For this test, the body has to be a binary file. + */ + async testBodyWithBinary(requestParameters: TestBodyWithBinaryRequest): Promise { + await this.testBodyWithBinaryRaw(requestParameters); + } + + /** + * For this test, the body for this request must reference a schema named `File`. */ async testBodyWithFileSchemaRaw(requestParameters: TestBodyWithFileSchemaRequest): Promise> { if (requestParameters.fileSchemaTestClass === null || requestParameters.fileSchemaTestClass === undefined) { @@ -377,7 +413,7 @@ export class FakeApi extends runtime.BaseAPI { } /** - * For this test, the body for this request much reference a schema named `File`. + * For this test, the body for this request must reference a schema named `File`. */ async testBodyWithFileSchema(requestParameters: TestBodyWithFileSchemaRequest): Promise { await this.testBodyWithFileSchemaRaw(requestParameters); @@ -835,7 +871,7 @@ export class FakeApi extends runtime.BaseAPI { const queryParameters: any = {}; if (requestParameters.pipe) { - queryParameters['pipe'] = requestParameters.pipe; + queryParameters['pipe'] = requestParameters.pipe.join(runtime.COLLECTION_FORMATS["pipes"]); } if (requestParameters.ioutil) { diff --git a/samples/client/petstore/typescript-fetch/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/enum/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/enum/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-fetch/builds/enum/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/enum/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/es6-target/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/with-interfaces/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/with-interfaces/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-interfaces/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/with-npm-version/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-inversify/.openapi-generator/VERSION b/samples/client/petstore/typescript-inversify/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-inversify/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-inversify/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-jquery/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-jquery/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-jquery/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-jquery/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-jquery/npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-jquery/npm/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-jquery/npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-jquery/npm/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-nestjs-v6-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-nestjs-v6-provided-in-root/builds/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-nestjs-v6-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-nestjs-v6-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-node/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-node/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-node/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-node/npm/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-node/npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-node/npm/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/npm/package.json b/samples/client/petstore/typescript-node/npm/package.json index 0ff014f766ae..2bab750c5bab 100644 --- a/samples/client/petstore/typescript-node/npm/package.json +++ b/samples/client/petstore/typescript-node/npm/package.json @@ -15,7 +15,7 @@ "dependencies": { "bluebird": "^3.5.0", "request": "^2.81.0", - "@types/bluebird": "*", + "@types/bluebird": "3.5.33", "@types/request": "*", "rewire": "^3.0.2" }, diff --git a/samples/client/petstore/typescript-redux-query/builds/with-npm-version/.openapi-generator/VERSION b/samples/client/petstore/typescript-redux-query/builds/with-npm-version/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-redux-query/builds/with-npm-version/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-redux-query/builds/with-npm-version/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-rxjs/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-rxjs/builds/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-rxjs/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-rxjs/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-rxjs/builds/es6-target/.openapi-generator/VERSION b/samples/client/petstore/typescript-rxjs/builds/es6-target/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-rxjs/builds/es6-target/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-rxjs/builds/es6-target/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-rxjs/builds/with-npm-version/.openapi-generator/VERSION b/samples/client/petstore/typescript-rxjs/builds/with-npm-version/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-rxjs/builds/with-npm-version/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-rxjs/builds/with-npm-version/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-rxjs/builds/with-progress-subscriber/.openapi-generator/VERSION b/samples/client/petstore/typescript-rxjs/builds/with-progress-subscriber/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/client/petstore/typescript-rxjs/builds/with-progress-subscriber/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-rxjs/builds/with-progress-subscriber/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/config/petstore/protobuf-schema/.openapi-generator/VERSION b/samples/config/petstore/protobuf-schema/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/config/petstore/protobuf-schema/.openapi-generator/VERSION +++ b/samples/config/petstore/protobuf-schema/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/meta-codegen/lib/pom.xml b/samples/meta-codegen/lib/pom.xml index 7a28653feaa4..3132601fc90c 100644 --- a/samples/meta-codegen/lib/pom.xml +++ b/samples/meta-codegen/lib/pom.xml @@ -121,7 +121,7 @@ UTF-8 - 5.1.1-SNAPSHOT + 5.2.0-SNAPSHOT 1.0.0 4.8.1 diff --git a/samples/meta-codegen/usage/.openapi-generator/VERSION b/samples/meta-codegen/usage/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/meta-codegen/usage/.openapi-generator/VERSION +++ b/samples/meta-codegen/usage/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/meta-codegen/usage/src/org/openapitools/api/PetApi.sample b/samples/meta-codegen/usage/src/org/openapitools/api/PetApi.sample index e75a6149341a..7b8b9c754d9f 100644 --- a/samples/meta-codegen/usage/src/org/openapitools/api/PetApi.sample +++ b/samples/meta-codegen/usage/src/org/openapitools/api/PetApi.sample @@ -16,7 +16,7 @@ classname: PetApi operationId: addPet # and parameters: -body: Pet +pet: Pet # each operation has an `operationId`: @@ -52,7 +52,7 @@ petId: Long operationId: updatePet # and parameters: -body: Pet +pet: Pet # each operation has an `operationId`: diff --git a/samples/meta-codegen/usage/src/org/openapitools/api/StoreApi.sample b/samples/meta-codegen/usage/src/org/openapitools/api/StoreApi.sample index 298e7edbb0fd..d66c28e85762 100644 --- a/samples/meta-codegen/usage/src/org/openapitools/api/StoreApi.sample +++ b/samples/meta-codegen/usage/src/org/openapitools/api/StoreApi.sample @@ -36,7 +36,7 @@ orderId: String operationId: placeOrder # and parameters: -body: Order +order: Order # end of operations block diff --git a/samples/meta-codegen/usage/src/org/openapitools/api/UserApi.sample b/samples/meta-codegen/usage/src/org/openapitools/api/UserApi.sample index ebc744ed975e..b3b05217530a 100644 --- a/samples/meta-codegen/usage/src/org/openapitools/api/UserApi.sample +++ b/samples/meta-codegen/usage/src/org/openapitools/api/UserApi.sample @@ -16,21 +16,21 @@ classname: UserApi operationId: createUser # and parameters: -body: User +user: User # each operation has an `operationId`: operationId: createUsersWithArrayInput # and parameters: -body: List +user: List # each operation has an `operationId`: operationId: createUsersWithListInput # and parameters: -body: List +user: List # each operation has an `operationId`: @@ -66,7 +66,7 @@ operationId: updateUser # and parameters: username: String -body: User +user: User # end of operations block diff --git a/samples/openapi3/client/elm/.openapi-generator/VERSION b/samples/openapi3/client/elm/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/elm/.openapi-generator/VERSION +++ b/samples/openapi3/client/elm/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/VERSION b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/VERSION +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/VERSION b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/VERSION +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/.openapi-generator/VERSION b/samples/openapi3/client/extensions/x-auth-id-alias/python/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/python/.openapi-generator/VERSION +++ b/samples/openapi3/client/extensions/x-auth-id-alias/python/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/model_utils.py b/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/model_utils.py index 55b99827e5e7..bd30ebabb27f 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/model_utils.py +++ b/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/model_utils.py @@ -29,6 +29,22 @@ file_type = io.IOBase +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(_self, *args, **kwargs): + """ + An attribute named `self` received from the api will conflicts with the reserved `self` + parameter of a class method. During generation, `self` attributes are mapped + to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. + """ + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python(kwargs, _self if isinstance(_self, type) else _self.__class__) + return fn(_self, *args, **kwargs) + return wrapped_init + + class cached_property(object): # this caches the result of the function call for fn with no inputs # use this as a decorator on fuction methods that you want converted @@ -284,6 +300,121 @@ def __new__(cls, *args, **kwargs): return new_inst + @classmethod + @convert_js_args_to_python_args + def _new_from_openapi_data(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return cls._from_openapi_data(*args, **kwargs) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return cls._from_openapi_data(*args, **kwargs) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = cls._from_openapi_data(*args, **kwargs) + + + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + return new_inst + + class ModelSimple(OpenApiModel): """the parent class of models whose type != object in their swagger/openapi""" @@ -434,27 +565,43 @@ def __setitem__(self, name, value): self.__dict__[name] = value return - # set the attribute on the correct instance - model_instances = self._var_name_to_model_instances.get( - name, self._additional_properties_model_instances) - if model_instances: - for model_instance in model_instances: - if model_instance == self: - self.set_attribute(name, value) - else: - setattr(model_instance, name, value) - if name not in self._var_name_to_model_instances: - # we assigned an additional property - self.__dict__['_var_name_to_model_instances'][name] = ( - model_instance - ) - return None - - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) + """ + Use cases: + 1. additional_properties_type is None (additionalProperties == False in spec) + Check for property presence in self.openapi_types + if not present then throw an error + if present set in self, set attribute + always set on composed schemas + 2. additional_properties_type exists + set attribute on self + always set on composed schemas + """ + if self.additional_properties_type is None: + """ + For an attribute to exist on a composed schema it must: + - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND + - fulfill schema_requirements in each oneOf/anyOf/allOf schemas + + schema_requirements: + For an attribute to exist on a schema it must: + - be present in properties at the schema OR + - have additionalProperties unset (defaults additionalProperties = any type) OR + - have additionalProperties set + """ + if name not in self.openapi_types: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + # attribute must be set on self and composed instances + self.set_attribute(name, value) + for model_instance in self._composed_instances: + setattr(model_instance, name, value) + if name not in self._var_name_to_model_instances: + # we assigned an additional property + self.__dict__['_var_name_to_model_instances'][name] = self._composed_instances + [self] + return None __unset_attribute_value__ = object() @@ -464,13 +611,12 @@ def get(self, name, default=None): return self.__dict__[name] # get the attribute from the correct instance - model_instances = self._var_name_to_model_instances.get( - name, self._additional_properties_model_instances) + model_instances = self._var_name_to_model_instances.get(name) values = [] - # A composed model stores child (oneof/anyOf/allOf) models under - # self._var_name_to_model_instances. A named property can exist in - # multiple child models. If the property is present in more than one - # child model, the value must be the same across all the child models. + # A composed model stores self and child (oneof/anyOf/allOf) models under + # self._var_name_to_model_instances. + # Any property must exist in self and all model instances + # The value stored in all model instances must be the same if model_instances: for model_instance in model_instances: if name in model_instance._data_store: @@ -1193,14 +1339,14 @@ def deserialize_model(model_data, model_class, path_to_item, check_type, _spec_property_naming=spec_property_naming) if issubclass(model_class, ModelSimple): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) elif isinstance(model_data, list): - return model_class(*model_data, **kw_args) + return model_class._new_from_openapi_data(*model_data, **kw_args) if isinstance(model_data, dict): kw_args.update(model_data) - return model_class(**kw_args) + return model_class._new_from_openapi_data(**kw_args) elif isinstance(model_data, PRIMITIVE_TYPES): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) def deserialize_file(response_data, configuration, content_disposition=None): @@ -1486,12 +1632,20 @@ def model_to_dict(model_instance, serialize=True): model_instances = [model_instance] if model_instance._composed_schemas: model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} for model_instance in model_instances: for attr, value in model_instance._data_store.items(): if serialize: # we use get here because additional property key names do not # exist in attribute_map - attr = model_instance.attribute_map.get(attr, attr) + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) if isinstance(value, list): if not value: # empty list or None @@ -1519,6 +1673,16 @@ def model_to_dict(model_instance, serialize=True): result[attr] = model_to_dict(value, serialize=serialize) else: result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] return result @@ -1562,30 +1726,19 @@ def get_valid_classes_phrase(input_classes): return "is one of [{0}]".format(", ".join(all_class_names)) -def convert_js_args_to_python_args(fn): - from functools import wraps - @wraps(fn) - def wrapped_init(_self, *args, **kwargs): - """ - An attribute named `self` received from the api will conflicts with the reserved `self` - parameter of a class method. During generation, `self` attributes are mapped - to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. - """ - spec_property_naming = kwargs.get('_spec_property_naming', False) - if spec_property_naming: - kwargs = change_keys_js_to_python(kwargs, _self.__class__) - return fn(_self, *args, **kwargs) - return wrapped_init - - def get_allof_instances(self, model_args, constant_args): """ Args: self: the class we are handling model_args (dict): var_name to var_value used to make instances - constant_args (dict): var_name to var_value - used to make instances + constant_args (dict): + metadata arguments: + _check_type + _path_to_item + _spec_property_naming + _configuration + _visited_composed_classes Returns composed_instances (list) @@ -1593,20 +1746,8 @@ def get_allof_instances(self, model_args, constant_args): composed_instances = [] for allof_class in self._composed_schemas['allOf']: - # no need to handle changing js keys to python because - # for composed schemas, allof parameters are included in the - # composed schema and were changed to python keys in __new__ - # extract a dict of only required keys from fixed_model_args - kwargs = {} - var_names = set(allof_class.openapi_types.keys()) - for var_name in var_names: - if var_name in model_args: - kwargs[var_name] = model_args[var_name] - - # and use it to make the instance - kwargs.update(constant_args) try: - allof_instance = allof_class(**kwargs) + allof_instance = allof_class(**model_args, **constant_args) composed_instances.append(allof_instance) except Exception as ex: raise ApiValueError( @@ -1666,31 +1807,9 @@ def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): single_value_input = allows_single_value_input(oneof_class) - if not single_value_input: - # transform js keys from input data to python keys in fixed_model_args - fixed_model_args = change_keys_js_to_python( - model_kwargs, oneof_class) - - # Extract a dict with the properties that are declared in the oneOf schema. - # Undeclared properties (e.g. properties that are allowed because of the - # additionalProperties attribute in the OAS document) are not added to - # the dict. - kwargs = {} - var_names = set(oneof_class.openapi_types.keys()) - for var_name in var_names: - if var_name in fixed_model_args: - kwargs[var_name] = fixed_model_args[var_name] - - # do not try to make a model with no input args - if len(kwargs) == 0: - continue - - # and use it to make the instance - kwargs.update(constant_kwargs) - try: if not single_value_input: - oneof_instance = oneof_class(**kwargs) + oneof_instance = oneof_class(**model_kwargs, **constant_kwargs) else: if issubclass(oneof_class, ModelSimple): oneof_instance = oneof_class(model_arg, **constant_kwargs) @@ -1747,24 +1866,8 @@ def get_anyof_instances(self, model_args, constant_args): # none_type deserialization is handled in the __new__ method continue - # transform js keys to python keys in fixed_model_args - fixed_model_args = change_keys_js_to_python(model_args, anyof_class) - - # extract a dict of only required keys from these_model_vars - kwargs = {} - var_names = set(anyof_class.openapi_types.keys()) - for var_name in var_names: - if var_name in fixed_model_args: - kwargs[var_name] = fixed_model_args[var_name] - - # do not try to make a model with no input args - if len(kwargs) == 0: - continue - - # and use it to make the instance - kwargs.update(constant_args) try: - anyof_instance = anyof_class(**kwargs) + anyof_instance = anyof_class(**model_args, **constant_args) anyof_instances.append(anyof_instance) except Exception: pass @@ -1777,47 +1880,34 @@ def get_anyof_instances(self, model_args, constant_args): return anyof_instances -def get_additional_properties_model_instances( - composed_instances, self): - additional_properties_model_instances = [] - all_instances = [self] - all_instances.extend(composed_instances) - for instance in all_instances: - if instance.additional_properties_type is not None: - additional_properties_model_instances.append(instance) - return additional_properties_model_instances - - -def get_var_name_to_model_instances(self, composed_instances): - var_name_to_model_instances = {} - all_instances = [self] - all_instances.extend(composed_instances) - for instance in all_instances: - for var_name in instance.openapi_types: - if var_name not in var_name_to_model_instances: - var_name_to_model_instances[var_name] = [instance] - else: - var_name_to_model_instances[var_name].append(instance) - return var_name_to_model_instances - - -def get_unused_args(self, composed_instances, model_args): - unused_args = dict(model_args) - # arguments apssed to self were already converted to python names +def get_discarded_args(self, composed_instances, model_args): + """ + Gathers the args that were discarded by configuration.discard_unknown_keys + """ + model_arg_keys = model_args.keys() + discarded_args = set() + # arguments passed to self were already converted to python names # before __init__ was called - for var_name_py in self.attribute_map: - if var_name_py in unused_args: - del unused_args[var_name_py] for instance in composed_instances: if instance.__class__ in self._composed_schemas['allOf']: - for var_name_py in instance.attribute_map: - if var_name_py in unused_args: - del unused_args[var_name_py] + try: + keys = instance.to_dict().keys() + discarded_keys = model_args - keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass else: - for var_name_js in instance.attribute_map.values(): - if var_name_js in unused_args: - del unused_args[var_name_js] - return unused_args + try: + all_keys = set(model_to_dict(instance, serialize=False).keys()) + js_keys = model_to_dict(instance, serialize=True).keys() + all_keys.update(js_keys) + discarded_keys = model_arg_keys - all_keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass + return discarded_args def validate_get_composed_info(constant_args, model_args, self): @@ -1861,36 +1951,42 @@ def validate_get_composed_info(constant_args, model_args, self): composed_instances.append(oneof_instance) anyof_instances = get_anyof_instances(self, model_args, constant_args) composed_instances.extend(anyof_instances) + """ + set additional_properties_model_instances + additional properties must be evaluated at the schema level + so self's additional properties are most important + If self is a composed schema with: + - no properties defined in self + - additionalProperties: False + Then for object payloads every property is an additional property + and they are not allowed, so only empty dict is allowed + + Properties must be set on all matching schemas + so when a property is assigned toa composed instance, it must be set on all + composed instances regardless of additionalProperties presence + keeping it to prevent breaking changes in v5.0.1 + TODO remove cls._additional_properties_model_instances in 6.0.0 + """ + additional_properties_model_instances = [] + if self.additional_properties_type is not None: + additional_properties_model_instances = [self] - # map variable names to composed_instances - var_name_to_model_instances = get_var_name_to_model_instances( - self, composed_instances) - - # set additional_properties_model_instances - additional_properties_model_instances = ( - get_additional_properties_model_instances(composed_instances, self) - ) - - # set any remaining values - unused_args = get_unused_args(self, composed_instances, model_args) - if len(unused_args) > 0 and \ - len(additional_properties_model_instances) == 0 and \ - (self._configuration is None or - not self._configuration.discard_unknown_keys): - raise ApiValueError( - "Invalid input arguments input when making an instance of " - "class %s. Not all inputs were used. The unused input data " - "is %s" % (self.__class__.__name__, unused_args) - ) + """ + no need to set properties on self in here, they will be set in __init__ + By here all composed schema oneOf/anyOf/allOf instances have their properties set using + model_args + """ + discarded_args = get_discarded_args(self, composed_instances, model_args) - # no need to add additional_properties to var_name_to_model_instances here - # because additional_properties_model_instances will direct us to that - # instance when we use getattr or setattr - # and we update var_name_to_model_instances in setattr + # map variable names to composed_instances + var_name_to_model_instances = {} + for prop_name in model_args: + if prop_name not in discarded_args: + var_name_to_model_instances[prop_name] = [self] + composed_instances return [ composed_instances, var_name_to_model_instances, additional_properties_model_instances, - unused_args + discarded_args ] diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/VERSION b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/VERSION +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias.rb index 57f6fbbec4a3..e0d70e377a4d 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api/usage_api.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api/usage_api.rb index dea64fcd53a6..e150a0f673f3 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api/usage_api.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api/usage_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_client.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_client.rb index bafd7c3ddc9e..dceb19bdb223 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_client.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_error.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_error.rb index 75a7eb7cff54..3984528e045e 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_error.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_error.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/configuration.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/configuration.rb index 1a79bce664cf..65f2cfea56a5 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/configuration.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/configuration.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/version.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/version.rb index a58259effb73..80e58dd211a7 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/version.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/version.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/api_client_spec.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/api_client_spec.rb index de6667830496..0b4502a11c8b 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/api_client_spec.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/api_client_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/configuration_spec.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/configuration_spec.rb index 59fbe08f126a..df8bb818aa76 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/configuration_spec.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/configuration_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/spec_helper.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/spec_helper.rb index c800de0f9b78..ae5d77411e26 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/spec_helper.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/spec_helper.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/x_auth_id_alias.gemspec b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/x_auth_id_alias.gemspec index bbd905db7d61..0b5caba0e8bd 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/x_auth_id_alias.gemspec +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/x_auth_id_alias.gemspec @@ -8,7 +8,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/dynamic-servers/python/.openapi-generator/VERSION b/samples/openapi3/client/features/dynamic-servers/python/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/.openapi-generator/VERSION +++ b/samples/openapi3/client/features/dynamic-servers/python/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/model_utils.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/model_utils.py index fb914b5b8f2f..c73de2486818 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/model_utils.py +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/model_utils.py @@ -29,6 +29,22 @@ file_type = io.IOBase +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(_self, *args, **kwargs): + """ + An attribute named `self` received from the api will conflicts with the reserved `self` + parameter of a class method. During generation, `self` attributes are mapped + to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. + """ + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python(kwargs, _self if isinstance(_self, type) else _self.__class__) + return fn(_self, *args, **kwargs) + return wrapped_init + + class cached_property(object): # this caches the result of the function call for fn with no inputs # use this as a decorator on fuction methods that you want converted @@ -284,6 +300,121 @@ def __new__(cls, *args, **kwargs): return new_inst + @classmethod + @convert_js_args_to_python_args + def _new_from_openapi_data(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return cls._from_openapi_data(*args, **kwargs) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return cls._from_openapi_data(*args, **kwargs) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = cls._from_openapi_data(*args, **kwargs) + + + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + return new_inst + + class ModelSimple(OpenApiModel): """the parent class of models whose type != object in their swagger/openapi""" @@ -434,27 +565,43 @@ def __setitem__(self, name, value): self.__dict__[name] = value return - # set the attribute on the correct instance - model_instances = self._var_name_to_model_instances.get( - name, self._additional_properties_model_instances) - if model_instances: - for model_instance in model_instances: - if model_instance == self: - self.set_attribute(name, value) - else: - setattr(model_instance, name, value) - if name not in self._var_name_to_model_instances: - # we assigned an additional property - self.__dict__['_var_name_to_model_instances'][name] = ( - model_instance - ) - return None - - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) + """ + Use cases: + 1. additional_properties_type is None (additionalProperties == False in spec) + Check for property presence in self.openapi_types + if not present then throw an error + if present set in self, set attribute + always set on composed schemas + 2. additional_properties_type exists + set attribute on self + always set on composed schemas + """ + if self.additional_properties_type is None: + """ + For an attribute to exist on a composed schema it must: + - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND + - fulfill schema_requirements in each oneOf/anyOf/allOf schemas + + schema_requirements: + For an attribute to exist on a schema it must: + - be present in properties at the schema OR + - have additionalProperties unset (defaults additionalProperties = any type) OR + - have additionalProperties set + """ + if name not in self.openapi_types: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + # attribute must be set on self and composed instances + self.set_attribute(name, value) + for model_instance in self._composed_instances: + setattr(model_instance, name, value) + if name not in self._var_name_to_model_instances: + # we assigned an additional property + self.__dict__['_var_name_to_model_instances'][name] = self._composed_instances + [self] + return None __unset_attribute_value__ = object() @@ -464,13 +611,12 @@ def get(self, name, default=None): return self.__dict__[name] # get the attribute from the correct instance - model_instances = self._var_name_to_model_instances.get( - name, self._additional_properties_model_instances) + model_instances = self._var_name_to_model_instances.get(name) values = [] - # A composed model stores child (oneof/anyOf/allOf) models under - # self._var_name_to_model_instances. A named property can exist in - # multiple child models. If the property is present in more than one - # child model, the value must be the same across all the child models. + # A composed model stores self and child (oneof/anyOf/allOf) models under + # self._var_name_to_model_instances. + # Any property must exist in self and all model instances + # The value stored in all model instances must be the same if model_instances: for model_instance in model_instances: if name in model_instance._data_store: @@ -1193,14 +1339,14 @@ def deserialize_model(model_data, model_class, path_to_item, check_type, _spec_property_naming=spec_property_naming) if issubclass(model_class, ModelSimple): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) elif isinstance(model_data, list): - return model_class(*model_data, **kw_args) + return model_class._new_from_openapi_data(*model_data, **kw_args) if isinstance(model_data, dict): kw_args.update(model_data) - return model_class(**kw_args) + return model_class._new_from_openapi_data(**kw_args) elif isinstance(model_data, PRIMITIVE_TYPES): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) def deserialize_file(response_data, configuration, content_disposition=None): @@ -1486,12 +1632,20 @@ def model_to_dict(model_instance, serialize=True): model_instances = [model_instance] if model_instance._composed_schemas: model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} for model_instance in model_instances: for attr, value in model_instance._data_store.items(): if serialize: # we use get here because additional property key names do not # exist in attribute_map - attr = model_instance.attribute_map.get(attr, attr) + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) if isinstance(value, list): if not value: # empty list or None @@ -1519,6 +1673,16 @@ def model_to_dict(model_instance, serialize=True): result[attr] = model_to_dict(value, serialize=serialize) else: result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] return result @@ -1562,30 +1726,19 @@ def get_valid_classes_phrase(input_classes): return "is one of [{0}]".format(", ".join(all_class_names)) -def convert_js_args_to_python_args(fn): - from functools import wraps - @wraps(fn) - def wrapped_init(_self, *args, **kwargs): - """ - An attribute named `self` received from the api will conflicts with the reserved `self` - parameter of a class method. During generation, `self` attributes are mapped - to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. - """ - spec_property_naming = kwargs.get('_spec_property_naming', False) - if spec_property_naming: - kwargs = change_keys_js_to_python(kwargs, _self.__class__) - return fn(_self, *args, **kwargs) - return wrapped_init - - def get_allof_instances(self, model_args, constant_args): """ Args: self: the class we are handling model_args (dict): var_name to var_value used to make instances - constant_args (dict): var_name to var_value - used to make instances + constant_args (dict): + metadata arguments: + _check_type + _path_to_item + _spec_property_naming + _configuration + _visited_composed_classes Returns composed_instances (list) @@ -1593,20 +1746,8 @@ def get_allof_instances(self, model_args, constant_args): composed_instances = [] for allof_class in self._composed_schemas['allOf']: - # no need to handle changing js keys to python because - # for composed schemas, allof parameters are included in the - # composed schema and were changed to python keys in __new__ - # extract a dict of only required keys from fixed_model_args - kwargs = {} - var_names = set(allof_class.openapi_types.keys()) - for var_name in var_names: - if var_name in model_args: - kwargs[var_name] = model_args[var_name] - - # and use it to make the instance - kwargs.update(constant_args) try: - allof_instance = allof_class(**kwargs) + allof_instance = allof_class(**model_args, **constant_args) composed_instances.append(allof_instance) except Exception as ex: raise ApiValueError( @@ -1666,31 +1807,9 @@ def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): single_value_input = allows_single_value_input(oneof_class) - if not single_value_input: - # transform js keys from input data to python keys in fixed_model_args - fixed_model_args = change_keys_js_to_python( - model_kwargs, oneof_class) - - # Extract a dict with the properties that are declared in the oneOf schema. - # Undeclared properties (e.g. properties that are allowed because of the - # additionalProperties attribute in the OAS document) are not added to - # the dict. - kwargs = {} - var_names = set(oneof_class.openapi_types.keys()) - for var_name in var_names: - if var_name in fixed_model_args: - kwargs[var_name] = fixed_model_args[var_name] - - # do not try to make a model with no input args - if len(kwargs) == 0: - continue - - # and use it to make the instance - kwargs.update(constant_kwargs) - try: if not single_value_input: - oneof_instance = oneof_class(**kwargs) + oneof_instance = oneof_class(**model_kwargs, **constant_kwargs) else: if issubclass(oneof_class, ModelSimple): oneof_instance = oneof_class(model_arg, **constant_kwargs) @@ -1747,24 +1866,8 @@ def get_anyof_instances(self, model_args, constant_args): # none_type deserialization is handled in the __new__ method continue - # transform js keys to python keys in fixed_model_args - fixed_model_args = change_keys_js_to_python(model_args, anyof_class) - - # extract a dict of only required keys from these_model_vars - kwargs = {} - var_names = set(anyof_class.openapi_types.keys()) - for var_name in var_names: - if var_name in fixed_model_args: - kwargs[var_name] = fixed_model_args[var_name] - - # do not try to make a model with no input args - if len(kwargs) == 0: - continue - - # and use it to make the instance - kwargs.update(constant_args) try: - anyof_instance = anyof_class(**kwargs) + anyof_instance = anyof_class(**model_args, **constant_args) anyof_instances.append(anyof_instance) except Exception: pass @@ -1777,47 +1880,34 @@ def get_anyof_instances(self, model_args, constant_args): return anyof_instances -def get_additional_properties_model_instances( - composed_instances, self): - additional_properties_model_instances = [] - all_instances = [self] - all_instances.extend(composed_instances) - for instance in all_instances: - if instance.additional_properties_type is not None: - additional_properties_model_instances.append(instance) - return additional_properties_model_instances - - -def get_var_name_to_model_instances(self, composed_instances): - var_name_to_model_instances = {} - all_instances = [self] - all_instances.extend(composed_instances) - for instance in all_instances: - for var_name in instance.openapi_types: - if var_name not in var_name_to_model_instances: - var_name_to_model_instances[var_name] = [instance] - else: - var_name_to_model_instances[var_name].append(instance) - return var_name_to_model_instances - - -def get_unused_args(self, composed_instances, model_args): - unused_args = dict(model_args) - # arguments apssed to self were already converted to python names +def get_discarded_args(self, composed_instances, model_args): + """ + Gathers the args that were discarded by configuration.discard_unknown_keys + """ + model_arg_keys = model_args.keys() + discarded_args = set() + # arguments passed to self were already converted to python names # before __init__ was called - for var_name_py in self.attribute_map: - if var_name_py in unused_args: - del unused_args[var_name_py] for instance in composed_instances: if instance.__class__ in self._composed_schemas['allOf']: - for var_name_py in instance.attribute_map: - if var_name_py in unused_args: - del unused_args[var_name_py] + try: + keys = instance.to_dict().keys() + discarded_keys = model_args - keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass else: - for var_name_js in instance.attribute_map.values(): - if var_name_js in unused_args: - del unused_args[var_name_js] - return unused_args + try: + all_keys = set(model_to_dict(instance, serialize=False).keys()) + js_keys = model_to_dict(instance, serialize=True).keys() + all_keys.update(js_keys) + discarded_keys = model_arg_keys - all_keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass + return discarded_args def validate_get_composed_info(constant_args, model_args, self): @@ -1861,36 +1951,42 @@ def validate_get_composed_info(constant_args, model_args, self): composed_instances.append(oneof_instance) anyof_instances = get_anyof_instances(self, model_args, constant_args) composed_instances.extend(anyof_instances) + """ + set additional_properties_model_instances + additional properties must be evaluated at the schema level + so self's additional properties are most important + If self is a composed schema with: + - no properties defined in self + - additionalProperties: False + Then for object payloads every property is an additional property + and they are not allowed, so only empty dict is allowed + + Properties must be set on all matching schemas + so when a property is assigned toa composed instance, it must be set on all + composed instances regardless of additionalProperties presence + keeping it to prevent breaking changes in v5.0.1 + TODO remove cls._additional_properties_model_instances in 6.0.0 + """ + additional_properties_model_instances = [] + if self.additional_properties_type is not None: + additional_properties_model_instances = [self] - # map variable names to composed_instances - var_name_to_model_instances = get_var_name_to_model_instances( - self, composed_instances) - - # set additional_properties_model_instances - additional_properties_model_instances = ( - get_additional_properties_model_instances(composed_instances, self) - ) - - # set any remaining values - unused_args = get_unused_args(self, composed_instances, model_args) - if len(unused_args) > 0 and \ - len(additional_properties_model_instances) == 0 and \ - (self._configuration is None or - not self._configuration.discard_unknown_keys): - raise ApiValueError( - "Invalid input arguments input when making an instance of " - "class %s. Not all inputs were used. The unused input data " - "is %s" % (self.__class__.__name__, unused_args) - ) + """ + no need to set properties on self in here, they will be set in __init__ + By here all composed schema oneOf/anyOf/allOf instances have their properties set using + model_args + """ + discarded_args = get_discarded_args(self, composed_instances, model_args) - # no need to add additional_properties to var_name_to_model_instances here - # because additional_properties_model_instances will direct us to that - # instance when we use getattr or setattr - # and we update var_name_to_model_instances in setattr + # map variable names to composed_instances + var_name_to_model_instances = {} + for prop_name in model_args: + if prop_name not in discarded_args: + var_name_to_model_instances[prop_name] = [self] + composed_instances return [ composed_instances, var_name_to_model_instances, additional_properties_model_instances, - unused_args + discarded_args ] diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/.openapi-generator/VERSION b/samples/openapi3/client/features/dynamic-servers/ruby/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/.openapi-generator/VERSION +++ b/samples/openapi3/client/features/dynamic-servers/ruby/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/dynamic_servers.gemspec b/samples/openapi3/client/features/dynamic-servers/ruby/dynamic_servers.gemspec index 5bf3aefb73ae..bfaeacb1aed8 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/dynamic_servers.gemspec +++ b/samples/openapi3/client/features/dynamic-servers/ruby/dynamic_servers.gemspec @@ -8,7 +8,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers.rb b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers.rb index de9bed53f27d..2fdd66b4145d 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api/usage_api.rb b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api/usage_api.rb index eebb239b3382..1fdb9e468f0e 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api/usage_api.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api/usage_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_client.rb b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_client.rb index dbc8f908f4bf..5e236ccddd9b 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_client.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_error.rb b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_error.rb index 46e6a2ca0add..fbb07fa1c4dc 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_error.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_error.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/configuration.rb b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/configuration.rb index 47c7180a2a6e..9ae58b4a33a6 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/configuration.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/configuration.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/version.rb b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/version.rb index bc9def4db998..6c7f7ac27d90 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/version.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/version.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/spec/api_client_spec.rb b/samples/openapi3/client/features/dynamic-servers/ruby/spec/api_client_spec.rb index e3270122c377..685f1ee26c87 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/spec/api_client_spec.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/spec/api_client_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/spec/configuration_spec.rb b/samples/openapi3/client/features/dynamic-servers/ruby/spec/configuration_spec.rb index 6cfbb27797ee..adc964496e42 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/spec/configuration_spec.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/spec/configuration_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/spec/spec_helper.rb b/samples/openapi3/client/features/dynamic-servers/ruby/spec/spec_helper.rb index ea1690def96d..68368b2e587e 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/spec/spec_helper.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/spec/spec_helper.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/.openapi-generator/VERSION b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/.openapi-generator/VERSION +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore.rb index 0aacaaae2d69..dedc2a733beb 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api/usage_api.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api/usage_api.rb index b978d1beaeed..355c78dd797b 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api/usage_api.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api/usage_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_client.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_client.rb index 42da7d802008..02e0f300d109 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_client.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_error.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_error.rb index a9fdba6803b3..921981794ebb 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_error.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_error.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/configuration.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/configuration.rb index e8a443c18d77..20bb2cf0269d 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/configuration.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/configuration.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/models/array_alias.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/models/array_alias.rb index 90fba2508b88..b9f03227ba99 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/models/array_alias.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/models/array_alias.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/models/map_alias.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/models/map_alias.rb index 99f8455ae776..6cac74ac13e7 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/models/map_alias.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/models/map_alias.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/version.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/version.rb index fbaf1271f073..787763a66f3b 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/version.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/version.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/petstore.gemspec b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/petstore.gemspec index 151037c85a54..af450c8fe8df 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/petstore.gemspec +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/petstore.gemspec @@ -8,7 +8,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/api_client_spec.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/api_client_spec.rb index 489a718996ae..495e376a0946 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/api_client_spec.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/api_client_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/configuration_spec.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/configuration_spec.rb index 18846fa3c626..55ca88de58b4 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/configuration_spec.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/configuration_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/spec_helper.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/spec_helper.rb index 5dace1f934dc..9ab6dba6ba0c 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/spec_helper.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/spec_helper.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 5.1.1-SNAPSHOT +OpenAPI Generator version: 5.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.gitignore b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.gitignore index 8092a49d5152..6d2ac22c0b41 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.gitignore +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.gitignore @@ -30,8 +30,12 @@ pubspec.lock # Don’t commit files and directories created by other development environments. # For example, if your development environment creates any of the following files, # consider putting them in a global ignore file: -*.iml // IntelliJ -*.ipr // IntelliJ -*.iws // IntelliJ -.idea/ // IntelliJ -.DS_Store // Mac + +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ + +# Mac +.DS_Store diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.openapi-generator/FILES b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.openapi-generator/FILES index eb412a44146e..73e49578702f 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.openapi-generator/FILES @@ -66,6 +66,7 @@ lib/src/auth/api_key_auth.dart lib/src/auth/auth.dart lib/src/auth/basic_auth.dart lib/src/auth/oauth.dart +lib/src/date_serializer.dart lib/src/model/additional_properties_class.dart lib/src/model/animal.dart lib/src/model/api_response.dart @@ -77,6 +78,7 @@ lib/src/model/cat.dart lib/src/model/cat_all_of.dart lib/src/model/category.dart lib/src/model/class_model.dart +lib/src/model/date.dart lib/src/model/dog.dart lib/src/model/dog_all_of.dart lib/src/model/enum_arrays.dart diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/README.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/README.md index 8c94c359ed77..0e312d4370dd 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/README.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/README.md @@ -10,25 +10,29 @@ This Dart package is automatically generated by the [OpenAPI Generator](https:// * Dart 2.12.0 or later OR Flutter 1.26.0 or later * Dio 4.0.0+ -* timemachine option currently **DOES NOT** support sound null-safety and may not work ## Installation & Usage +### pub.dev +To use the package from [pub.dev](https://pub.dev), please include the following in pubspec.yaml +```yaml +dependencies: + openapi: 1.0.0 +``` + ### Github If this Dart package is published to Github, please include the following in pubspec.yaml -``` -name: openapi -version: 1.0.0 -description: OpenAPI API client +```yaml dependencies: openapi: - git: https://github.com/GIT_USER_ID/GIT_REPO_ID.git - version: 'any' + git: + url: https://github.com/GIT_USER_ID/GIT_REPO_ID.git + #ref: main ``` -### Local -To use the package in your local drive, please include the following in pubspec.yaml -``` +### Local development +To use the package from your local drive, please include the following in pubspec.yaml +```yaml dependencies: openapi: path: /path/to/openapi @@ -42,8 +46,8 @@ Please follow the [installation procedure](#installation--usage) and then run th import 'package:openapi/openapi.dart'; -final api = AnotherFakeApi(); -final modelClient = ModelClient(); // ModelClient | client model +final api = Openapi().getAnotherFakeApi(); +final ModelClient modelClient = ; // ModelClient | client model try { final response = await api.call123testSpecialTags(modelClient); @@ -60,46 +64,47 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*AnotherFakeApi* | [**call123testSpecialTags**](doc/AnotherFakeApi.md#call123testspecialtags) | **patch** /another-fake/dummy | To test special tags -*DefaultApi* | [**fooGet**](doc/DefaultApi.md#fooget) | **get** /foo | -*FakeApi* | [**fakeHealthGet**](doc/FakeApi.md#fakehealthget) | **get** /fake/health | Health check endpoint -*FakeApi* | [**fakeHttpSignatureTest**](doc/FakeApi.md#fakehttpsignaturetest) | **get** /fake/http-signature-test | test http signature authentication -*FakeApi* | [**fakeOuterBooleanSerialize**](doc/FakeApi.md#fakeouterbooleanserialize) | **post** /fake/outer/boolean | -*FakeApi* | [**fakeOuterCompositeSerialize**](doc/FakeApi.md#fakeoutercompositeserialize) | **post** /fake/outer/composite | -*FakeApi* | [**fakeOuterNumberSerialize**](doc/FakeApi.md#fakeouternumberserialize) | **post** /fake/outer/number | -*FakeApi* | [**fakeOuterStringSerialize**](doc/FakeApi.md#fakeouterstringserialize) | **post** /fake/outer/string | -*FakeApi* | [**fakePropertyEnumIntegerSerialize**](doc/FakeApi.md#fakepropertyenumintegerserialize) | **post** /fake/property/enum-int | -*FakeApi* | [**testBodyWithFileSchema**](doc/FakeApi.md#testbodywithfileschema) | **put** /fake/body-with-file-schema | -*FakeApi* | [**testBodyWithQueryParams**](doc/FakeApi.md#testbodywithqueryparams) | **put** /fake/body-with-query-params | -*FakeApi* | [**testClientModel**](doc/FakeApi.md#testclientmodel) | **patch** /fake | To test \"client\" model -*FakeApi* | [**testEndpointParameters**](doc/FakeApi.md#testendpointparameters) | **post** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*FakeApi* | [**testEnumParameters**](doc/FakeApi.md#testenumparameters) | **get** /fake | To test enum parameters -*FakeApi* | [**testGroupParameters**](doc/FakeApi.md#testgroupparameters) | **delete** /fake | Fake endpoint to test group parameters (optional) -*FakeApi* | [**testInlineAdditionalProperties**](doc/FakeApi.md#testinlineadditionalproperties) | **post** /fake/inline-additionalProperties | test inline additionalProperties -*FakeApi* | [**testJsonFormData**](doc/FakeApi.md#testjsonformdata) | **get** /fake/jsonFormData | test json serialization of form data -*FakeApi* | [**testQueryParameterCollectionFormat**](doc/FakeApi.md#testqueryparametercollectionformat) | **put** /fake/test-query-paramters | -*FakeClassnameTags123Api* | [**testClassname**](doc/FakeClassnameTags123Api.md#testclassname) | **patch** /fake_classname_test | To test class name in snake case -*PetApi* | [**addPet**](doc/PetApi.md#addpet) | **post** /pet | Add a new pet to the store -*PetApi* | [**deletePet**](doc/PetApi.md#deletepet) | **delete** /pet/{petId} | Deletes a pet -*PetApi* | [**findPetsByStatus**](doc/PetApi.md#findpetsbystatus) | **get** /pet/findByStatus | Finds Pets by status -*PetApi* | [**findPetsByTags**](doc/PetApi.md#findpetsbytags) | **get** /pet/findByTags | Finds Pets by tags -*PetApi* | [**getPetById**](doc/PetApi.md#getpetbyid) | **get** /pet/{petId} | Find pet by ID -*PetApi* | [**updatePet**](doc/PetApi.md#updatepet) | **put** /pet | Update an existing pet -*PetApi* | [**updatePetWithForm**](doc/PetApi.md#updatepetwithform) | **post** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**uploadFile**](doc/PetApi.md#uploadfile) | **post** /pet/{petId}/uploadImage | uploads an image -*PetApi* | [**uploadFileWithRequiredFile**](doc/PetApi.md#uploadfilewithrequiredfile) | **post** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) -*StoreApi* | [**deleteOrder**](doc/StoreApi.md#deleteorder) | **delete** /store/order/{order_id} | Delete purchase order by ID -*StoreApi* | [**getInventory**](doc/StoreApi.md#getinventory) | **get** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getOrderById**](doc/StoreApi.md#getorderbyid) | **get** /store/order/{order_id} | Find purchase order by ID -*StoreApi* | [**placeOrder**](doc/StoreApi.md#placeorder) | **post** /store/order | Place an order for a pet -*UserApi* | [**createUser**](doc/UserApi.md#createuser) | **post** /user | Create user -*UserApi* | [**createUsersWithArrayInput**](doc/UserApi.md#createuserswitharrayinput) | **post** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**createUsersWithListInput**](doc/UserApi.md#createuserswithlistinput) | **post** /user/createWithList | Creates list of users with given input array -*UserApi* | [**deleteUser**](doc/UserApi.md#deleteuser) | **delete** /user/{username} | Delete user -*UserApi* | [**getUserByName**](doc/UserApi.md#getuserbyname) | **get** /user/{username} | Get user by user name -*UserApi* | [**loginUser**](doc/UserApi.md#loginuser) | **get** /user/login | Logs user into the system -*UserApi* | [**logoutUser**](doc/UserApi.md#logoutuser) | **get** /user/logout | Logs out current logged in user session -*UserApi* | [**updateUser**](doc/UserApi.md#updateuser) | **put** /user/{username} | Updated user +[*AnotherFakeApi*](doc/AnotherFakeApi.md) | [**call123testSpecialTags**](doc/AnotherFakeApi.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags +[*DefaultApi*](doc/DefaultApi.md) | [**fooGet**](doc/DefaultApi.md#fooget) | **GET** /foo | +[*FakeApi*](doc/FakeApi.md) | [**fakeHealthGet**](doc/FakeApi.md#fakehealthget) | **GET** /fake/health | Health check endpoint +[*FakeApi*](doc/FakeApi.md) | [**fakeHttpSignatureTest**](doc/FakeApi.md#fakehttpsignaturetest) | **GET** /fake/http-signature-test | test http signature authentication +[*FakeApi*](doc/FakeApi.md) | [**fakeOuterBooleanSerialize**](doc/FakeApi.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +[*FakeApi*](doc/FakeApi.md) | [**fakeOuterCompositeSerialize**](doc/FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +[*FakeApi*](doc/FakeApi.md) | [**fakeOuterNumberSerialize**](doc/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | +[*FakeApi*](doc/FakeApi.md) | [**fakeOuterStringSerialize**](doc/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | +[*FakeApi*](doc/FakeApi.md) | [**fakePropertyEnumIntegerSerialize**](doc/FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +[*FakeApi*](doc/FakeApi.md) | [**testBodyWithBinary**](doc/FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | +[*FakeApi*](doc/FakeApi.md) | [**testBodyWithFileSchema**](doc/FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | +[*FakeApi*](doc/FakeApi.md) | [**testBodyWithQueryParams**](doc/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | +[*FakeApi*](doc/FakeApi.md) | [**testClientModel**](doc/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +[*FakeApi*](doc/FakeApi.md) | [**testEndpointParameters**](doc/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[*FakeApi*](doc/FakeApi.md) | [**testEnumParameters**](doc/FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters +[*FakeApi*](doc/FakeApi.md) | [**testGroupParameters**](doc/FakeApi.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[*FakeApi*](doc/FakeApi.md) | [**testInlineAdditionalProperties**](doc/FakeApi.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[*FakeApi*](doc/FakeApi.md) | [**testJsonFormData**](doc/FakeApi.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +[*FakeApi*](doc/FakeApi.md) | [**testQueryParameterCollectionFormat**](doc/FakeApi.md#testqueryparametercollectionformat) | **PUT** /fake/test-query-paramters | +[*FakeClassnameTags123Api*](doc/FakeClassnameTags123Api.md) | [**testClassname**](doc/FakeClassnameTags123Api.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case +[*PetApi*](doc/PetApi.md) | [**addPet**](doc/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +[*PetApi*](doc/PetApi.md) | [**deletePet**](doc/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +[*PetApi*](doc/PetApi.md) | [**findPetsByStatus**](doc/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +[*PetApi*](doc/PetApi.md) | [**findPetsByTags**](doc/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +[*PetApi*](doc/PetApi.md) | [**getPetById**](doc/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +[*PetApi*](doc/PetApi.md) | [**updatePet**](doc/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +[*PetApi*](doc/PetApi.md) | [**updatePetWithForm**](doc/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +[*PetApi*](doc/PetApi.md) | [**uploadFile**](doc/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +[*PetApi*](doc/PetApi.md) | [**uploadFileWithRequiredFile**](doc/PetApi.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +[*StoreApi*](doc/StoreApi.md) | [**deleteOrder**](doc/StoreApi.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +[*StoreApi*](doc/StoreApi.md) | [**getInventory**](doc/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[*StoreApi*](doc/StoreApi.md) | [**getOrderById**](doc/StoreApi.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +[*StoreApi*](doc/StoreApi.md) | [**placeOrder**](doc/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +[*UserApi*](doc/UserApi.md) | [**createUser**](doc/UserApi.md#createuser) | **POST** /user | Create user +[*UserApi*](doc/UserApi.md) | [**createUsersWithArrayInput**](doc/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +[*UserApi*](doc/UserApi.md) | [**createUsersWithListInput**](doc/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +[*UserApi*](doc/UserApi.md) | [**deleteUser**](doc/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +[*UserApi*](doc/UserApi.md) | [**getUserByName**](doc/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +[*UserApi*](doc/UserApi.md) | [**loginUser**](doc/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +[*UserApi*](doc/UserApi.md) | [**logoutUser**](doc/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +[*UserApi*](doc/UserApi.md) | [**updateUser**](doc/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user ## Documentation For Models diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/AdditionalPropertiesClass.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/AdditionalPropertiesClass.md index 5443d024fd25..f9f7857894d0 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/AdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/AdditionalPropertiesClass.md @@ -8,8 +8,8 @@ import 'package:openapi/api.dart'; ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapProperty** | **BuiltMap** | | [optional] -**mapOfMapProperty** | [**BuiltMap>**](BuiltMap.md) | | [optional] +**mapProperty** | **BuiltMap<String, String>** | | [optional] +**mapOfMapProperty** | [**BuiltMap<String, BuiltMap<String, String>>**](BuiltMap.md) | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/AnotherFakeApi.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/AnotherFakeApi.md index d55663297c13..9416627d74d6 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/AnotherFakeApi.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/AnotherFakeApi.md @@ -9,7 +9,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**call123testSpecialTags**](AnotherFakeApi.md#call123testspecialtags) | **patch** /another-fake/dummy | To test special tags +[**call123testSpecialTags**](AnotherFakeApi.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags # **call123testSpecialTags** @@ -23,13 +23,13 @@ To test special tags and operation ID starting with number ```dart import 'package:openapi/api.dart'; -var api_instance = new AnotherFakeApi(); -var modelClient = new ModelClient(); // ModelClient | client model +final api = Openapi().getAnotherFakeApi(); +final ModelClient modelClient = ; // ModelClient | client model try { - var result = api_instance.call123testSpecialTags(modelClient); - print(result); -} catch (e) { + final response = api.call123testSpecialTags(modelClient); + print(response); +} catch on DioError (e) { print('Exception when calling AnotherFakeApi->call123testSpecialTags: $e\n'); } ``` diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayOfArrayOfNumberOnly.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayOfArrayOfNumberOnly.md index 0a9d69c7e3cb..d1a272ab6023 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayOfArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayOfArrayOfNumberOnly.md @@ -8,7 +8,7 @@ import 'package:openapi/api.dart'; ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**arrayArrayNumber** | [**BuiltList>**](BuiltList.md) | | [optional] +**arrayArrayNumber** | [**BuiltList<BuiltList<num>>**](BuiltList.md) | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayOfNumberOnly.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayOfNumberOnly.md index 6ffe36730c25..94b60f272fd4 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayOfNumberOnly.md @@ -8,7 +8,7 @@ import 'package:openapi/api.dart'; ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**arrayNumber** | **BuiltList** | | [optional] +**arrayNumber** | **BuiltList<num>** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayTest.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayTest.md index fc38f8ae52d5..0813d4fa93c6 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayTest.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayTest.md @@ -8,9 +8,9 @@ import 'package:openapi/api.dart'; ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**arrayOfString** | **BuiltList** | | [optional] -**arrayArrayOfInteger** | [**BuiltList>**](BuiltList.md) | | [optional] -**arrayArrayOfModel** | [**BuiltList>**](BuiltList.md) | | [optional] +**arrayOfString** | **BuiltList<String>** | | [optional] +**arrayArrayOfInteger** | [**BuiltList<BuiltList<int>>**](BuiltList.md) | | [optional] +**arrayArrayOfModel** | [**BuiltList<BuiltList<ReadOnlyFirst>>**](BuiltList.md) | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/DefaultApi.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/DefaultApi.md index be916c3037d5..5b5a2cdead65 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/DefaultApi.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/DefaultApi.md @@ -9,7 +9,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**fooGet**](DefaultApi.md#fooget) | **get** /foo | +[**fooGet**](DefaultApi.md#fooget) | **GET** /foo | # **fooGet** @@ -21,12 +21,12 @@ Method | HTTP request | Description ```dart import 'package:openapi/api.dart'; -var api_instance = new DefaultApi(); +final api = Openapi().getDefaultApi(); try { - var result = api_instance.fooGet(); - print(result); -} catch (e) { + final response = api.fooGet(); + print(response); +} catch on DioError (e) { print('Exception when calling DefaultApi->fooGet: $e\n'); } ``` diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/EnumArrays.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/EnumArrays.md index 9cc4d727b2a9..06170bb8f51d 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/EnumArrays.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/EnumArrays.md @@ -9,7 +9,7 @@ import 'package:openapi/api.dart'; Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **justSymbol** | **String** | | [optional] -**arrayEnum** | **BuiltList** | | [optional] +**arrayEnum** | **BuiltList<String>** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FakeApi.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FakeApi.md index 41ab4e4fc126..b8e90ea60748 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FakeApi.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FakeApi.md @@ -9,22 +9,23 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**fakeHealthGet**](FakeApi.md#fakehealthget) | **get** /fake/health | Health check endpoint -[**fakeHttpSignatureTest**](FakeApi.md#fakehttpsignaturetest) | **get** /fake/http-signature-test | test http signature authentication -[**fakeOuterBooleanSerialize**](FakeApi.md#fakeouterbooleanserialize) | **post** /fake/outer/boolean | -[**fakeOuterCompositeSerialize**](FakeApi.md#fakeoutercompositeserialize) | **post** /fake/outer/composite | -[**fakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **post** /fake/outer/number | -[**fakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **post** /fake/outer/string | -[**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakepropertyenumintegerserialize) | **post** /fake/property/enum-int | -[**testBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **put** /fake/body-with-file-schema | -[**testBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **put** /fake/body-with-query-params | -[**testClientModel**](FakeApi.md#testclientmodel) | **patch** /fake | To test \"client\" model -[**testEndpointParameters**](FakeApi.md#testendpointparameters) | **post** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumParameters**](FakeApi.md#testenumparameters) | **get** /fake | To test enum parameters -[**testGroupParameters**](FakeApi.md#testgroupparameters) | **delete** /fake | Fake endpoint to test group parameters (optional) -[**testInlineAdditionalProperties**](FakeApi.md#testinlineadditionalproperties) | **post** /fake/inline-additionalProperties | test inline additionalProperties -[**testJsonFormData**](FakeApi.md#testjsonformdata) | **get** /fake/jsonFormData | test json serialization of form data -[**testQueryParameterCollectionFormat**](FakeApi.md#testqueryparametercollectionformat) | **put** /fake/test-query-paramters | +[**fakeHealthGet**](FakeApi.md#fakehealthget) | **GET** /fake/health | Health check endpoint +[**fakeHttpSignatureTest**](FakeApi.md#fakehttpsignaturetest) | **GET** /fake/http-signature-test | test http signature authentication +[**fakeOuterBooleanSerialize**](FakeApi.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +[**fakeOuterCompositeSerialize**](FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +[**fakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | +[**fakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | +[**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +[**testBodyWithBinary**](FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | +[**testBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | +[**testBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | +[**testClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +[**testEndpointParameters**](FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumParameters**](FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters +[**testGroupParameters**](FakeApi.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[**testInlineAdditionalProperties**](FakeApi.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**testJsonFormData**](FakeApi.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +[**testQueryParameterCollectionFormat**](FakeApi.md#testqueryparametercollectionformat) | **PUT** /fake/test-query-paramters | # **fakeHealthGet** @@ -36,12 +37,12 @@ Health check endpoint ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); +final api = Openapi().getFakeApi(); try { - var result = api_instance.fakeHealthGet(); - print(result); -} catch (e) { + final response = api.fakeHealthGet(); + print(response); +} catch on DioError (e) { print('Exception when calling FakeApi->fakeHealthGet: $e\n'); } ``` @@ -76,14 +77,14 @@ import 'package:openapi/api.dart'; //defaultApiClient.getAuthentication('http_signature_test').username = 'YOUR_USERNAME' //defaultApiClient.getAuthentication('http_signature_test').password = 'YOUR_PASSWORD'; -var api_instance = new FakeApi(); -var pet = new Pet(); // Pet | Pet object that needs to be added to the store -var query1 = query1_example; // String | query parameter -var header1 = header1_example; // String | header parameter +final api = Openapi().getFakeApi(); +final Pet pet = ; // Pet | Pet object that needs to be added to the store +final String query1 = query1_example; // String | query parameter +final String header1 = header1_example; // String | header parameter try { - api_instance.fakeHttpSignatureTest(pet, query1, header1); -} catch (e) { + api.fakeHttpSignatureTest(pet, query1, header1); +} catch on DioError (e) { print('Exception when calling FakeApi->fakeHttpSignatureTest: $e\n'); } ``` @@ -122,13 +123,13 @@ Test serialization of outer boolean types ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var body = new bool(); // bool | Input boolean as post body +final api = Openapi().getFakeApi(); +final bool body = true; // bool | Input boolean as post body try { - var result = api_instance.fakeOuterBooleanSerialize(body); - print(result); -} catch (e) { + final response = api.fakeOuterBooleanSerialize(body); + print(response); +} catch on DioError (e) { print('Exception when calling FakeApi->fakeOuterBooleanSerialize: $e\n'); } ``` @@ -165,13 +166,13 @@ Test serialization of object with outer number type ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var outerComposite = new OuterComposite(); // OuterComposite | Input composite as post body +final api = Openapi().getFakeApi(); +final OuterComposite outerComposite = ; // OuterComposite | Input composite as post body try { - var result = api_instance.fakeOuterCompositeSerialize(outerComposite); - print(result); -} catch (e) { + final response = api.fakeOuterCompositeSerialize(outerComposite); + print(response); +} catch on DioError (e) { print('Exception when calling FakeApi->fakeOuterCompositeSerialize: $e\n'); } ``` @@ -208,13 +209,13 @@ Test serialization of outer number types ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var body = new num(); // num | Input number as post body +final api = Openapi().getFakeApi(); +final num body = 8.14; // num | Input number as post body try { - var result = api_instance.fakeOuterNumberSerialize(body); - print(result); -} catch (e) { + final response = api.fakeOuterNumberSerialize(body); + print(response); +} catch on DioError (e) { print('Exception when calling FakeApi->fakeOuterNumberSerialize: $e\n'); } ``` @@ -251,13 +252,13 @@ Test serialization of outer string types ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var body = new String(); // String | Input string as post body +final api = Openapi().getFakeApi(); +final String body = body_example; // String | Input string as post body try { - var result = api_instance.fakeOuterStringSerialize(body); - print(result); -} catch (e) { + final response = api.fakeOuterStringSerialize(body); + print(response); +} catch on DioError (e) { print('Exception when calling FakeApi->fakeOuterStringSerialize: $e\n'); } ``` @@ -294,13 +295,13 @@ Test serialization of enum (int) properties with examples ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var outerObjectWithEnumProperty = new OuterObjectWithEnumProperty(); // OuterObjectWithEnumProperty | Input enum (int) as post body +final api = Openapi().getFakeApi(); +final OuterObjectWithEnumProperty outerObjectWithEnumProperty = ; // OuterObjectWithEnumProperty | Input enum (int) as post body try { - var result = api_instance.fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty); - print(result); -} catch (e) { + final response = api.fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty); + print(response); +} catch on DioError (e) { print('Exception when calling FakeApi->fakePropertyEnumIntegerSerialize: $e\n'); } ``` @@ -326,23 +327,65 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **testBodyWithBinary** +> testBodyWithBinary(body) + + + +For this test, the body has to be a binary file. + +### Example +```dart +import 'package:openapi/api.dart'; + +final api = Openapi().getFakeApi(); +final MultipartFile body = BINARY_DATA_HERE; // MultipartFile | image to upload + +try { + api.testBodyWithBinary(body); +} catch on DioError (e) { + print('Exception when calling FakeApi->testBodyWithBinary: $e\n'); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **MultipartFile**| image to upload | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: image/png + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **testBodyWithFileSchema** > testBodyWithFileSchema(fileSchemaTestClass) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var fileSchemaTestClass = new FileSchemaTestClass(); // FileSchemaTestClass | +final api = Openapi().getFakeApi(); +final FileSchemaTestClass fileSchemaTestClass = ; // FileSchemaTestClass | try { - api_instance.testBodyWithFileSchema(fileSchemaTestClass); -} catch (e) { + api.testBodyWithFileSchema(fileSchemaTestClass); +} catch on DioError (e) { print('Exception when calling FakeApi->testBodyWithFileSchema: $e\n'); } ``` @@ -377,13 +420,13 @@ No authorization required ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var query = query_example; // String | -var user = new User(); // User | +final api = Openapi().getFakeApi(); +final String query = query_example; // String | +final User user = ; // User | try { - api_instance.testBodyWithQueryParams(query, user); -} catch (e) { + api.testBodyWithQueryParams(query, user); +} catch on DioError (e) { print('Exception when calling FakeApi->testBodyWithQueryParams: $e\n'); } ``` @@ -421,13 +464,13 @@ To test \"client\" model ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var modelClient = new ModelClient(); // ModelClient | client model +final api = Openapi().getFakeApi(); +final ModelClient modelClient = ; // ModelClient | client model try { - var result = api_instance.testClientModel(modelClient); - print(result); -} catch (e) { + final response = api.testClientModel(modelClient); + print(response); +} catch on DioError (e) { print('Exception when calling FakeApi->testClientModel: $e\n'); } ``` @@ -467,25 +510,25 @@ import 'package:openapi/api.dart'; //defaultApiClient.getAuthentication('http_basic_test').username = 'YOUR_USERNAME' //defaultApiClient.getAuthentication('http_basic_test').password = 'YOUR_PASSWORD'; -var api_instance = new FakeApi(); -var number = 8.14; // num | None -var double_ = 1.2; // double | None -var patternWithoutDelimiter = patternWithoutDelimiter_example; // String | None -var byte = BYTE_ARRAY_DATA_HERE; // String | None -var integer = 56; // int | None -var int32 = 56; // int | None -var int64 = 789; // int | None -var float = 3.4; // double | None -var string = string_example; // String | None -var binary = BINARY_DATA_HERE; // Uint8List | None -var date = 2013-10-20; // DateTime | None -var dateTime = 2013-10-20T19:20:30+01:00; // DateTime | None -var password = password_example; // String | None -var callback = callback_example; // String | None +final api = Openapi().getFakeApi(); +final num number = 8.14; // num | None +final double double_ = 1.2; // double | None +final String patternWithoutDelimiter = patternWithoutDelimiter_example; // String | None +final String byte = BYTE_ARRAY_DATA_HERE; // String | None +final int integer = 56; // int | None +final int int32 = 56; // int | None +final int int64 = 789; // int | None +final double float = 3.4; // double | None +final String string = string_example; // String | None +final Uint8List binary = BINARY_DATA_HERE; // Uint8List | None +final Date date = 2013-10-20; // Date | None +final DateTime dateTime = 2013-10-20T19:20:30+01:00; // DateTime | None +final String password = password_example; // String | None +final String callback = callback_example; // String | None try { - api_instance.testEndpointParameters(number, double_, patternWithoutDelimiter, byte, integer, int32, int64, float, string, binary, date, dateTime, password, callback); -} catch (e) { + api.testEndpointParameters(number, double_, patternWithoutDelimiter, byte, integer, int32, int64, float, string, binary, date, dateTime, password, callback); +} catch on DioError (e) { print('Exception when calling FakeApi->testEndpointParameters: $e\n'); } ``` @@ -504,7 +547,7 @@ Name | Type | Description | Notes **float** | **double**| None | [optional] **string** | **String**| None | [optional] **binary** | **Uint8List**| None | [optional] - **date** | **DateTime**| None | [optional] + **date** | **Date**| None | [optional] **dateTime** | **DateTime**| None | [optional] **password** | **String**| None | [optional] **callback** | **String**| None | [optional] @@ -535,19 +578,19 @@ To test enum parameters ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var enumHeaderStringArray = []; // BuiltList | Header parameter enum test (string array) -var enumHeaderString = enumHeaderString_example; // String | Header parameter enum test (string) -var enumQueryStringArray = []; // BuiltList | Query parameter enum test (string array) -var enumQueryString = enumQueryString_example; // String | Query parameter enum test (string) -var enumQueryInteger = 56; // int | Query parameter enum test (double) -var enumQueryDouble = 1.2; // double | Query parameter enum test (double) -var enumFormStringArray = [enumFormStringArray_example]; // BuiltList | Form parameter enum test (string array) -var enumFormString = enumFormString_example; // String | Form parameter enum test (string) +final api = Openapi().getFakeApi(); +final BuiltList enumHeaderStringArray = ; // BuiltList | Header parameter enum test (string array) +final String enumHeaderString = enumHeaderString_example; // String | Header parameter enum test (string) +final BuiltList enumQueryStringArray = ; // BuiltList | Query parameter enum test (string array) +final String enumQueryString = enumQueryString_example; // String | Query parameter enum test (string) +final int enumQueryInteger = 56; // int | Query parameter enum test (double) +final double enumQueryDouble = 1.2; // double | Query parameter enum test (double) +final BuiltList enumFormStringArray = enumFormStringArray_example; // BuiltList | Form parameter enum test (string array) +final String enumFormString = enumFormString_example; // String | Form parameter enum test (string) try { - api_instance.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); -} catch (e) { + api.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); +} catch on DioError (e) { print('Exception when calling FakeApi->testEnumParameters: $e\n'); } ``` @@ -556,13 +599,13 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **enumHeaderStringArray** | [**BuiltList**](String.md)| Header parameter enum test (string array) | [optional] + **enumHeaderStringArray** | [**BuiltList<String>**](String.md)| Header parameter enum test (string array) | [optional] **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to '-efg'] - **enumQueryStringArray** | [**BuiltList**](String.md)| Query parameter enum test (string array) | [optional] + **enumQueryStringArray** | [**BuiltList<String>**](String.md)| Query parameter enum test (string array) | [optional] **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to '-efg'] **enumQueryInteger** | **int**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **double**| Query parameter enum test (double) | [optional] - **enumFormStringArray** | [**BuiltList**](String.md)| Form parameter enum test (string array) | [optional] [default to '$'] + **enumFormStringArray** | [**BuiltList<String>**](String.md)| Form parameter enum test (string array) | [optional] [default to '$'] **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to '-efg'] ### Return type @@ -594,17 +637,17 @@ import 'package:openapi/api.dart'; //defaultApiClient.getAuthentication('bearer_test').username = 'YOUR_USERNAME' //defaultApiClient.getAuthentication('bearer_test').password = 'YOUR_PASSWORD'; -var api_instance = new FakeApi(); -var requiredStringGroup = 56; // int | Required String in group parameters -var requiredBooleanGroup = true; // bool | Required Boolean in group parameters -var requiredInt64Group = 789; // int | Required Integer in group parameters -var stringGroup = 56; // int | String in group parameters -var booleanGroup = true; // bool | Boolean in group parameters -var int64Group = 789; // int | Integer in group parameters +final api = Openapi().getFakeApi(); +final int requiredStringGroup = 56; // int | Required String in group parameters +final bool requiredBooleanGroup = true; // bool | Required Boolean in group parameters +final int requiredInt64Group = 789; // int | Required Integer in group parameters +final int stringGroup = 56; // int | String in group parameters +final bool booleanGroup = true; // bool | Boolean in group parameters +final int int64Group = 789; // int | Integer in group parameters try { - api_instance.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); -} catch (e) { + api.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); +} catch on DioError (e) { print('Exception when calling FakeApi->testGroupParameters: $e\n'); } ``` @@ -644,12 +687,12 @@ test inline additionalProperties ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var requestBody = new BuiltMap(); // BuiltMap | request body +final api = Openapi().getFakeApi(); +final BuiltMap requestBody = ; // BuiltMap | request body try { - api_instance.testInlineAdditionalProperties(requestBody); -} catch (e) { + api.testInlineAdditionalProperties(requestBody); +} catch on DioError (e) { print('Exception when calling FakeApi->testInlineAdditionalProperties: $e\n'); } ``` @@ -658,7 +701,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **requestBody** | [**BuiltMap**](String.md)| request body | + **requestBody** | [**BuiltMap<String, String>**](String.md)| request body | ### Return type @@ -684,13 +727,13 @@ test json serialization of form data ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var param = param_example; // String | field1 -var param2 = param2_example; // String | field2 +final api = Openapi().getFakeApi(); +final String param = param_example; // String | field1 +final String param2 = param2_example; // String | field2 try { - api_instance.testJsonFormData(param, param2); -} catch (e) { + api.testJsonFormData(param, param2); +} catch on DioError (e) { print('Exception when calling FakeApi->testJsonFormData: $e\n'); } ``` @@ -728,16 +771,16 @@ To test the collection format in query parameters ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var pipe = []; // BuiltList | -var ioutil = []; // BuiltList | -var http = []; // BuiltList | -var url = []; // BuiltList | -var context = []; // BuiltList | +final api = Openapi().getFakeApi(); +final BuiltList pipe = ; // BuiltList | +final BuiltList ioutil = ; // BuiltList | +final BuiltList http = ; // BuiltList | +final BuiltList url = ; // BuiltList | +final BuiltList context = ; // BuiltList | try { - api_instance.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context); -} catch (e) { + api.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context); +} catch on DioError (e) { print('Exception when calling FakeApi->testQueryParameterCollectionFormat: $e\n'); } ``` @@ -746,11 +789,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **pipe** | [**BuiltList**](String.md)| | - **ioutil** | [**BuiltList**](String.md)| | - **http** | [**BuiltList**](String.md)| | - **url** | [**BuiltList**](String.md)| | - **context** | [**BuiltList**](String.md)| | + **pipe** | [**BuiltList<String>**](String.md)| | + **ioutil** | [**BuiltList<String>**](String.md)| | + **http** | [**BuiltList<String>**](String.md)| | + **url** | [**BuiltList<String>**](String.md)| | + **context** | [**BuiltList<String>**](String.md)| | ### Return type diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FakeClassnameTags123Api.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FakeClassnameTags123Api.md index 9745ca8e3ffe..cabd6fe0a99b 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FakeClassnameTags123Api.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FakeClassnameTags123Api.md @@ -9,7 +9,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testClassname**](FakeClassnameTags123Api.md#testclassname) | **patch** /fake_classname_test | To test class name in snake case +[**testClassname**](FakeClassnameTags123Api.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case # **testClassname** @@ -27,13 +27,13 @@ import 'package:openapi/api.dart'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed //defaultApiClient.getAuthentication('api_key_query').apiKeyPrefix = 'Bearer'; -var api_instance = new FakeClassnameTags123Api(); -var modelClient = new ModelClient(); // ModelClient | client model +final api = Openapi().getFakeClassnameTags123Api(); +final ModelClient modelClient = ; // ModelClient | client model try { - var result = api_instance.testClassname(modelClient); - print(result); -} catch (e) { + final response = api.testClassname(modelClient); + print(response); +} catch on DioError (e) { print('Exception when calling FakeClassnameTags123Api->testClassname: $e\n'); } ``` diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FileSchemaTestClass.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FileSchemaTestClass.md index 9b7eebcb2bf1..105fece87f1d 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FileSchemaTestClass.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FileSchemaTestClass.md @@ -9,7 +9,7 @@ import 'package:openapi/api.dart'; Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **file** | [**ModelFile**](ModelFile.md) | | [optional] -**files** | [**BuiltList**](ModelFile.md) | | [optional] +**files** | [**BuiltList<ModelFile>**](ModelFile.md) | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FormatTest.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FormatTest.md index 7cac4e3b6be1..f811264ca2ba 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FormatTest.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FormatTest.md @@ -18,7 +18,7 @@ Name | Type | Description | Notes **string** | **String** | | [optional] **byte** | **String** | | **binary** | [**Uint8List**](Uint8List.md) | | [optional] -**date** | [**DateTime**](DateTime.md) | | +**date** | [**Date**](Date.md) | | **dateTime** | [**DateTime**](DateTime.md) | | [optional] **uuid** | **String** | | [optional] **password** | **String** | | diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/MapTest.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/MapTest.md index 2da739ba8b83..4ad87df64232 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/MapTest.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/MapTest.md @@ -8,10 +8,10 @@ import 'package:openapi/api.dart'; ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapMapOfString** | [**BuiltMap>**](BuiltMap.md) | | [optional] -**mapOfEnumString** | **BuiltMap** | | [optional] -**directMap** | **BuiltMap** | | [optional] -**indirectMap** | **BuiltMap** | | [optional] +**mapMapOfString** | [**BuiltMap<String, BuiltMap<String, String>>**](BuiltMap.md) | | [optional] +**mapOfEnumString** | **BuiltMap<String, String>** | | [optional] +**directMap** | **BuiltMap<String, bool>** | | [optional] +**indirectMap** | **BuiltMap<String, bool>** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/MixedPropertiesAndAdditionalPropertiesClass.md index f50d97687517..b1a4c4ccc401 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/MixedPropertiesAndAdditionalPropertiesClass.md @@ -10,7 +10,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **String** | | [optional] **dateTime** | [**DateTime**](DateTime.md) | | [optional] -**map** | [**BuiltMap**](Animal.md) | | [optional] +**map** | [**BuiltMap<String, Animal>**](Animal.md) | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/NullableClass.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/NullableClass.md index a9694f846c55..4ce8d5e17576 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/NullableClass.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/NullableClass.md @@ -12,14 +12,14 @@ Name | Type | Description | Notes **numberProp** | **num** | | [optional] **booleanProp** | **bool** | | [optional] **stringProp** | **String** | | [optional] -**dateProp** | [**DateTime**](DateTime.md) | | [optional] +**dateProp** | [**Date**](Date.md) | | [optional] **datetimeProp** | [**DateTime**](DateTime.md) | | [optional] -**arrayNullableProp** | [**BuiltList**](JsonObject.md) | | [optional] -**arrayAndItemsNullableProp** | [**BuiltList**](JsonObject.md) | | [optional] -**arrayItemsNullable** | [**BuiltList**](JsonObject.md) | | [optional] -**objectNullableProp** | [**BuiltMap**](JsonObject.md) | | [optional] -**objectAndItemsNullableProp** | [**BuiltMap**](JsonObject.md) | | [optional] -**objectItemsNullable** | [**BuiltMap**](JsonObject.md) | | [optional] +**arrayNullableProp** | [**BuiltList<JsonObject>**](JsonObject.md) | | [optional] +**arrayAndItemsNullableProp** | [**BuiltList<JsonObject>**](JsonObject.md) | | [optional] +**arrayItemsNullable** | [**BuiltList<JsonObject>**](JsonObject.md) | | [optional] +**objectNullableProp** | [**BuiltMap<String, JsonObject>**](JsonObject.md) | | [optional] +**objectAndItemsNullableProp** | [**BuiltMap<String, JsonObject>**](JsonObject.md) | | [optional] +**objectItemsNullable** | [**BuiltMap<String, JsonObject>**](JsonObject.md) | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/Pet.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/Pet.md index 3640640df190..08e0aeedd784 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/Pet.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/Pet.md @@ -11,8 +11,8 @@ Name | Type | Description | Notes **id** | **int** | | [optional] **category** | [**Category**](Category.md) | | [optional] **name** | **String** | | -**photoUrls** | **BuiltSet** | | -**tags** | [**BuiltList**](Tag.md) | | [optional] +**photoUrls** | **BuiltSet<String>** | | +**tags** | [**BuiltList<Tag>**](Tag.md) | | [optional] **status** | **String** | pet status in the store | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/PetApi.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/PetApi.md index d5a07d5046e2..70f5342d771d 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/PetApi.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/PetApi.md @@ -9,15 +9,15 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**addPet**](PetApi.md#addpet) | **post** /pet | Add a new pet to the store -[**deletePet**](PetApi.md#deletepet) | **delete** /pet/{petId} | Deletes a pet -[**findPetsByStatus**](PetApi.md#findpetsbystatus) | **get** /pet/findByStatus | Finds Pets by status -[**findPetsByTags**](PetApi.md#findpetsbytags) | **get** /pet/findByTags | Finds Pets by tags -[**getPetById**](PetApi.md#getpetbyid) | **get** /pet/{petId} | Find pet by ID -[**updatePet**](PetApi.md#updatepet) | **put** /pet | Update an existing pet -[**updatePetWithForm**](PetApi.md#updatepetwithform) | **post** /pet/{petId} | Updates a pet in the store with form data -[**uploadFile**](PetApi.md#uploadfile) | **post** /pet/{petId}/uploadImage | uploads an image -[**uploadFileWithRequiredFile**](PetApi.md#uploadfilewithrequiredfile) | **post** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +[**addPet**](PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +[**uploadFileWithRequiredFile**](PetApi.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) # **addPet** @@ -31,12 +31,12 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = new PetApi(); -var pet = new Pet(); // Pet | Pet object that needs to be added to the store +final api = Openapi().getPetApi(); +final Pet pet = ; // Pet | Pet object that needs to be added to the store try { - api_instance.addPet(pet); -} catch (e) { + api.addPet(pet); +} catch on DioError (e) { print('Exception when calling PetApi->addPet: $e\n'); } ``` @@ -73,13 +73,13 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = new PetApi(); -var petId = 789; // int | Pet id to delete -var apiKey = apiKey_example; // String | +final api = Openapi().getPetApi(); +final int petId = 789; // int | Pet id to delete +final String apiKey = apiKey_example; // String | try { - api_instance.deletePet(petId, apiKey); -} catch (e) { + api.deletePet(petId, apiKey); +} catch on DioError (e) { print('Exception when calling PetApi->deletePet: $e\n'); } ``` @@ -119,13 +119,13 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = new PetApi(); -var status = []; // BuiltList | Status values that need to be considered for filter +final api = Openapi().getPetApi(); +final BuiltList status = ; // BuiltList | Status values that need to be considered for filter try { - var result = api_instance.findPetsByStatus(status); - print(result); -} catch (e) { + final response = api.findPetsByStatus(status); + print(response); +} catch on DioError (e) { print('Exception when calling PetApi->findPetsByStatus: $e\n'); } ``` @@ -134,11 +134,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**BuiltList**](String.md)| Status values that need to be considered for filter | + **status** | [**BuiltList<String>**](String.md)| Status values that need to be considered for filter | ### Return type -[**BuiltList**](Pet.md) +[**BuiltList<Pet>**](Pet.md) ### Authorization @@ -164,13 +164,13 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = new PetApi(); -var tags = []; // BuiltSet | Tags to filter by +final api = Openapi().getPetApi(); +final BuiltSet tags = ; // BuiltSet | Tags to filter by try { - var result = api_instance.findPetsByTags(tags); - print(result); -} catch (e) { + final response = api.findPetsByTags(tags); + print(response); +} catch on DioError (e) { print('Exception when calling PetApi->findPetsByTags: $e\n'); } ``` @@ -179,11 +179,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **tags** | [**BuiltSet**](String.md)| Tags to filter by | + **tags** | [**BuiltSet<String>**](String.md)| Tags to filter by | ### Return type -[**BuiltSet**](Pet.md) +[**BuiltSet<Pet>**](Pet.md) ### Authorization @@ -211,13 +211,13 @@ import 'package:openapi/api.dart'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed //defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; -var api_instance = new PetApi(); -var petId = 789; // int | ID of pet to return +final api = Openapi().getPetApi(); +final int petId = 789; // int | ID of pet to return try { - var result = api_instance.getPetById(petId); - print(result); -} catch (e) { + final response = api.getPetById(petId); + print(response); +} catch on DioError (e) { print('Exception when calling PetApi->getPetById: $e\n'); } ``` @@ -254,12 +254,12 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = new PetApi(); -var pet = new Pet(); // Pet | Pet object that needs to be added to the store +final api = Openapi().getPetApi(); +final Pet pet = ; // Pet | Pet object that needs to be added to the store try { - api_instance.updatePet(pet); -} catch (e) { + api.updatePet(pet); +} catch on DioError (e) { print('Exception when calling PetApi->updatePet: $e\n'); } ``` @@ -296,14 +296,14 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = new PetApi(); -var petId = 789; // int | ID of pet that needs to be updated -var name = name_example; // String | Updated name of the pet -var status = status_example; // String | Updated status of the pet +final api = Openapi().getPetApi(); +final int petId = 789; // int | ID of pet that needs to be updated +final String name = name_example; // String | Updated name of the pet +final String status = status_example; // String | Updated status of the pet try { - api_instance.updatePetWithForm(petId, name, status); -} catch (e) { + api.updatePetWithForm(petId, name, status); +} catch on DioError (e) { print('Exception when calling PetApi->updatePetWithForm: $e\n'); } ``` @@ -342,15 +342,15 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = new PetApi(); -var petId = 789; // int | ID of pet to update -var additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server -var file = BINARY_DATA_HERE; // Uint8List | file to upload +final api = Openapi().getPetApi(); +final int petId = 789; // int | ID of pet to update +final String additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server +final MultipartFile file = BINARY_DATA_HERE; // MultipartFile | file to upload try { - var result = api_instance.uploadFile(petId, additionalMetadata, file); - print(result); -} catch (e) { + final response = api.uploadFile(petId, additionalMetadata, file); + print(response); +} catch on DioError (e) { print('Exception when calling PetApi->uploadFile: $e\n'); } ``` @@ -361,7 +361,7 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **int**| ID of pet to update | **additionalMetadata** | **String**| Additional data to pass to server | [optional] - **file** | **Uint8List**| file to upload | [optional] + **file** | **MultipartFile**| file to upload | [optional] ### Return type @@ -389,15 +389,15 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = new PetApi(); -var petId = 789; // int | ID of pet to update -var requiredFile = BINARY_DATA_HERE; // Uint8List | file to upload -var additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server +final api = Openapi().getPetApi(); +final int petId = 789; // int | ID of pet to update +final MultipartFile requiredFile = BINARY_DATA_HERE; // MultipartFile | file to upload +final String additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server try { - var result = api_instance.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); - print(result); -} catch (e) { + final response = api.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + print(response); +} catch on DioError (e) { print('Exception when calling PetApi->uploadFileWithRequiredFile: $e\n'); } ``` @@ -407,7 +407,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **int**| ID of pet to update | - **requiredFile** | **Uint8List**| file to upload | + **requiredFile** | **MultipartFile**| file to upload | **additionalMetadata** | **String**| Additional data to pass to server | [optional] ### Return type diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/StoreApi.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/StoreApi.md index 1fcb8f71eea9..e955785ca95e 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/StoreApi.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/StoreApi.md @@ -9,10 +9,10 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**deleteOrder**](StoreApi.md#deleteorder) | **delete** /store/order/{order_id} | Delete purchase order by ID -[**getInventory**](StoreApi.md#getinventory) | **get** /store/inventory | Returns pet inventories by status -[**getOrderById**](StoreApi.md#getorderbyid) | **get** /store/order/{order_id} | Find purchase order by ID -[**placeOrder**](StoreApi.md#placeorder) | **post** /store/order | Place an order for a pet +[**deleteOrder**](StoreApi.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet # **deleteOrder** @@ -26,12 +26,12 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ```dart import 'package:openapi/api.dart'; -var api_instance = new StoreApi(); -var orderId = orderId_example; // String | ID of the order that needs to be deleted +final api = Openapi().getStoreApi(); +final String orderId = orderId_example; // String | ID of the order that needs to be deleted try { - api_instance.deleteOrder(orderId); -} catch (e) { + api.deleteOrder(orderId); +} catch on DioError (e) { print('Exception when calling StoreApi->deleteOrder: $e\n'); } ``` @@ -72,12 +72,12 @@ import 'package:openapi/api.dart'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed //defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; -var api_instance = new StoreApi(); +final api = Openapi().getStoreApi(); try { - var result = api_instance.getInventory(); - print(result); -} catch (e) { + final response = api.getInventory(); + print(response); +} catch on DioError (e) { print('Exception when calling StoreApi->getInventory: $e\n'); } ``` @@ -87,7 +87,7 @@ This endpoint does not need any parameter. ### Return type -**BuiltMap** +**BuiltMap<String, int>** ### Authorization @@ -111,13 +111,13 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ```dart import 'package:openapi/api.dart'; -var api_instance = new StoreApi(); -var orderId = 789; // int | ID of pet that needs to be fetched +final api = Openapi().getStoreApi(); +final int orderId = 789; // int | ID of pet that needs to be fetched try { - var result = api_instance.getOrderById(orderId); - print(result); -} catch (e) { + final response = api.getOrderById(orderId); + print(response); +} catch on DioError (e) { print('Exception when calling StoreApi->getOrderById: $e\n'); } ``` @@ -152,13 +152,13 @@ Place an order for a pet ```dart import 'package:openapi/api.dart'; -var api_instance = new StoreApi(); -var order = new Order(); // Order | order placed for purchasing the pet +final api = Openapi().getStoreApi(); +final Order order = ; // Order | order placed for purchasing the pet try { - var result = api_instance.placeOrder(order); - print(result); -} catch (e) { + final response = api.placeOrder(order); + print(response); +} catch on DioError (e) { print('Exception when calling StoreApi->placeOrder: $e\n'); } ``` diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/UserApi.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/UserApi.md index 62e01652e800..5e96b548e3b0 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/UserApi.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/UserApi.md @@ -9,14 +9,14 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**createUser**](UserApi.md#createuser) | **post** /user | Create user -[**createUsersWithArrayInput**](UserApi.md#createuserswitharrayinput) | **post** /user/createWithArray | Creates list of users with given input array -[**createUsersWithListInput**](UserApi.md#createuserswithlistinput) | **post** /user/createWithList | Creates list of users with given input array -[**deleteUser**](UserApi.md#deleteuser) | **delete** /user/{username} | Delete user -[**getUserByName**](UserApi.md#getuserbyname) | **get** /user/{username} | Get user by user name -[**loginUser**](UserApi.md#loginuser) | **get** /user/login | Logs user into the system -[**logoutUser**](UserApi.md#logoutuser) | **get** /user/logout | Logs out current logged in user session -[**updateUser**](UserApi.md#updateuser) | **put** /user/{username} | Updated user +[**createUser**](UserApi.md#createuser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateuser) | **PUT** /user/{username} | Updated user # **createUser** @@ -30,12 +30,12 @@ This can only be done by the logged in user. ```dart import 'package:openapi/api.dart'; -var api_instance = new UserApi(); -var user = new User(); // User | Created user object +final api = Openapi().getUserApi(); +final User user = ; // User | Created user object try { - api_instance.createUser(user); -} catch (e) { + api.createUser(user); +} catch on DioError (e) { print('Exception when calling UserApi->createUser: $e\n'); } ``` @@ -70,12 +70,12 @@ Creates list of users with given input array ```dart import 'package:openapi/api.dart'; -var api_instance = new UserApi(); -var user = [new BuiltList()]; // BuiltList | List of user object +final api = Openapi().getUserApi(); +final BuiltList user = ; // BuiltList | List of user object try { - api_instance.createUsersWithArrayInput(user); -} catch (e) { + api.createUsersWithArrayInput(user); +} catch on DioError (e) { print('Exception when calling UserApi->createUsersWithArrayInput: $e\n'); } ``` @@ -84,7 +84,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **user** | [**BuiltList**](User.md)| List of user object | + **user** | [**BuiltList<User>**](User.md)| List of user object | ### Return type @@ -110,12 +110,12 @@ Creates list of users with given input array ```dart import 'package:openapi/api.dart'; -var api_instance = new UserApi(); -var user = [new BuiltList()]; // BuiltList | List of user object +final api = Openapi().getUserApi(); +final BuiltList user = ; // BuiltList | List of user object try { - api_instance.createUsersWithListInput(user); -} catch (e) { + api.createUsersWithListInput(user); +} catch on DioError (e) { print('Exception when calling UserApi->createUsersWithListInput: $e\n'); } ``` @@ -124,7 +124,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **user** | [**BuiltList**](User.md)| List of user object | + **user** | [**BuiltList<User>**](User.md)| List of user object | ### Return type @@ -152,12 +152,12 @@ This can only be done by the logged in user. ```dart import 'package:openapi/api.dart'; -var api_instance = new UserApi(); -var username = username_example; // String | The name that needs to be deleted +final api = Openapi().getUserApi(); +final String username = username_example; // String | The name that needs to be deleted try { - api_instance.deleteUser(username); -} catch (e) { + api.deleteUser(username); +} catch on DioError (e) { print('Exception when calling UserApi->deleteUser: $e\n'); } ``` @@ -192,13 +192,13 @@ Get user by user name ```dart import 'package:openapi/api.dart'; -var api_instance = new UserApi(); -var username = username_example; // String | The name that needs to be fetched. Use user1 for testing. +final api = Openapi().getUserApi(); +final String username = username_example; // String | The name that needs to be fetched. Use user1 for testing. try { - var result = api_instance.getUserByName(username); - print(result); -} catch (e) { + final response = api.getUserByName(username); + print(response); +} catch on DioError (e) { print('Exception when calling UserApi->getUserByName: $e\n'); } ``` @@ -233,14 +233,14 @@ Logs user into the system ```dart import 'package:openapi/api.dart'; -var api_instance = new UserApi(); -var username = username_example; // String | The user name for login -var password = password_example; // String | The password for login in clear text +final api = Openapi().getUserApi(); +final String username = username_example; // String | The user name for login +final String password = password_example; // String | The password for login in clear text try { - var result = api_instance.loginUser(username, password); - print(result); -} catch (e) { + final response = api.loginUser(username, password); + print(response); +} catch on DioError (e) { print('Exception when calling UserApi->loginUser: $e\n'); } ``` @@ -276,11 +276,11 @@ Logs out current logged in user session ```dart import 'package:openapi/api.dart'; -var api_instance = new UserApi(); +final api = Openapi().getUserApi(); try { - api_instance.logoutUser(); -} catch (e) { + api.logoutUser(); +} catch on DioError (e) { print('Exception when calling UserApi->logoutUser: $e\n'); } ``` @@ -314,13 +314,13 @@ This can only be done by the logged in user. ```dart import 'package:openapi/api.dart'; -var api_instance = new UserApi(); -var username = username_example; // String | name that need to be deleted -var user = new User(); // User | Updated user object +final api = Openapi().getUserApi(); +final String username = username_example; // String | name that need to be deleted +final User user = ; // User | Updated user object try { - api_instance.updateUser(username, user); -} catch (e) { + api.updateUser(username, user); +} catch on DioError (e) { print('Exception when calling UserApi->updateUser: $e\n'); } ``` diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/openapi.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/openapi.dart index 9234c943ab63..e2ea4292ffed 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/openapi.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/openapi.dart @@ -7,6 +7,7 @@ export 'package:openapi/src/auth/api_key_auth.dart'; export 'package:openapi/src/auth/basic_auth.dart'; export 'package:openapi/src/auth/oauth.dart'; export 'package:openapi/src/serializers.dart'; +export 'package:openapi/src/model/date.dart'; export 'package:openapi/src/api/another_fake_api.dart'; export 'package:openapi/src/api/default_api.dart'; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/another_fake_api.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/another_fake_api.dart index 00d88a5c1786..4d0e1366d063 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/another_fake_api.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/another_fake_api.dart @@ -18,8 +18,19 @@ class AnotherFakeApi { const AnotherFakeApi(this._dio, this._serializers); /// To test special tags - /// /// To test special tags and operation ID starting with number + /// + /// Parameters: + /// * [modelClient] - client model + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [ModelClient] as data + /// Throws [DioError] if API call or serialization fails Future> call123testSpecialTags({ required ModelClient modelClient, CancelToken? cancelToken, @@ -39,9 +50,7 @@ class AnotherFakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -54,7 +63,7 @@ class AnotherFakeApi { const _type = FullType(ModelClient); _bodyData = _serializers.serialize(modelClient, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -63,7 +72,7 @@ class AnotherFakeApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -85,13 +94,13 @@ class AnotherFakeApi { specifiedType: _responseType, ) as ModelClient; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/default_api.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/default_api.dart index 48fc9b8c444a..3a46c9a2048e 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/default_api.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/default_api.dart @@ -17,9 +17,19 @@ class DefaultApi { const DefaultApi(this._dio, this._serializers); + /// fooGet /// /// - /// + /// Parameters: + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [InlineResponseDefault] as data + /// Throws [DioError] if API call or serialization fails Future> fooGet({ CancelToken? cancelToken, Map? headers, @@ -38,9 +48,6 @@ class DefaultApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); @@ -65,13 +72,13 @@ class DefaultApi { specifiedType: _responseType, ) as InlineResponseDefault; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/fake_api.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/fake_api.dart index 3a9501cca3f8..20e4483e544b 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/fake_api.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/fake_api.dart @@ -10,6 +10,7 @@ import 'package:dio/dio.dart'; import 'dart:typed_data'; import 'package:built_collection/built_collection.dart'; import 'package:openapi/src/api_util.dart'; +import 'package:openapi/src/model/date.dart'; import 'package:openapi/src/model/file_schema_test_class.dart'; import 'package:openapi/src/model/health_check_result.dart'; import 'package:openapi/src/model/model_client.dart'; @@ -27,8 +28,18 @@ class FakeApi { const FakeApi(this._dio, this._serializers); /// Health check endpoint - /// /// + /// + /// Parameters: + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [HealthCheckResult] as data + /// Throws [DioError] if API call or serialization fails Future> fakeHealthGet({ CancelToken? cancelToken, Map? headers, @@ -47,9 +58,6 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); @@ -74,13 +82,13 @@ class FakeApi { specifiedType: _responseType, ) as HealthCheckResult; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -96,8 +104,21 @@ class FakeApi { } /// test http signature authentication - /// /// + /// + /// Parameters: + /// * [pet] - Pet object that needs to be added to the store + /// * [query1] - query parameter + /// * [header1] - header parameter + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> fakeHttpSignatureTest({ required Pet pet, String? query1, @@ -125,10 +146,7 @@ class FakeApi { ], ...?extra, }, - contentType: [ - 'application/json', - 'application/xml', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -142,7 +160,7 @@ class FakeApi { const _type = FullType(Pet); _bodyData = _serializers.serialize(pet, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -151,7 +169,7 @@ class FakeApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -167,9 +185,20 @@ class FakeApi { return _response; } - /// - /// + /// fakeOuterBooleanSerialize /// Test serialization of outer boolean types + /// + /// Parameters: + /// * [body] - Input boolean as post body + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [bool] as data + /// Throws [DioError] if API call or serialization fails Future> fakeOuterBooleanSerialize({ bool? body, CancelToken? cancelToken, @@ -189,9 +218,7 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -203,7 +230,7 @@ class FakeApi { try { _bodyData = body; - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -212,7 +239,7 @@ class FakeApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -230,13 +257,13 @@ class FakeApi { try { _responseData = _response.data as bool; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -251,9 +278,20 @@ class FakeApi { ); } - /// - /// + /// fakeOuterCompositeSerialize /// Test serialization of object with outer number type + /// + /// Parameters: + /// * [outerComposite] - Input composite as post body + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [OuterComposite] as data + /// Throws [DioError] if API call or serialization fails Future> fakeOuterCompositeSerialize({ OuterComposite? outerComposite, CancelToken? cancelToken, @@ -273,9 +311,7 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -288,7 +324,7 @@ class FakeApi { const _type = FullType(OuterComposite); _bodyData = outerComposite == null ? null : _serializers.serialize(outerComposite, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -297,7 +333,7 @@ class FakeApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -319,13 +355,13 @@ class FakeApi { specifiedType: _responseType, ) as OuterComposite; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -340,9 +376,20 @@ class FakeApi { ); } - /// - /// + /// fakeOuterNumberSerialize /// Test serialization of outer number types + /// + /// Parameters: + /// * [body] - Input number as post body + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [num] as data + /// Throws [DioError] if API call or serialization fails Future> fakeOuterNumberSerialize({ num? body, CancelToken? cancelToken, @@ -362,9 +409,7 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -376,7 +421,7 @@ class FakeApi { try { _bodyData = body; - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -385,7 +430,7 @@ class FakeApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -403,13 +448,13 @@ class FakeApi { try { _responseData = _response.data as num; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -424,9 +469,20 @@ class FakeApi { ); } - /// - /// + /// fakeOuterStringSerialize /// Test serialization of outer string types + /// + /// Parameters: + /// * [body] - Input string as post body + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [String] as data + /// Throws [DioError] if API call or serialization fails Future> fakeOuterStringSerialize({ String? body, CancelToken? cancelToken, @@ -446,9 +502,7 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -460,7 +514,7 @@ class FakeApi { try { _bodyData = body; - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -469,7 +523,7 @@ class FakeApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -487,13 +541,13 @@ class FakeApi { try { _responseData = _response.data as String; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -508,9 +562,20 @@ class FakeApi { ); } - /// - /// + /// fakePropertyEnumIntegerSerialize /// Test serialization of enum (int) properties with examples + /// + /// Parameters: + /// * [outerObjectWithEnumProperty] - Input enum (int) as post body + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [OuterObjectWithEnumProperty] as data + /// Throws [DioError] if API call or serialization fails Future> fakePropertyEnumIntegerSerialize({ required OuterObjectWithEnumProperty outerObjectWithEnumProperty, CancelToken? cancelToken, @@ -530,9 +595,7 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -545,7 +608,7 @@ class FakeApi { const _type = FullType(OuterObjectWithEnumProperty); _bodyData = _serializers.serialize(outerObjectWithEnumProperty, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -554,7 +617,7 @@ class FakeApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -576,13 +639,13 @@ class FakeApi { specifiedType: _responseType, ) as OuterObjectWithEnumProperty; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -597,9 +660,90 @@ class FakeApi { ); } - /// + /// testBodyWithBinary + /// For this test, the body has to be a binary file. + /// + /// Parameters: + /// * [body] - image to upload + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress /// - /// For this test, the body for this request much reference a schema named `File`. + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails + Future> testBodyWithBinary({ + required MultipartFile body, + CancelToken? cancelToken, + Map? headers, + Map? extra, + ValidateStatus? validateStatus, + ProgressCallback? onSendProgress, + ProgressCallback? onReceiveProgress, + }) async { + final _path = r'/fake/body-with-binary'; + final _options = Options( + method: r'PUT', + headers: { + ...?headers, + }, + extra: { + 'secure': >[], + ...?extra, + }, + contentType: 'image/png', + validateStatus: validateStatus, + ); + + final _queryParameters = { + }; + + dynamic _bodyData; + + try { + _bodyData = body.finalize(); + + } catch(error, stackTrace) { + throw DioError( + requestOptions: _options.compose( + _dio.options, + _path, + queryParameters: _queryParameters, + ), + type: DioErrorType.other, + error: error, + )..stackTrace = stackTrace; + } + + final _response = await _dio.request( + _path, + data: _bodyData, + options: _options, + queryParameters: _queryParameters, + cancelToken: cancelToken, + onSendProgress: onSendProgress, + onReceiveProgress: onReceiveProgress, + ); + + return _response; + } + + /// testBodyWithFileSchema + /// For this test, the body for this request must reference a schema named `File`. + /// + /// Parameters: + /// * [fileSchemaTestClass] + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> testBodyWithFileSchema({ required FileSchemaTestClass fileSchemaTestClass, CancelToken? cancelToken, @@ -619,9 +763,7 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -634,7 +776,7 @@ class FakeApi { const _type = FullType(FileSchemaTestClass); _bodyData = _serializers.serialize(fileSchemaTestClass, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -643,7 +785,7 @@ class FakeApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -659,9 +801,21 @@ class FakeApi { return _response; } + /// testBodyWithQueryParams /// /// - /// + /// Parameters: + /// * [query] + /// * [user] + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> testBodyWithQueryParams({ required String query, required User user, @@ -682,9 +836,7 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -698,7 +850,7 @@ class FakeApi { const _type = FullType(User); _bodyData = _serializers.serialize(user, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -707,7 +859,7 @@ class FakeApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -723,9 +875,20 @@ class FakeApi { return _response; } - /// To test \"client\" model + /// To test \"client\" model + /// To test \"client\" model + /// + /// Parameters: + /// * [modelClient] - client model + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress /// - /// To test \"client\" model + /// Returns a [Future] containing a [Response] with a [ModelClient] as data + /// Throws [DioError] if API call or serialization fails Future> testClientModel({ required ModelClient modelClient, CancelToken? cancelToken, @@ -745,9 +908,7 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -760,7 +921,7 @@ class FakeApi { const _type = FullType(ModelClient); _bodyData = _serializers.serialize(modelClient, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -769,7 +930,7 @@ class FakeApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -791,13 +952,13 @@ class FakeApi { specifiedType: _responseType, ) as ModelClient; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -813,8 +974,32 @@ class FakeApi { } /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Parameters: + /// * [number] - None + /// * [double_] - None + /// * [patternWithoutDelimiter] - None + /// * [byte] - None + /// * [integer] - None + /// * [int32] - None + /// * [int64] - None + /// * [float] - None + /// * [string] - None + /// * [binary] - None + /// * [date] - None + /// * [dateTime] - None + /// * [password] - None + /// * [callback] - None + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> testEndpointParameters({ required num number, required double double_, @@ -826,7 +1011,7 @@ class FakeApi { double? float, String? string, Uint8List? binary, - DateTime? date, + Date? date, DateTime? dateTime, String? password, String? callback, @@ -852,9 +1037,7 @@ class FakeApi { ], ...?extra, }, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', validateStatus: validateStatus, ); @@ -874,14 +1057,14 @@ class FakeApi { if (string != null) r'string': encodeFormParameter(_serializers, string, const FullType(String)), r'pattern_without_delimiter': encodeFormParameter(_serializers, patternWithoutDelimiter, const FullType(String)), r'byte': encodeFormParameter(_serializers, byte, const FullType(String)), - if (binary != null) r'binary': MultipartFile.fromBytes(binary, filename: r'binary'), - if (date != null) r'date': encodeFormParameter(_serializers, date, const FullType(DateTime)), + if (binary != null) r'binary': binary, + if (date != null) r'date': encodeFormParameter(_serializers, date, const FullType(Date)), if (dateTime != null) r'dateTime': encodeFormParameter(_serializers, dateTime, const FullType(DateTime)), if (password != null) r'password': encodeFormParameter(_serializers, password, const FullType(String)), if (callback != null) r'callback': encodeFormParameter(_serializers, callback, const FullType(String)), }; - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -890,7 +1073,7 @@ class FakeApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -907,8 +1090,26 @@ class FakeApi { } /// To test enum parameters - /// /// To test enum parameters + /// + /// Parameters: + /// * [enumHeaderStringArray] - Header parameter enum test (string array) + /// * [enumHeaderString] - Header parameter enum test (string) + /// * [enumQueryStringArray] - Query parameter enum test (string array) + /// * [enumQueryString] - Query parameter enum test (string) + /// * [enumQueryInteger] - Query parameter enum test (double) + /// * [enumQueryDouble] - Query parameter enum test (double) + /// * [enumFormStringArray] - Form parameter enum test (string array) + /// * [enumFormString] - Form parameter enum test (string) + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> testEnumParameters({ BuiltList? enumHeaderStringArray, String? enumHeaderString, @@ -937,9 +1138,7 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', validateStatus: validateStatus, ); @@ -958,7 +1157,7 @@ class FakeApi { if (enumFormString != null) r'enum_form_string': encodeFormParameter(_serializers, enumFormString, const FullType(String)), }; - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -967,7 +1166,7 @@ class FakeApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -984,8 +1183,24 @@ class FakeApi { } /// Fake endpoint to test group parameters (optional) - /// /// Fake endpoint to test group parameters (optional) + /// + /// Parameters: + /// * [requiredStringGroup] - Required String in group parameters + /// * [requiredBooleanGroup] - Required Boolean in group parameters + /// * [requiredInt64Group] - Required Integer in group parameters + /// * [stringGroup] - String in group parameters + /// * [booleanGroup] - Boolean in group parameters + /// * [int64Group] - Integer in group parameters + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> testGroupParameters({ required int requiredStringGroup, required bool requiredBooleanGroup, @@ -1017,9 +1232,6 @@ class FakeApi { ], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); @@ -1043,8 +1255,19 @@ class FakeApi { } /// test inline additionalProperties - /// /// + /// + /// Parameters: + /// * [requestBody] - request body + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> testInlineAdditionalProperties({ required BuiltMap requestBody, CancelToken? cancelToken, @@ -1064,9 +1287,7 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -1079,7 +1300,7 @@ class FakeApi { const _type = FullType(BuiltMap, [FullType(String), FullType(String)]); _bodyData = _serializers.serialize(requestBody, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -1088,7 +1309,7 @@ class FakeApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -1105,8 +1326,20 @@ class FakeApi { } /// test json serialization of form data - /// /// + /// + /// Parameters: + /// * [param] - field1 + /// * [param2] - field2 + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> testJsonFormData({ required String param, required String param2, @@ -1127,9 +1360,7 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', validateStatus: validateStatus, ); @@ -1144,7 +1375,7 @@ class FakeApi { r'param2': encodeFormParameter(_serializers, param2, const FullType(String)), }; - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -1153,7 +1384,7 @@ class FakeApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -1169,9 +1400,24 @@ class FakeApi { return _response; } - /// - /// + /// testQueryParameterCollectionFormat /// To test the collection format in query parameters + /// + /// Parameters: + /// * [pipe] + /// * [ioutil] + /// * [http] + /// * [url] + /// * [context] + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> testQueryParameterCollectionFormat({ required BuiltList pipe, required BuiltList ioutil, @@ -1195,9 +1441,6 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/fake_classname_tags123_api.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/fake_classname_tags123_api.dart index 01d0383fd160..e48c38c96ba6 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/fake_classname_tags123_api.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/fake_classname_tags123_api.dart @@ -18,8 +18,19 @@ class FakeClassnameTags123Api { const FakeClassnameTags123Api(this._dio, this._serializers); /// To test class name in snake case - /// /// To test class name in snake case + /// + /// Parameters: + /// * [modelClient] - client model + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [ModelClient] as data + /// Throws [DioError] if API call or serialization fails Future> testClassname({ required ModelClient modelClient, CancelToken? cancelToken, @@ -46,9 +57,7 @@ class FakeClassnameTags123Api { ], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -61,7 +70,7 @@ class FakeClassnameTags123Api { const _type = FullType(ModelClient); _bodyData = _serializers.serialize(modelClient, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -70,7 +79,7 @@ class FakeClassnameTags123Api { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -92,13 +101,13 @@ class FakeClassnameTags123Api { specifiedType: _responseType, ) as ModelClient; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/pet_api.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/pet_api.dart index 219b0cecd269..be1d9d27924d 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/pet_api.dart @@ -7,7 +7,6 @@ import 'dart:async'; import 'package:built_value/serializer.dart'; import 'package:dio/dio.dart'; -import 'dart:typed_data'; import 'package:built_collection/built_collection.dart'; import 'package:openapi/src/api_util.dart'; import 'package:openapi/src/model/api_response.dart'; @@ -22,8 +21,19 @@ class PetApi { const PetApi(this._dio, this._serializers); /// Add a new pet to the store - /// /// + /// + /// Parameters: + /// * [pet] - Pet object that needs to be added to the store + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> addPet({ required Pet pet, CancelToken? cancelToken, @@ -48,10 +58,7 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'application/json', - 'application/xml', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -64,7 +71,7 @@ class PetApi { const _type = FullType(Pet); _bodyData = _serializers.serialize(pet, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -73,7 +80,7 @@ class PetApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -90,8 +97,20 @@ class PetApi { } /// Deletes a pet - /// /// + /// + /// Parameters: + /// * [petId] - Pet id to delete + /// * [apiKey] + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> deletePet({ required int petId, String? apiKey, @@ -118,9 +137,6 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); @@ -140,8 +156,19 @@ class PetApi { } /// Finds Pets by status - /// /// Multiple status values can be provided with comma separated strings + /// + /// Parameters: + /// * [status] - Status values that need to be considered for filter + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [BuiltList] as data + /// Throws [DioError] if API call or serialization fails Future>> findPetsByStatus({ required BuiltList status, CancelToken? cancelToken, @@ -166,9 +193,6 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); @@ -194,13 +218,13 @@ class PetApi { specifiedType: _responseType, ) as BuiltList; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response>( @@ -216,8 +240,20 @@ class PetApi { } /// Finds Pets by tags - /// /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Parameters: + /// * [tags] - Tags to filter by + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [BuiltSet] as data + /// Throws [DioError] if API call or serialization fails + @Deprecated('This operation has been deprecated') Future>> findPetsByTags({ required BuiltSet tags, CancelToken? cancelToken, @@ -242,9 +278,6 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); @@ -270,13 +303,13 @@ class PetApi { specifiedType: _responseType, ) as BuiltSet; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response>( @@ -292,8 +325,19 @@ class PetApi { } /// Find pet by ID - /// /// Returns a single pet + /// + /// Parameters: + /// * [petId] - ID of pet to return + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [Pet] as data + /// Throws [DioError] if API call or serialization fails Future> getPetById({ required int petId, CancelToken? cancelToken, @@ -320,9 +364,6 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); @@ -347,13 +388,13 @@ class PetApi { specifiedType: _responseType, ) as Pet; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -369,8 +410,19 @@ class PetApi { } /// Update an existing pet - /// /// + /// + /// Parameters: + /// * [pet] - Pet object that needs to be added to the store + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> updatePet({ required Pet pet, CancelToken? cancelToken, @@ -395,10 +447,7 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'application/json', - 'application/xml', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -411,7 +460,7 @@ class PetApi { const _type = FullType(Pet); _bodyData = _serializers.serialize(pet, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -420,7 +469,7 @@ class PetApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -437,8 +486,21 @@ class PetApi { } /// Updates a pet in the store with form data - /// /// + /// + /// Parameters: + /// * [petId] - ID of pet that needs to be updated + /// * [name] - Updated name of the pet + /// * [status] - Updated status of the pet + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> updatePetWithForm({ required int petId, String? name, @@ -465,9 +527,7 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', validateStatus: validateStatus, ); @@ -482,7 +542,7 @@ class PetApi { if (status != null) r'status': encodeFormParameter(_serializers, status, const FullType(String)), }; - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -491,7 +551,7 @@ class PetApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -508,12 +568,25 @@ class PetApi { } /// uploads an image - /// /// + /// + /// Parameters: + /// * [petId] - ID of pet to update + /// * [additionalMetadata] - Additional data to pass to server + /// * [file] - file to upload + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [ApiResponse] as data + /// Throws [DioError] if API call or serialization fails Future> uploadFile({ required int petId, String? additionalMetadata, - Uint8List? file, + MultipartFile? file, CancelToken? cancelToken, Map? headers, Map? extra, @@ -536,9 +609,7 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'multipart/form-data', - ].first, + contentType: 'multipart/form-data', validateStatus: validateStatus, ); @@ -550,10 +621,10 @@ class PetApi { try { _bodyData = FormData.fromMap({ if (additionalMetadata != null) r'additionalMetadata': encodeFormParameter(_serializers, additionalMetadata, const FullType(String)), - if (file != null) r'file': MultipartFile.fromBytes(file, filename: r'file'), + if (file != null) r'file': file, }); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -562,7 +633,7 @@ class PetApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -584,13 +655,13 @@ class PetApi { specifiedType: _responseType, ) as ApiResponse; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -606,11 +677,24 @@ class PetApi { } /// uploads an image (required) - /// /// + /// + /// Parameters: + /// * [petId] - ID of pet to update + /// * [requiredFile] - file to upload + /// * [additionalMetadata] - Additional data to pass to server + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [ApiResponse] as data + /// Throws [DioError] if API call or serialization fails Future> uploadFileWithRequiredFile({ required int petId, - required Uint8List requiredFile, + required MultipartFile requiredFile, String? additionalMetadata, CancelToken? cancelToken, Map? headers, @@ -634,9 +718,7 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'multipart/form-data', - ].first, + contentType: 'multipart/form-data', validateStatus: validateStatus, ); @@ -648,10 +730,10 @@ class PetApi { try { _bodyData = FormData.fromMap({ if (additionalMetadata != null) r'additionalMetadata': encodeFormParameter(_serializers, additionalMetadata, const FullType(String)), - r'requiredFile': MultipartFile.fromBytes(requiredFile, filename: r'requiredFile'), + r'requiredFile': requiredFile, }); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -660,7 +742,7 @@ class PetApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -682,13 +764,13 @@ class PetApi { specifiedType: _responseType, ) as ApiResponse; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/store_api.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/store_api.dart index 0c0b9f44794f..24c4bd7a55c8 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/store_api.dart @@ -19,8 +19,19 @@ class StoreApi { const StoreApi(this._dio, this._serializers); /// Delete purchase order by ID + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// - /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// Parameters: + /// * [orderId] - ID of the order that needs to be deleted + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> deleteOrder({ required String orderId, CancelToken? cancelToken, @@ -40,9 +51,6 @@ class StoreApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); @@ -62,8 +70,18 @@ class StoreApi { } /// Returns pet inventories by status - /// /// Returns a map of status codes to quantities + /// + /// Parameters: + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [BuiltMap] as data + /// Throws [DioError] if API call or serialization fails Future>> getInventory({ CancelToken? cancelToken, Map? headers, @@ -89,9 +107,6 @@ class StoreApi { ], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); @@ -116,13 +131,13 @@ class StoreApi { specifiedType: _responseType, ) as BuiltMap; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response>( @@ -138,8 +153,19 @@ class StoreApi { } /// Find purchase order by ID + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// - /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// Parameters: + /// * [orderId] - ID of pet that needs to be fetched + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [Order] as data + /// Throws [DioError] if API call or serialization fails Future> getOrderById({ required int orderId, CancelToken? cancelToken, @@ -159,9 +185,6 @@ class StoreApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); @@ -186,13 +209,13 @@ class StoreApi { specifiedType: _responseType, ) as Order; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -208,8 +231,19 @@ class StoreApi { } /// Place an order for a pet - /// /// + /// + /// Parameters: + /// * [order] - order placed for purchasing the pet + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [Order] as data + /// Throws [DioError] if API call or serialization fails Future> placeOrder({ required Order order, CancelToken? cancelToken, @@ -229,9 +263,7 @@ class StoreApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -244,7 +276,7 @@ class StoreApi { const _type = FullType(Order); _bodyData = _serializers.serialize(order, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -253,7 +285,7 @@ class StoreApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -275,13 +307,13 @@ class StoreApi { specifiedType: _responseType, ) as Order; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/user_api.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/user_api.dart index c0551df5e516..a05524844039 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/user_api.dart @@ -19,8 +19,19 @@ class UserApi { const UserApi(this._dio, this._serializers); /// Create user - /// /// This can only be done by the logged in user. + /// + /// Parameters: + /// * [user] - Created user object + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> createUser({ required User user, CancelToken? cancelToken, @@ -40,9 +51,7 @@ class UserApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -55,7 +64,7 @@ class UserApi { const _type = FullType(User); _bodyData = _serializers.serialize(user, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -64,7 +73,7 @@ class UserApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -81,8 +90,19 @@ class UserApi { } /// Creates list of users with given input array - /// /// + /// + /// Parameters: + /// * [user] - List of user object + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> createUsersWithArrayInput({ required BuiltList user, CancelToken? cancelToken, @@ -102,9 +122,7 @@ class UserApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -117,7 +135,7 @@ class UserApi { const _type = FullType(BuiltList, [FullType(User)]); _bodyData = _serializers.serialize(user, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -126,7 +144,7 @@ class UserApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -143,8 +161,19 @@ class UserApi { } /// Creates list of users with given input array - /// /// + /// + /// Parameters: + /// * [user] - List of user object + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> createUsersWithListInput({ required BuiltList user, CancelToken? cancelToken, @@ -164,9 +193,7 @@ class UserApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -179,7 +206,7 @@ class UserApi { const _type = FullType(BuiltList, [FullType(User)]); _bodyData = _serializers.serialize(user, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -188,7 +215,7 @@ class UserApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -205,8 +232,19 @@ class UserApi { } /// Delete user - /// /// This can only be done by the logged in user. + /// + /// Parameters: + /// * [username] - The name that needs to be deleted + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> deleteUser({ required String username, CancelToken? cancelToken, @@ -226,9 +264,6 @@ class UserApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); @@ -248,8 +283,19 @@ class UserApi { } /// Get user by user name - /// /// + /// + /// Parameters: + /// * [username] - The name that needs to be fetched. Use user1 for testing. + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [User] as data + /// Throws [DioError] if API call or serialization fails Future> getUserByName({ required String username, CancelToken? cancelToken, @@ -269,9 +315,6 @@ class UserApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); @@ -296,13 +339,13 @@ class UserApi { specifiedType: _responseType, ) as User; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -318,8 +361,20 @@ class UserApi { } /// Logs user into the system - /// /// + /// + /// Parameters: + /// * [username] - The user name for login + /// * [password] - The password for login in clear text + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] containing a [Response] with a [String] as data + /// Throws [DioError] if API call or serialization fails Future> loginUser({ required String username, required String password, @@ -340,9 +395,6 @@ class UserApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); @@ -365,13 +417,13 @@ class UserApi { try { _responseData = _response.data as String; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -387,8 +439,18 @@ class UserApi { } /// Logs out current logged in user session - /// /// + /// + /// Parameters: + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> logoutUser({ CancelToken? cancelToken, Map? headers, @@ -407,9 +469,6 @@ class UserApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); @@ -429,8 +488,20 @@ class UserApi { } /// Updated user - /// /// This can only be done by the logged in user. + /// + /// Parameters: + /// * [username] - name that need to be deleted + /// * [user] - Updated user object + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioError] if API call or serialization fails Future> updateUser({ required String username, required User user, @@ -451,9 +522,7 @@ class UserApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); @@ -466,7 +535,7 @@ class UserApi { const _type = FullType(User); _bodyData = _serializers.serialize(user, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -475,7 +544,7 @@ class UserApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/date_serializer.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/date_serializer.dart new file mode 100644 index 000000000000..db3c5c437db1 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/date_serializer.dart @@ -0,0 +1,31 @@ +// +// AUTO-GENERATED FILE, DO NOT MODIFY! +// + +import 'package:built_collection/built_collection.dart'; +import 'package:built_value/serializer.dart'; +import 'package:openapi/src/model/date.dart'; + +class DateSerializer implements PrimitiveSerializer { + + const DateSerializer(); + + @override + Iterable get types => BuiltList.of([Date]); + + @override + String get wireName => 'Date'; + + @override + Date deserialize(Serializers serializers, Object serialized, + {FullType specifiedType = FullType.unspecified}) { + final parsed = DateTime.parse(serialized as String); + return Date(parsed.year, parsed.month, parsed.day); + } + + @override + Object serialize(Serializers serializers, Date date, + {FullType specifiedType = FullType.unspecified}) { + return date.toString(); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/additional_properties_class.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/additional_properties_class.dart index f92d8336bbb5..25e0fb4fdbff 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/additional_properties_class.dart @@ -8,8 +8,11 @@ import 'package:built_value/serializer.dart'; part 'additional_properties_class.g.dart'; - - +/// AdditionalPropertiesClass +/// +/// Properties: +/// * [mapProperty] +/// * [mapOfMapProperty] abstract class AdditionalPropertiesClass implements Built { @BuiltValueField(wireName: r'map_property') BuiltMap? get mapProperty; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/animal.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/animal.dart index 14419f9eca45..d51c6d7b0be3 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/animal.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/animal.dart @@ -7,8 +7,11 @@ import 'package:built_value/serializer.dart'; part 'animal.g.dart'; - - +/// Animal +/// +/// Properties: +/// * [className] +/// * [color] abstract class Animal implements Built { @BuiltValueField(wireName: r'className') String get className; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/api_response.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/api_response.dart index 4c9fa0b7159c..fc9554f36cec 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/api_response.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/api_response.dart @@ -7,8 +7,12 @@ import 'package:built_value/serializer.dart'; part 'api_response.g.dart'; - - +/// ApiResponse +/// +/// Properties: +/// * [code] +/// * [type] +/// * [message] abstract class ApiResponse implements Built { @BuiltValueField(wireName: r'code') int? get code; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_of_array_of_number_only.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_of_array_of_number_only.dart index 0f86aa08c5bb..899697f7efc8 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_of_array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_of_array_of_number_only.dart @@ -8,8 +8,10 @@ import 'package:built_value/serializer.dart'; part 'array_of_array_of_number_only.g.dart'; - - +/// ArrayOfArrayOfNumberOnly +/// +/// Properties: +/// * [arrayArrayNumber] abstract class ArrayOfArrayOfNumberOnly implements Built { @BuiltValueField(wireName: r'ArrayArrayNumber') BuiltList>? get arrayArrayNumber; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_of_number_only.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_of_number_only.dart index b68a04794aa5..2e886df9b04c 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_of_number_only.dart @@ -8,8 +8,10 @@ import 'package:built_value/serializer.dart'; part 'array_of_number_only.g.dart'; - - +/// ArrayOfNumberOnly +/// +/// Properties: +/// * [arrayNumber] abstract class ArrayOfNumberOnly implements Built { @BuiltValueField(wireName: r'ArrayNumber') BuiltList? get arrayNumber; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_test.dart index e9657764dc43..82ee6c2c01a9 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_test.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_test.dart @@ -9,8 +9,12 @@ import 'package:built_value/serializer.dart'; part 'array_test.g.dart'; - - +/// ArrayTest +/// +/// Properties: +/// * [arrayOfString] +/// * [arrayArrayOfInteger] +/// * [arrayArrayOfModel] abstract class ArrayTest implements Built { @BuiltValueField(wireName: r'array_of_string') BuiltList? get arrayOfString; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/capitalization.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/capitalization.dart index 9b7cd294db36..fb1bfd7a5b92 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/capitalization.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/capitalization.dart @@ -7,8 +7,15 @@ import 'package:built_value/serializer.dart'; part 'capitalization.g.dart'; - - +/// Capitalization +/// +/// Properties: +/// * [smallCamel] +/// * [capitalCamel] +/// * [smallSnake] +/// * [capitalSnake] +/// * [sCAETHFlowPoints] +/// * [ATT_NAME] - Name of the pet abstract class Capitalization implements Built { @BuiltValueField(wireName: r'smallCamel') String? get smallCamel; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/cat.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/cat.dart index 1ee68912ba71..fa9282bb8cb0 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/cat.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/cat.dart @@ -11,6 +11,12 @@ part 'cat.g.dart'; // ignore_for_file: unused_import +/// Cat +/// +/// Properties: +/// * [className] +/// * [color] +/// * [declawed] abstract class Cat implements Built { @BuiltValueField(wireName: r'className') String get className; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/cat_all_of.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/cat_all_of.dart index cbbf63216034..b8019b936d8f 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/cat_all_of.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/cat_all_of.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'cat_all_of.g.dart'; - - +/// CatAllOf +/// +/// Properties: +/// * [declawed] abstract class CatAllOf implements Built { @BuiltValueField(wireName: r'declawed') bool? get declawed; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/category.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/category.dart index 3bc36cefbcc2..351842659923 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/category.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/category.dart @@ -7,8 +7,11 @@ import 'package:built_value/serializer.dart'; part 'category.g.dart'; - - +/// Category +/// +/// Properties: +/// * [id] +/// * [name] abstract class Category implements Built { @BuiltValueField(wireName: r'id') int? get id; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/class_model.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/class_model.dart index bdc392005cf0..7b99dc2be1ae 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/class_model.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/class_model.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'class_model.g.dart'; - - +/// Model for testing model with \"_class\" property +/// +/// Properties: +/// * [class_] abstract class ClassModel implements Built { @BuiltValueField(wireName: r'_class') String? get class_; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/date.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/date.dart new file mode 100644 index 000000000000..c3a87eae259c --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/date.dart @@ -0,0 +1,69 @@ +/// A gregorian calendar date generated by +/// OpenAPI generator to differentiate +/// between [DateTime] and [Date] formats. +class Date implements Comparable { + final int year; + + /// January is 1. + final int month; + + /// First day is 1. + final int day; + + Date(this.year, this.month, this.day); + + /// The current date + static Date now({bool utc = false}) { + var now = DateTime.now(); + if (utc) { + now = now.toUtc(); + } + return now.toDate(); + } + + /// Convert to a [DateTime]. + DateTime toDateTime({bool utc = false}) { + if (utc) { + DateTime.utc(year, month, day); + } + return DateTime(year, month, day); + } + + @override + int compareTo(Date other) { + int d = year.compareTo(other.year); + if (d != 0) { + return d; + } + d = month.compareTo(other.month); + if (d != 0) { + return d; + } + return day.compareTo(other.day); + } + + @override + bool operator ==(Object other) => + identical(this, other) || + other is Date && + runtimeType == other.runtimeType && + year == other.year && + month == other.month && + day == other.day; + + @override + int get hashCode => year.hashCode ^ month.hashCode ^ day.hashCode; + + @override + String toString() { + final yyyy = year.toString(); + final mm = month.toString().padLeft(2, '0'); + final dd = day.toString().padLeft(2, '0'); + + return '$yyyy-$mm-$dd'; + } +} + +extension DateTimeToDate on DateTime { + Date toDate() => Date(year, month, day); +} \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/dog.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/dog.dart index 63f2d483d5d7..9ca43e054025 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/dog.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/dog.dart @@ -11,6 +11,12 @@ part 'dog.g.dart'; // ignore_for_file: unused_import +/// Dog +/// +/// Properties: +/// * [className] +/// * [color] +/// * [breed] abstract class Dog implements Built { @BuiltValueField(wireName: r'className') String get className; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/dog_all_of.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/dog_all_of.dart index e896ffe4b1bf..291310df2c28 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/dog_all_of.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/dog_all_of.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'dog_all_of.g.dart'; - - +/// DogAllOf +/// +/// Properties: +/// * [breed] abstract class DogAllOf implements Built { @BuiltValueField(wireName: r'breed') String? get breed; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/enum_arrays.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/enum_arrays.dart index 371f28947d86..0e28f7247a88 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/enum_arrays.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/enum_arrays.dart @@ -8,8 +8,11 @@ import 'package:built_value/serializer.dart'; part 'enum_arrays.g.dart'; - - +/// EnumArrays +/// +/// Properties: +/// * [justSymbol] +/// * [arrayEnum] abstract class EnumArrays implements Built { @BuiltValueField(wireName: r'just_symbol') EnumArraysJustSymbolEnum? get justSymbol; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/enum_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/enum_test.dart index 51c417dcaddb..8e6d8c6d23e7 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/enum_test.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/enum_test.dart @@ -12,8 +12,17 @@ import 'package:built_value/serializer.dart'; part 'enum_test.g.dart'; - - +/// EnumTest +/// +/// Properties: +/// * [enumString] +/// * [enumStringRequired] +/// * [enumInteger] +/// * [enumNumber] +/// * [outerEnum] +/// * [outerEnumInteger] +/// * [outerEnumDefaultValue] +/// * [outerEnumIntegerDefaultValue] abstract class EnumTest implements Built { @BuiltValueField(wireName: r'enum_string') EnumTestEnumStringEnum? get enumString; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/file_schema_test_class.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/file_schema_test_class.dart index 083b61e326aa..0fdd83670854 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/file_schema_test_class.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/file_schema_test_class.dart @@ -9,8 +9,11 @@ import 'package:built_value/serializer.dart'; part 'file_schema_test_class.g.dart'; - - +/// FileSchemaTestClass +/// +/// Properties: +/// * [file] +/// * [files] abstract class FileSchemaTestClass implements Built { @BuiltValueField(wireName: r'file') ModelFile? get file; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/foo.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/foo.dart index 045d8857577e..148b67aacea6 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/foo.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/foo.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'foo.g.dart'; - - +/// Foo +/// +/// Properties: +/// * [bar] abstract class Foo implements Built { @BuiltValueField(wireName: r'bar') String? get bar; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/format_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/format_test.dart index 60879a1479ad..eb013af8673c 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/format_test.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/format_test.dart @@ -3,13 +3,31 @@ // import 'dart:typed_data'; +import 'package:openapi/src/model/date.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; part 'format_test.g.dart'; - - +/// FormatTest +/// +/// Properties: +/// * [integer] +/// * [int32] +/// * [int64] +/// * [number] +/// * [float] +/// * [double_] +/// * [decimal] +/// * [string] +/// * [byte] +/// * [binary] +/// * [date] +/// * [dateTime] +/// * [uuid] +/// * [password] +/// * [patternWithDigits] - A string that is a 10 digit number. Can have leading zeros. +/// * [patternWithDigitsAndDelimiter] - A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. abstract class FormatTest implements Built { @BuiltValueField(wireName: r'integer') int? get integer; @@ -42,7 +60,7 @@ abstract class FormatTest implements Built { Uint8List? get binary; @BuiltValueField(wireName: r'date') - DateTime get date; + Date get date; @BuiltValueField(wireName: r'dateTime') DateTime? get dateTime; @@ -141,7 +159,7 @@ class _$FormatTestSerializer implements StructuredSerializer { result ..add(r'date') ..add(serializers.serialize(object.date, - specifiedType: const FullType(DateTime))); + specifiedType: const FullType(Date))); if (object.dateTime != null) { result ..add(r'dateTime') @@ -226,7 +244,7 @@ class _$FormatTestSerializer implements StructuredSerializer { break; case r'date': result.date = serializers.deserialize(value, - specifiedType: const FullType(DateTime)) as DateTime; + specifiedType: const FullType(Date)) as Date; break; case r'dateTime': result.dateTime = serializers.deserialize(value, diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/has_only_read_only.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/has_only_read_only.dart index f7cb2cd2e5ab..d1ed7b46954c 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/has_only_read_only.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/has_only_read_only.dart @@ -7,8 +7,11 @@ import 'package:built_value/serializer.dart'; part 'has_only_read_only.g.dart'; - - +/// HasOnlyReadOnly +/// +/// Properties: +/// * [bar] +/// * [foo] abstract class HasOnlyReadOnly implements Built { @BuiltValueField(wireName: r'bar') String? get bar; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/health_check_result.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/health_check_result.dart index 69bca6dce0fb..a071f9567878 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/health_check_result.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/health_check_result.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'health_check_result.g.dart'; - - +/// Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. +/// +/// Properties: +/// * [nullableMessage] abstract class HealthCheckResult implements Built { @BuiltValueField(wireName: r'NullableMessage') String? get nullableMessage; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/inline_response_default.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/inline_response_default.dart index 875b612c5d6d..d6eb09c8797f 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/inline_response_default.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/inline_response_default.dart @@ -8,8 +8,10 @@ import 'package:built_value/serializer.dart'; part 'inline_response_default.g.dart'; - - +/// InlineResponseDefault +/// +/// Properties: +/// * [string] abstract class InlineResponseDefault implements Built { @BuiltValueField(wireName: r'string') Foo? get string; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/map_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/map_test.dart index 21af21a52bb9..89fa1e3065e0 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/map_test.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/map_test.dart @@ -8,8 +8,13 @@ import 'package:built_value/serializer.dart'; part 'map_test.g.dart'; - - +/// MapTest +/// +/// Properties: +/// * [mapMapOfString] +/// * [mapOfEnumString] +/// * [directMap] +/// * [indirectMap] abstract class MapTest implements Built { @BuiltValueField(wireName: r'map_map_of_string') BuiltMap>? get mapMapOfString; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/mixed_properties_and_additional_properties_class.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/mixed_properties_and_additional_properties_class.dart index 4da5f4d520df..55328c39f6f0 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/mixed_properties_and_additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/mixed_properties_and_additional_properties_class.dart @@ -9,8 +9,12 @@ import 'package:built_value/serializer.dart'; part 'mixed_properties_and_additional_properties_class.g.dart'; - - +/// MixedPropertiesAndAdditionalPropertiesClass +/// +/// Properties: +/// * [uuid] +/// * [dateTime] +/// * [map] abstract class MixedPropertiesAndAdditionalPropertiesClass implements Built { @BuiltValueField(wireName: r'uuid') String? get uuid; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model200_response.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model200_response.dart index be8614351cb1..f8eaf0f3e2d9 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model200_response.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model200_response.dart @@ -7,8 +7,11 @@ import 'package:built_value/serializer.dart'; part 'model200_response.g.dart'; - - +/// Model for testing model name starting with number +/// +/// Properties: +/// * [name] +/// * [class_] abstract class Model200Response implements Built { @BuiltValueField(wireName: r'name') int? get name; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_client.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_client.dart index 57871562a076..045a68057077 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_client.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_client.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'model_client.g.dart'; - - +/// ModelClient +/// +/// Properties: +/// * [client] abstract class ModelClient implements Built { @BuiltValueField(wireName: r'client') String? get client; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_file.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_file.dart index 8a6c468bc00b..2ad4601d2f08 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_file.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_file.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'model_file.g.dart'; - - +/// Must be named `File` for test. +/// +/// Properties: +/// * [sourceURI] - Test capitalization abstract class ModelFile implements Built { /// Test capitalization @BuiltValueField(wireName: r'sourceURI') diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_list.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_list.dart index 901616e8dc65..4bb83e5f277a 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_list.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_list.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'model_list.g.dart'; - - +/// ModelList +/// +/// Properties: +/// * [n123list] abstract class ModelList implements Built { @BuiltValueField(wireName: r'123-list') String? get n123list; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_return.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_return.dart index 42c03755627d..4e7bad16424e 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_return.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_return.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'model_return.g.dart'; - - +/// Model for testing reserved words +/// +/// Properties: +/// * [return_] abstract class ModelReturn implements Built { @BuiltValueField(wireName: r'return') int? get return_; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/name.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/name.dart index 911fa0a54710..1963c3ace078 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/name.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/name.dart @@ -7,8 +7,13 @@ import 'package:built_value/serializer.dart'; part 'name.g.dart'; - - +/// Model for testing model name same as property name +/// +/// Properties: +/// * [name] +/// * [snakeCase] +/// * [property] +/// * [n123number] abstract class Name implements Built { @BuiltValueField(wireName: r'name') int get name; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/nullable_class.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/nullable_class.dart index d244f5106819..30dc376cb02a 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/nullable_class.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/nullable_class.dart @@ -3,14 +3,28 @@ // import 'package:built_collection/built_collection.dart'; +import 'package:openapi/src/model/date.dart'; import 'package:built_value/json_object.dart'; import 'package:built_value/built_value.dart'; import 'package:built_value/serializer.dart'; part 'nullable_class.g.dart'; - - +/// NullableClass +/// +/// Properties: +/// * [integerProp] +/// * [numberProp] +/// * [booleanProp] +/// * [stringProp] +/// * [dateProp] +/// * [datetimeProp] +/// * [arrayNullableProp] +/// * [arrayAndItemsNullableProp] +/// * [arrayItemsNullable] +/// * [objectNullableProp] +/// * [objectAndItemsNullableProp] +/// * [objectItemsNullable] abstract class NullableClass implements Built { @BuiltValueField(wireName: r'integer_prop') int? get integerProp; @@ -25,7 +39,7 @@ abstract class NullableClass implements Built { result ..add(r'date_prop') ..add(serializers.serialize(object.dateProp, - specifiedType: const FullType(DateTime))); + specifiedType: const FullType(Date))); } if (object.datetimeProp != null) { result @@ -173,7 +187,7 @@ class _$NullableClassSerializer implements StructuredSerializer { break; case r'date_prop': result.dateProp = serializers.deserialize(value, - specifiedType: const FullType(DateTime)) as DateTime; + specifiedType: const FullType(Date)) as Date; break; case r'datetime_prop': result.datetimeProp = serializers.deserialize(value, diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/number_only.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/number_only.dart index 55e00d4d65cf..b423c6fc6566 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/number_only.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'number_only.g.dart'; - - +/// NumberOnly +/// +/// Properties: +/// * [justNumber] abstract class NumberOnly implements Built { @BuiltValueField(wireName: r'JustNumber') num? get justNumber; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/order.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/order.dart index 9c65fbf0c3a4..cdebcd96b1eb 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/order.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/order.dart @@ -8,8 +8,15 @@ import 'package:built_value/serializer.dart'; part 'order.g.dart'; - - +/// Order +/// +/// Properties: +/// * [id] +/// * [petId] +/// * [quantity] +/// * [shipDate] +/// * [status] - Order Status +/// * [complete] abstract class Order implements Built { @BuiltValueField(wireName: r'id') int? get id; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/outer_composite.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/outer_composite.dart index 69007a114640..0a8f4296c13e 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/outer_composite.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/outer_composite.dart @@ -7,8 +7,12 @@ import 'package:built_value/serializer.dart'; part 'outer_composite.g.dart'; - - +/// OuterComposite +/// +/// Properties: +/// * [myNumber] +/// * [myString] +/// * [myBoolean] abstract class OuterComposite implements Built { @BuiltValueField(wireName: r'my_number') num? get myNumber; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/outer_object_with_enum_property.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/outer_object_with_enum_property.dart index 6f4563d7a5eb..a95f92d8837c 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/outer_object_with_enum_property.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/outer_object_with_enum_property.dart @@ -8,8 +8,10 @@ import 'package:built_value/serializer.dart'; part 'outer_object_with_enum_property.g.dart'; - - +/// OuterObjectWithEnumProperty +/// +/// Properties: +/// * [value] abstract class OuterObjectWithEnumProperty implements Built { @BuiltValueField(wireName: r'value') OuterEnumInteger get value; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/pet.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/pet.dart index 99ef939eb1bf..ea94306056cc 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/pet.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/pet.dart @@ -10,8 +10,15 @@ import 'package:built_value/serializer.dart'; part 'pet.g.dart'; - - +/// Pet +/// +/// Properties: +/// * [id] +/// * [category] +/// * [name] +/// * [photoUrls] +/// * [tags] +/// * [status] - pet status in the store abstract class Pet implements Built { @BuiltValueField(wireName: r'id') int? get id; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/read_only_first.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/read_only_first.dart index d53617d1c0b4..ce46f919ea33 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/read_only_first.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/read_only_first.dart @@ -7,8 +7,11 @@ import 'package:built_value/serializer.dart'; part 'read_only_first.g.dart'; - - +/// ReadOnlyFirst +/// +/// Properties: +/// * [bar] +/// * [baz] abstract class ReadOnlyFirst implements Built { @BuiltValueField(wireName: r'bar') String? get bar; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/special_model_name.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/special_model_name.dart index 36880f32998d..dc69b29e4968 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/special_model_name.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/special_model_name.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'special_model_name.g.dart'; - - +/// SpecialModelName +/// +/// Properties: +/// * [dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket] abstract class SpecialModelName implements Built { @BuiltValueField(wireName: r'$special[property.name]') int? get dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/tag.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/tag.dart index d46c2aa40452..6723a6ea9f2f 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/tag.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/tag.dart @@ -7,8 +7,11 @@ import 'package:built_value/serializer.dart'; part 'tag.g.dart'; - - +/// Tag +/// +/// Properties: +/// * [id] +/// * [name] abstract class Tag implements Built { @BuiltValueField(wireName: r'id') int? get id; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/user.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/user.dart index dec21c7e473c..8aeb8f43aded 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/user.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/user.dart @@ -7,8 +7,17 @@ import 'package:built_value/serializer.dart'; part 'user.g.dart'; - - +/// User +/// +/// Properties: +/// * [id] +/// * [username] +/// * [firstName] +/// * [lastName] +/// * [email] +/// * [password] +/// * [phone] +/// * [userStatus] - User Status abstract class User implements Built { @BuiltValueField(wireName: r'id') int? get id; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/serializers.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/serializers.dart index e922e1d467c4..ea2264185dab 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/serializers.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/serializers.dart @@ -2,11 +2,15 @@ // AUTO-GENERATED FILE, DO NOT MODIFY! // +// ignore_for_file: unused_import + import 'package:built_collection/built_collection.dart'; import 'package:built_value/json_object.dart'; import 'package:built_value/serializer.dart'; import 'package:built_value/standard_json_plugin.dart'; import 'package:built_value/iso_8601_date_time_serializer.dart'; +import 'package:openapi/src/date_serializer.dart'; +import 'package:openapi/src/model/date.dart'; import 'package:openapi/src/model/additional_properties_class.dart'; import 'package:openapi/src/model/animal.dart'; @@ -122,6 +126,7 @@ Serializers serializers = (_$serializers.toBuilder() const FullType(BuiltList, [FullType(User)]), () => ListBuilder(), ) + ..add(const DateSerializer()) ..add(Iso8601DateTimeSerializer())) .build(); diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/pom.xml b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/pom.xml index 86285381f975..dec7604a53ac 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/pom.xml +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/pom.xml @@ -39,26 +39,6 @@ - - format - pre-integration-test - - exec - - - dart - - format - - --output=none - . - - - pub-run-build-runner pre-integration-test diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/pubspec.yaml b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/pubspec.yaml index 71d34529fb4c..2a62f274f368 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/pubspec.yaml @@ -1,6 +1,7 @@ name: openapi version: 1.0.0 description: OpenAPI API client +homepage: homepage environment: sdk: '>=2.12.0 <3.0.0' diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/test/fake_api_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/test/fake_api_test.dart index 961e7a5cec73..7dca853fa9d6 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/test/fake_api_test.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/test/fake_api_test.dart @@ -81,7 +81,7 @@ void main() { // // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 // - //Future testEndpointParameters(num number, double double_, String patternWithoutDelimiter, String byte, { int integer, int int32, int int64, double float, String string, Uint8List binary, DateTime date, DateTime dateTime, String password, String callback }) async + //Future testEndpointParameters(num number, double double_, String patternWithoutDelimiter, String byte, { int integer, int int32, int int64, double float, String string, Uint8List binary, Date date, DateTime dateTime, String password, String callback }) async test('test testEndpointParameters', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/test/format_test_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/test/format_test_test.dart index 78f599fb051b..558c3aa4b659 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/test/format_test_test.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/test/format_test_test.dart @@ -57,7 +57,7 @@ void main() { // TODO }); - // DateTime date + // Date date test('to test the property `date`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/test/nullable_class_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/test/nullable_class_test.dart index a174a90621d4..1a6767dbb2ab 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/test/nullable_class_test.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/test/nullable_class_test.dart @@ -27,7 +27,7 @@ void main() { // TODO }); - // DateTime dateProp + // Date dateProp test('to test the property `dateProp`', () async { // TODO }); diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/pubspec.yaml b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/pubspec.yaml index 6c33286cb5ae..398c6a074709 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/pubspec.yaml @@ -8,11 +8,11 @@ environment: sdk: '>=2.10.0 <3.0.0' dev_dependencies: - built_collection: '5.0.0' - built_value: '8.0.4' - dio: '4.0.0' + built_collection: 5.0.0 + built_value: 8.0.6 + dio: 4.0.0 http_mock_adapter: 0.2.1 - mockito: '5.0.3' + mockito: 5.0.8 openapi: path: ../petstore_client_lib_fake - test: '1.16.8' + test: 1.17.4 diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/api/fake_api_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/api/fake_api_test.dart index 5448f90adce8..9330474d4992 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/api/fake_api_test.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/api/fake_api_test.dart @@ -34,9 +34,9 @@ void main() { 'integer': '45', 'int32': '2147483647', 'int64': '9223372036854775807', - 'date': '2020-08-11T00:00:00.000Z', + 'date': '2020-08-11', 'dateTime': '2020-08-11T12:30:55.123Z', - 'binary': "Instance of 'MultipartFile'", + 'binary': '[0, 1, 2, 3, 4, 5]', }, headers: { 'content-type': 'application/x-www-form-urlencoded', @@ -53,7 +53,7 @@ void main() { integer: 45, int32: 2147483647, int64: 9223372036854775807, - date: DateTime.utc(2020, 8, 11), + date: Date(2020, 8, 11), dateTime: DateTime.utc(2020, 8, 11, 12, 30, 55, 123), binary: Uint8List.fromList([0, 1, 2, 3, 4, 5]), ); diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/api/pet_api_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/api/pet_api_test.dart index 5aae7639fda1..6b52fdce13ed 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/api/pet_api_test.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/api/pet_api_test.dart @@ -1,9 +1,12 @@ import 'package:built_collection/built_collection.dart'; import 'package:dio/dio.dart'; import 'package:http_mock_adapter/http_mock_adapter.dart'; +import 'package:http_parser/http_parser.dart'; import 'package:openapi/openapi.dart'; import 'package:test/test.dart'; +import '../matcher/form_data_matcher.dart'; + void main() { const photo1 = 'https://localhost/photo1.jpg'; const photo2 = 'https://localhost/photo2.jpg'; @@ -221,5 +224,83 @@ void main() { expect(response.data[1].status, PetStatusEnum.available); }); }); + + group('uploadFile', () { + test('uploadFileWithRequiredFile', () async { + final file = MultipartFile.fromBytes( + [1, 2, 3, 4], + filename: 'test.png', + contentType: MediaType.parse('image/png'), + ); + + server.onRoute( + '/fake/5/uploadImageWithRequiredFile', + (request) => request.reply(200, { + 'code': 200, + 'type': 'success', + 'message': 'File uploaded', + }), + request: Request( + method: RequestMethods.post, + headers: { + Headers.contentTypeHeader: + Matchers.pattern('multipart/form-data'), + Headers.contentLengthHeader: Matchers.integer, + }, + data: FormDataMatcher( + expected: FormData.fromMap({ + r'requiredFile': file, + }), + ), + ), + ); + final response = await client.getPetApi().uploadFileWithRequiredFile( + petId: 5, + requiredFile: file, + ); + + expect(response.statusCode, 200); + expect(response.data.message, 'File uploaded'); + }); + + test('uploadFileWithRequiredFile & additionalMetadata', () async { + final file = MultipartFile.fromBytes( + [1, 2, 3, 4], + filename: 'test.png', + contentType: MediaType.parse('image/png'), + ); + + server.onRoute( + '/fake/3/uploadImageWithRequiredFile', + (request) => request.reply(200, { + 'code': 200, + 'type': 'success', + 'message': 'File uploaded', + }), + request: Request( + method: RequestMethods.post, + headers: { + Headers.contentTypeHeader: + Matchers.pattern('multipart/form-data'), + Headers.contentLengthHeader: Matchers.integer, + }, + data: FormDataMatcher( + expected: FormData.fromMap({ + 'additionalMetadata': 'foo', + r'requiredFile': file, + }), + ), + ), + ); + final response = await client.getPetApi().uploadFileWithRequiredFile( + petId: 3, + requiredFile: file, + additionalMetadata: 'foo', + ); + + expect(response.statusCode, 200); + expect(response.data.message, 'File uploaded'); + }); + }); }); } diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/matcher/form_data_matcher.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/matcher/form_data_matcher.dart new file mode 100644 index 000000000000..8e0a7a6c032a --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/matcher/form_data_matcher.dart @@ -0,0 +1,26 @@ +import 'package:dio/dio.dart'; +import 'package:meta/meta.dart'; +import 'package:collection/collection.dart'; +import 'package:http_mock_adapter/src/matchers/matcher.dart'; + +class FormDataMatcher extends Matcher { + final FormData expected; + + const FormDataMatcher({@required this.expected}); + + @override + bool matches(dynamic actual) { + if (actual is! FormData) { + return false; + } + final data = actual as FormData; + return MapEquality().equals( + Map.fromEntries(expected.fields), + Map.fromEntries(data.fields), + ) && + MapEquality().equals( + Map.fromEntries(expected.files), + Map.fromEntries(data.files), + ); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/model/date_serializer_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/model/date_serializer_test.dart new file mode 100644 index 000000000000..9422fe8e47dd --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/model/date_serializer_test.dart @@ -0,0 +1,31 @@ +import 'package:openapi/openapi.dart'; +import 'package:openapi/src/date_serializer.dart'; +import 'package:test/test.dart'; + +void main() { + final date1 = Date(1999, 3, 25); + const serializer = DateSerializer(); + + group(DateSerializer, () { + test('serialize', () { + expect( + serializer.serialize(serializers, date1), + '1999-03-25', + ); + }); + + test('deserialize date', () { + expect( + serializer.deserialize(serializers, '1999-03-25'), + date1, + ); + }); + + test('deserialize ISO', () { + expect( + serializer.deserialize(serializers, '1999-03-25T12:30:55.123Z'), + date1, + ); + }); + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/model/date_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/model/date_test.dart new file mode 100644 index 000000000000..34675bd672e1 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/model/date_test.dart @@ -0,0 +1,25 @@ +import 'package:openapi/openapi.dart'; +import 'package:test/test.dart'; + +void main() { + final date1 = Date(1999, 3, 25); + final date2 = Date(1999, 1, 1); + + group(Date, () { + test('toString', () { + expect(date1.toString(), '1999-03-25'); + }); + + test('compare >', () { + expect(date1.compareTo(date2), 1); + }); + + test('compare <', () { + expect(date2.compareTo(date1), -1); + }); + + test('compare =', () { + expect(date1.compareTo(date1), 0); + }); + }); +} diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/.gitignore b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/.gitignore index 8092a49d5152..6d2ac22c0b41 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/.gitignore +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/.gitignore @@ -30,8 +30,12 @@ pubspec.lock # Don’t commit files and directories created by other development environments. # For example, if your development environment creates any of the following files, # consider putting them in a global ignore file: -*.iml // IntelliJ -*.ipr // IntelliJ -*.iws // IntelliJ -.idea/ // IntelliJ -.DS_Store // Mac + +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ + +# Mac +.DS_Store diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/README.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/README.md index af1b22de4d52..ac04fa9f72b0 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/README.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/README.md @@ -58,26 +58,26 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*PetApi* | [**addPet**](doc/PetApi.md#addpet) | **post** /pet | Add a new pet to the store -*PetApi* | [**deletePet**](doc/PetApi.md#deletepet) | **delete** /pet/{petId} | Deletes a pet -*PetApi* | [**findPetsByStatus**](doc/PetApi.md#findpetsbystatus) | **get** /pet/findByStatus | Finds Pets by status -*PetApi* | [**findPetsByTags**](doc/PetApi.md#findpetsbytags) | **get** /pet/findByTags | Finds Pets by tags -*PetApi* | [**getPetById**](doc/PetApi.md#getpetbyid) | **get** /pet/{petId} | Find pet by ID -*PetApi* | [**updatePet**](doc/PetApi.md#updatepet) | **put** /pet | Update an existing pet -*PetApi* | [**updatePetWithForm**](doc/PetApi.md#updatepetwithform) | **post** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**uploadFile**](doc/PetApi.md#uploadfile) | **post** /pet/{petId}/uploadImage | uploads an image -*StoreApi* | [**deleteOrder**](doc/StoreApi.md#deleteorder) | **delete** /store/order/{orderId} | Delete purchase order by ID -*StoreApi* | [**getInventory**](doc/StoreApi.md#getinventory) | **get** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getOrderById**](doc/StoreApi.md#getorderbyid) | **get** /store/order/{orderId} | Find purchase order by ID -*StoreApi* | [**placeOrder**](doc/StoreApi.md#placeorder) | **post** /store/order | Place an order for a pet -*UserApi* | [**createUser**](doc/UserApi.md#createuser) | **post** /user | Create user -*UserApi* | [**createUsersWithArrayInput**](doc/UserApi.md#createuserswitharrayinput) | **post** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**createUsersWithListInput**](doc/UserApi.md#createuserswithlistinput) | **post** /user/createWithList | Creates list of users with given input array -*UserApi* | [**deleteUser**](doc/UserApi.md#deleteuser) | **delete** /user/{username} | Delete user -*UserApi* | [**getUserByName**](doc/UserApi.md#getuserbyname) | **get** /user/{username} | Get user by user name -*UserApi* | [**loginUser**](doc/UserApi.md#loginuser) | **get** /user/login | Logs user into the system -*UserApi* | [**logoutUser**](doc/UserApi.md#logoutuser) | **get** /user/logout | Logs out current logged in user session -*UserApi* | [**updateUser**](doc/UserApi.md#updateuser) | **put** /user/{username} | Updated user +*PetApi* | [**addPet**](doc/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](doc/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](doc/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](doc/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](doc/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](doc/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](doc/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](doc/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](doc/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](doc/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](doc/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](doc/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](doc/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](doc/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](doc/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](doc/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](doc/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](doc/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](doc/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](doc/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user ## Documentation For Models diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/PetApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/PetApi.md index 3a78296f3834..74c87b72acc6 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/PetApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/PetApi.md @@ -9,14 +9,14 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**addPet**](PetApi.md#addpet) | **post** /pet | Add a new pet to the store -[**deletePet**](PetApi.md#deletepet) | **delete** /pet/{petId} | Deletes a pet -[**findPetsByStatus**](PetApi.md#findpetsbystatus) | **get** /pet/findByStatus | Finds Pets by status -[**findPetsByTags**](PetApi.md#findpetsbytags) | **get** /pet/findByTags | Finds Pets by tags -[**getPetById**](PetApi.md#getpetbyid) | **get** /pet/{petId} | Find pet by ID -[**updatePet**](PetApi.md#updatepet) | **put** /pet | Update an existing pet -[**updatePetWithForm**](PetApi.md#updatepetwithform) | **post** /pet/{petId} | Updates a pet in the store with form data -[**uploadFile**](PetApi.md#uploadfile) | **post** /pet/{petId}/uploadImage | uploads an image +[**addPet**](PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image # **addPet** diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/StoreApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/StoreApi.md index 0b016d70a84e..6075223c7412 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/StoreApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/StoreApi.md @@ -9,10 +9,10 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**deleteOrder**](StoreApi.md#deleteorder) | **delete** /store/order/{orderId} | Delete purchase order by ID -[**getInventory**](StoreApi.md#getinventory) | **get** /store/inventory | Returns pet inventories by status -[**getOrderById**](StoreApi.md#getorderbyid) | **get** /store/order/{orderId} | Find purchase order by ID -[**placeOrder**](StoreApi.md#placeorder) | **post** /store/order | Place an order for a pet +[**deleteOrder**](StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet # **deleteOrder** diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/UserApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/UserApi.md index c939d874a997..b3b11fe67485 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/UserApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/UserApi.md @@ -9,14 +9,14 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**createUser**](UserApi.md#createuser) | **post** /user | Create user -[**createUsersWithArrayInput**](UserApi.md#createuserswitharrayinput) | **post** /user/createWithArray | Creates list of users with given input array -[**createUsersWithListInput**](UserApi.md#createuserswithlistinput) | **post** /user/createWithList | Creates list of users with given input array -[**deleteUser**](UserApi.md#deleteuser) | **delete** /user/{username} | Delete user -[**getUserByName**](UserApi.md#getuserbyname) | **get** /user/{username} | Get user by user name -[**loginUser**](UserApi.md#loginuser) | **get** /user/login | Logs user into the system -[**logoutUser**](UserApi.md#logoutuser) | **get** /user/logout | Logs out current logged in user session -[**updateUser**](UserApi.md#updateuser) | **put** /user/{username} | Updated user +[**createUser**](UserApi.md#createuser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateuser) | **PUT** /user/{username} | Updated user # **createUser** diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/pet_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/pet_api.dart index 9b378a4b3fa1..70fc2b2dbe66 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/pet_api.dart @@ -51,10 +51,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - 'application/xml', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -119,9 +116,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -169,9 +164,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -234,9 +227,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -298,9 +289,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -360,10 +349,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - 'application/xml', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -428,9 +414,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -482,9 +466,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'multipart/form-data', - ].first, + contentType: 'multipart/form-data', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/store_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/store_api.dart index d0184f6eda8a..80b074645c82 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/store_api.dart @@ -43,9 +43,7 @@ class StoreApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -91,9 +89,7 @@ class StoreApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -148,9 +144,7 @@ class StoreApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -205,9 +199,7 @@ class StoreApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/user_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/user_api.dart index 5253ac660280..fef22be0b977 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/user_api.dart @@ -50,9 +50,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -102,9 +100,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -154,9 +150,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -206,9 +200,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -248,9 +240,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -310,9 +300,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -369,9 +357,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -419,9 +405,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/pubspec.yaml b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/pubspec.yaml index 0db393df2b7c..34a1aa76180f 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/pubspec.yaml @@ -1,13 +1,17 @@ name: openapi version: 1.0.0 description: OpenAPI API client +homepage: homepage + environment: - sdk: '>=2.7.0 <3.0.0' + sdk: '>=2.7.0 <3.0.0' + dependencies: - dio: '^3.0.9' - built_value: '>=7.1.0 <8.0.0' - built_collection: '>=4.3.2 <5.0.0' + dio: '^3.0.9' + built_value: '>=7.1.0 <8.0.0' + built_collection: '>=4.3.2 <5.0.0' + dev_dependencies: - built_value_generator: '>=7.1.0 <8.0.0' - build_runner: any - test: '>=1.3.0 <1.16.0' + built_value_generator: '>=7.1.0 <8.0.0' + build_runner: any + test: '>=1.3.0 <1.16.0' diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/.gitignore b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/.gitignore index 8092a49d5152..6d2ac22c0b41 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/.gitignore +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/.gitignore @@ -30,8 +30,12 @@ pubspec.lock # Don’t commit files and directories created by other development environments. # For example, if your development environment creates any of the following files, # consider putting them in a global ignore file: -*.iml // IntelliJ -*.ipr // IntelliJ -*.iws // IntelliJ -.idea/ // IntelliJ -.DS_Store // Mac + +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ + +# Mac +.DS_Store diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/README.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/README.md index af00b20ee1d5..b1d9fbe962c8 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/README.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/README.md @@ -58,46 +58,47 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*AnotherFakeApi* | [**call123testSpecialTags**](doc/AnotherFakeApi.md#call123testspecialtags) | **patch** /another-fake/dummy | To test special tags -*DefaultApi* | [**fooGet**](doc/DefaultApi.md#fooget) | **get** /foo | -*FakeApi* | [**fakeHealthGet**](doc/FakeApi.md#fakehealthget) | **get** /fake/health | Health check endpoint -*FakeApi* | [**fakeHttpSignatureTest**](doc/FakeApi.md#fakehttpsignaturetest) | **get** /fake/http-signature-test | test http signature authentication -*FakeApi* | [**fakeOuterBooleanSerialize**](doc/FakeApi.md#fakeouterbooleanserialize) | **post** /fake/outer/boolean | -*FakeApi* | [**fakeOuterCompositeSerialize**](doc/FakeApi.md#fakeoutercompositeserialize) | **post** /fake/outer/composite | -*FakeApi* | [**fakeOuterNumberSerialize**](doc/FakeApi.md#fakeouternumberserialize) | **post** /fake/outer/number | -*FakeApi* | [**fakeOuterStringSerialize**](doc/FakeApi.md#fakeouterstringserialize) | **post** /fake/outer/string | -*FakeApi* | [**fakePropertyEnumIntegerSerialize**](doc/FakeApi.md#fakepropertyenumintegerserialize) | **post** /fake/property/enum-int | -*FakeApi* | [**testBodyWithFileSchema**](doc/FakeApi.md#testbodywithfileschema) | **put** /fake/body-with-file-schema | -*FakeApi* | [**testBodyWithQueryParams**](doc/FakeApi.md#testbodywithqueryparams) | **put** /fake/body-with-query-params | -*FakeApi* | [**testClientModel**](doc/FakeApi.md#testclientmodel) | **patch** /fake | To test \"client\" model -*FakeApi* | [**testEndpointParameters**](doc/FakeApi.md#testendpointparameters) | **post** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*FakeApi* | [**testEnumParameters**](doc/FakeApi.md#testenumparameters) | **get** /fake | To test enum parameters -*FakeApi* | [**testGroupParameters**](doc/FakeApi.md#testgroupparameters) | **delete** /fake | Fake endpoint to test group parameters (optional) -*FakeApi* | [**testInlineAdditionalProperties**](doc/FakeApi.md#testinlineadditionalproperties) | **post** /fake/inline-additionalProperties | test inline additionalProperties -*FakeApi* | [**testJsonFormData**](doc/FakeApi.md#testjsonformdata) | **get** /fake/jsonFormData | test json serialization of form data -*FakeApi* | [**testQueryParameterCollectionFormat**](doc/FakeApi.md#testqueryparametercollectionformat) | **put** /fake/test-query-paramters | -*FakeClassnameTags123Api* | [**testClassname**](doc/FakeClassnameTags123Api.md#testclassname) | **patch** /fake_classname_test | To test class name in snake case -*PetApi* | [**addPet**](doc/PetApi.md#addpet) | **post** /pet | Add a new pet to the store -*PetApi* | [**deletePet**](doc/PetApi.md#deletepet) | **delete** /pet/{petId} | Deletes a pet -*PetApi* | [**findPetsByStatus**](doc/PetApi.md#findpetsbystatus) | **get** /pet/findByStatus | Finds Pets by status -*PetApi* | [**findPetsByTags**](doc/PetApi.md#findpetsbytags) | **get** /pet/findByTags | Finds Pets by tags -*PetApi* | [**getPetById**](doc/PetApi.md#getpetbyid) | **get** /pet/{petId} | Find pet by ID -*PetApi* | [**updatePet**](doc/PetApi.md#updatepet) | **put** /pet | Update an existing pet -*PetApi* | [**updatePetWithForm**](doc/PetApi.md#updatepetwithform) | **post** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**uploadFile**](doc/PetApi.md#uploadfile) | **post** /pet/{petId}/uploadImage | uploads an image -*PetApi* | [**uploadFileWithRequiredFile**](doc/PetApi.md#uploadfilewithrequiredfile) | **post** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) -*StoreApi* | [**deleteOrder**](doc/StoreApi.md#deleteorder) | **delete** /store/order/{order_id} | Delete purchase order by ID -*StoreApi* | [**getInventory**](doc/StoreApi.md#getinventory) | **get** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getOrderById**](doc/StoreApi.md#getorderbyid) | **get** /store/order/{order_id} | Find purchase order by ID -*StoreApi* | [**placeOrder**](doc/StoreApi.md#placeorder) | **post** /store/order | Place an order for a pet -*UserApi* | [**createUser**](doc/UserApi.md#createuser) | **post** /user | Create user -*UserApi* | [**createUsersWithArrayInput**](doc/UserApi.md#createuserswitharrayinput) | **post** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**createUsersWithListInput**](doc/UserApi.md#createuserswithlistinput) | **post** /user/createWithList | Creates list of users with given input array -*UserApi* | [**deleteUser**](doc/UserApi.md#deleteuser) | **delete** /user/{username} | Delete user -*UserApi* | [**getUserByName**](doc/UserApi.md#getuserbyname) | **get** /user/{username} | Get user by user name -*UserApi* | [**loginUser**](doc/UserApi.md#loginuser) | **get** /user/login | Logs user into the system -*UserApi* | [**logoutUser**](doc/UserApi.md#logoutuser) | **get** /user/logout | Logs out current logged in user session -*UserApi* | [**updateUser**](doc/UserApi.md#updateuser) | **put** /user/{username} | Updated user +*AnotherFakeApi* | [**call123testSpecialTags**](doc/AnotherFakeApi.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags +*DefaultApi* | [**fooGet**](doc/DefaultApi.md#fooget) | **GET** /foo | +*FakeApi* | [**fakeHealthGet**](doc/FakeApi.md#fakehealthget) | **GET** /fake/health | Health check endpoint +*FakeApi* | [**fakeHttpSignatureTest**](doc/FakeApi.md#fakehttpsignaturetest) | **GET** /fake/http-signature-test | test http signature authentication +*FakeApi* | [**fakeOuterBooleanSerialize**](doc/FakeApi.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +*FakeApi* | [**fakeOuterCompositeSerialize**](doc/FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +*FakeApi* | [**fakeOuterNumberSerialize**](doc/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | +*FakeApi* | [**fakeOuterStringSerialize**](doc/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | +*FakeApi* | [**fakePropertyEnumIntegerSerialize**](doc/FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**testBodyWithBinary**](doc/FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | +*FakeApi* | [**testBodyWithFileSchema**](doc/FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | +*FakeApi* | [**testBodyWithQueryParams**](doc/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | +*FakeApi* | [**testClientModel**](doc/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +*FakeApi* | [**testEndpointParameters**](doc/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**testEnumParameters**](doc/FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**testGroupParameters**](doc/FakeApi.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +*FakeApi* | [**testInlineAdditionalProperties**](doc/FakeApi.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeApi* | [**testJsonFormData**](doc/FakeApi.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeApi* | [**testQueryParameterCollectionFormat**](doc/FakeApi.md#testqueryparametercollectionformat) | **PUT** /fake/test-query-paramters | +*FakeClassnameTags123Api* | [**testClassname**](doc/FakeClassnameTags123Api.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case +*PetApi* | [**addPet**](doc/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](doc/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](doc/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](doc/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](doc/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](doc/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](doc/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](doc/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*PetApi* | [**uploadFileWithRequiredFile**](doc/PetApi.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +*StoreApi* | [**deleteOrder**](doc/StoreApi.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +*StoreApi* | [**getInventory**](doc/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](doc/StoreApi.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +*StoreApi* | [**placeOrder**](doc/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](doc/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](doc/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](doc/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](doc/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](doc/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](doc/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](doc/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](doc/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user ## Documentation For Models diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/AnotherFakeApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/AnotherFakeApi.md index d55663297c13..bb401f7c20cb 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/AnotherFakeApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/AnotherFakeApi.md @@ -9,7 +9,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**call123testSpecialTags**](AnotherFakeApi.md#call123testspecialtags) | **patch** /another-fake/dummy | To test special tags +[**call123testSpecialTags**](AnotherFakeApi.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags # **call123testSpecialTags** diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/DefaultApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/DefaultApi.md index be916c3037d5..5c305ecaa71f 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/DefaultApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/DefaultApi.md @@ -9,7 +9,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**fooGet**](DefaultApi.md#fooget) | **get** /foo | +[**fooGet**](DefaultApi.md#fooget) | **GET** /foo | # **fooGet** diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/FakeApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/FakeApi.md index 41ab4e4fc126..da4601dbec5f 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/FakeApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/FakeApi.md @@ -9,22 +9,23 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**fakeHealthGet**](FakeApi.md#fakehealthget) | **get** /fake/health | Health check endpoint -[**fakeHttpSignatureTest**](FakeApi.md#fakehttpsignaturetest) | **get** /fake/http-signature-test | test http signature authentication -[**fakeOuterBooleanSerialize**](FakeApi.md#fakeouterbooleanserialize) | **post** /fake/outer/boolean | -[**fakeOuterCompositeSerialize**](FakeApi.md#fakeoutercompositeserialize) | **post** /fake/outer/composite | -[**fakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **post** /fake/outer/number | -[**fakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **post** /fake/outer/string | -[**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakepropertyenumintegerserialize) | **post** /fake/property/enum-int | -[**testBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **put** /fake/body-with-file-schema | -[**testBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **put** /fake/body-with-query-params | -[**testClientModel**](FakeApi.md#testclientmodel) | **patch** /fake | To test \"client\" model -[**testEndpointParameters**](FakeApi.md#testendpointparameters) | **post** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumParameters**](FakeApi.md#testenumparameters) | **get** /fake | To test enum parameters -[**testGroupParameters**](FakeApi.md#testgroupparameters) | **delete** /fake | Fake endpoint to test group parameters (optional) -[**testInlineAdditionalProperties**](FakeApi.md#testinlineadditionalproperties) | **post** /fake/inline-additionalProperties | test inline additionalProperties -[**testJsonFormData**](FakeApi.md#testjsonformdata) | **get** /fake/jsonFormData | test json serialization of form data -[**testQueryParameterCollectionFormat**](FakeApi.md#testqueryparametercollectionformat) | **put** /fake/test-query-paramters | +[**fakeHealthGet**](FakeApi.md#fakehealthget) | **GET** /fake/health | Health check endpoint +[**fakeHttpSignatureTest**](FakeApi.md#fakehttpsignaturetest) | **GET** /fake/http-signature-test | test http signature authentication +[**fakeOuterBooleanSerialize**](FakeApi.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +[**fakeOuterCompositeSerialize**](FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +[**fakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | +[**fakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | +[**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +[**testBodyWithBinary**](FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | +[**testBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | +[**testBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | +[**testClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +[**testEndpointParameters**](FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumParameters**](FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters +[**testGroupParameters**](FakeApi.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[**testInlineAdditionalProperties**](FakeApi.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**testJsonFormData**](FakeApi.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +[**testQueryParameterCollectionFormat**](FakeApi.md#testqueryparametercollectionformat) | **PUT** /fake/test-query-paramters | # **fakeHealthGet** @@ -326,12 +327,54 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **testBodyWithBinary** +> testBodyWithBinary(body) + + + +For this test, the body has to be a binary file. + +### Example +```dart +import 'package:openapi/api.dart'; + +var api_instance = new FakeApi(); +var body = new Uint8List(); // Uint8List | image to upload + +try { + api_instance.testBodyWithBinary(body); +} catch (e) { + print('Exception when calling FakeApi->testBodyWithBinary: $e\n'); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **Uint8List**| image to upload | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: image/png + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **testBodyWithFileSchema** > testBodyWithFileSchema(fileSchemaTestClass) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example ```dart diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/FakeClassnameTags123Api.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/FakeClassnameTags123Api.md index 9745ca8e3ffe..98fe0b47358b 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/FakeClassnameTags123Api.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/FakeClassnameTags123Api.md @@ -9,7 +9,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testClassname**](FakeClassnameTags123Api.md#testclassname) | **patch** /fake_classname_test | To test class name in snake case +[**testClassname**](FakeClassnameTags123Api.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case # **testClassname** diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/PetApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/PetApi.md index d5a07d5046e2..841eed632916 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/PetApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/PetApi.md @@ -9,15 +9,15 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**addPet**](PetApi.md#addpet) | **post** /pet | Add a new pet to the store -[**deletePet**](PetApi.md#deletepet) | **delete** /pet/{petId} | Deletes a pet -[**findPetsByStatus**](PetApi.md#findpetsbystatus) | **get** /pet/findByStatus | Finds Pets by status -[**findPetsByTags**](PetApi.md#findpetsbytags) | **get** /pet/findByTags | Finds Pets by tags -[**getPetById**](PetApi.md#getpetbyid) | **get** /pet/{petId} | Find pet by ID -[**updatePet**](PetApi.md#updatepet) | **put** /pet | Update an existing pet -[**updatePetWithForm**](PetApi.md#updatepetwithform) | **post** /pet/{petId} | Updates a pet in the store with form data -[**uploadFile**](PetApi.md#uploadfile) | **post** /pet/{petId}/uploadImage | uploads an image -[**uploadFileWithRequiredFile**](PetApi.md#uploadfilewithrequiredfile) | **post** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +[**addPet**](PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +[**uploadFileWithRequiredFile**](PetApi.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) # **addPet** diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/StoreApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/StoreApi.md index 1fcb8f71eea9..a7dbf9ad0197 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/StoreApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/StoreApi.md @@ -9,10 +9,10 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**deleteOrder**](StoreApi.md#deleteorder) | **delete** /store/order/{order_id} | Delete purchase order by ID -[**getInventory**](StoreApi.md#getinventory) | **get** /store/inventory | Returns pet inventories by status -[**getOrderById**](StoreApi.md#getorderbyid) | **get** /store/order/{order_id} | Find purchase order by ID -[**placeOrder**](StoreApi.md#placeorder) | **post** /store/order | Place an order for a pet +[**deleteOrder**](StoreApi.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet # **deleteOrder** diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/UserApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/UserApi.md index 62e01652e800..32bc2e675da9 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/UserApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/UserApi.md @@ -9,14 +9,14 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**createUser**](UserApi.md#createuser) | **post** /user | Create user -[**createUsersWithArrayInput**](UserApi.md#createuserswitharrayinput) | **post** /user/createWithArray | Creates list of users with given input array -[**createUsersWithListInput**](UserApi.md#createuserswithlistinput) | **post** /user/createWithList | Creates list of users with given input array -[**deleteUser**](UserApi.md#deleteuser) | **delete** /user/{username} | Delete user -[**getUserByName**](UserApi.md#getuserbyname) | **get** /user/{username} | Get user by user name -[**loginUser**](UserApi.md#loginuser) | **get** /user/login | Logs user into the system -[**logoutUser**](UserApi.md#logoutuser) | **get** /user/logout | Logs out current logged in user session -[**updateUser**](UserApi.md#updateuser) | **put** /user/{username} | Updated user +[**createUser**](UserApi.md#createuser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateuser) | **PUT** /user/{username} | Updated user # **createUser** diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/another_fake_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/another_fake_api.dart index 4bea8f87dbdf..cabc80b7798b 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/another_fake_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/another_fake_api.dart @@ -42,9 +42,7 @@ class AnotherFakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/default_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/default_api.dart index ab47f0a65716..51dd7ea125ee 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/default_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/default_api.dart @@ -41,9 +41,7 @@ class DefaultApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_api.dart index b50d02d5cf60..9dadc9c19880 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_api.dart @@ -50,9 +50,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -118,10 +116,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - 'application/xml', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -164,9 +159,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -219,9 +212,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -279,9 +270,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -334,9 +323,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -389,9 +376,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -428,7 +413,49 @@ class FakeApi { /// /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body has to be a binary file. + Future> testBodyWithBinary( + Uint8List body, { + CancelToken cancelToken, + Map headers, + Map extra, + ValidateStatus validateStatus, + ProgressCallback onSendProgress, + ProgressCallback onReceiveProgress, + }) async { + final _request = RequestOptions( + path: r'/fake/body-with-binary', + method: 'PUT', + headers: { + ...?headers, + }, + extra: { + 'secure': >[], + ...?extra, + }, + validateStatus: validateStatus, + contentType: 'image/png', + cancelToken: cancelToken, + onSendProgress: onSendProgress, + onReceiveProgress: onReceiveProgress, + ); + + dynamic _bodyData; + + _bodyData = body; + + final _response = await _dio.request( + _request.path, + data: _bodyData, + options: _request, + ); + + return _response; + } + + /// + /// + /// For this test, the body for this request must reference a schema named `File`. Future> testBodyWithFileSchema( FileSchemaTestClass fileSchemaTestClass, { CancelToken cancelToken, @@ -449,9 +476,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -498,9 +523,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -543,9 +566,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -621,9 +642,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -695,9 +714,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -760,9 +777,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -802,9 +817,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -848,9 +861,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -906,9 +917,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart index f9b44deb6d52..54c40f0e3437 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart @@ -49,9 +49,7 @@ class FakeClassnameTags123Api { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/pet_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/pet_api.dart index 56bdd8556bc4..9cc7beeb57ed 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/pet_api.dart @@ -51,10 +51,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - 'application/xml', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -104,9 +101,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -154,9 +149,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -219,9 +212,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -283,9 +274,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -345,10 +334,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - 'application/xml', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -398,9 +384,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -452,9 +436,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'multipart/form-data', - ].first, + contentType: 'multipart/form-data', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -521,9 +503,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'multipart/form-data', - ].first, + contentType: 'multipart/form-data', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/store_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/store_api.dart index e6c7679d1cdf..14fa8b601219 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/store_api.dart @@ -43,9 +43,7 @@ class StoreApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -91,9 +89,7 @@ class StoreApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -148,9 +144,7 @@ class StoreApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -205,9 +199,7 @@ class StoreApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/user_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/user_api.dart index d85fbcc85855..86032dba94ae 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/user_api.dart @@ -43,9 +43,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -88,9 +86,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -133,9 +129,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -178,9 +172,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -220,9 +212,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -282,9 +272,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -334,9 +322,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -377,9 +363,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pubspec.yaml b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pubspec.yaml index 0db393df2b7c..34a1aa76180f 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pubspec.yaml @@ -1,13 +1,17 @@ name: openapi version: 1.0.0 description: OpenAPI API client +homepage: homepage + environment: - sdk: '>=2.7.0 <3.0.0' + sdk: '>=2.7.0 <3.0.0' + dependencies: - dio: '^3.0.9' - built_value: '>=7.1.0 <8.0.0' - built_collection: '>=4.3.2 <5.0.0' + dio: '^3.0.9' + built_value: '>=7.1.0 <8.0.0' + built_collection: '>=4.3.2 <5.0.0' + dev_dependencies: - built_value_generator: '>=7.1.0 <8.0.0' - build_runner: any - test: '>=1.3.0 <1.16.0' + built_value_generator: '>=7.1.0 <8.0.0' + build_runner: any + test: '>=1.3.0 <1.16.0' diff --git a/samples/openapi3/client/petstore/dart2/petstore/.analysis_options b/samples/openapi3/client/petstore/dart2/petstore/.analysis_options deleted file mode 100644 index a10d4c5a05c9..000000000000 --- a/samples/openapi3/client/petstore/dart2/petstore/.analysis_options +++ /dev/null @@ -1,2 +0,0 @@ -analyzer: - strong-mode: true diff --git a/samples/openapi3/client/petstore/dart2/petstore/pubspec.yaml b/samples/openapi3/client/petstore/dart2/petstore/pubspec.yaml index f26301750933..92262618ab48 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart2/petstore/pubspec.yaml @@ -1,13 +1,18 @@ name: petstore_client version: 1.0.0 description: Petstore client using OpenAPI library + +publish_to: none + environment: - sdk: '>=2.5.0 <3.0.0' + sdk: '>=2.11.0 <3.0.0' + dependencies: openapi: path: ../petstore_client_lib + dev_dependencies: test: ^1.8.0 mockito: ^4.1.1 - http: ^0.12.0 + http: ^0.13.0 collection: ^1.14.12 diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/fake_client.dart b/samples/openapi3/client/petstore/dart2/petstore/test/fake_client.dart index 95c735deb38c..ed60f386aa41 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/fake_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/fake_client.dart @@ -21,9 +21,9 @@ class FakeClient extends Fake implements Client { this.expectedPutRequestBody, this.putResponseBody, this.sendResponseBody, - this.expectedUrl, + String expectedUrl, this.expectedHeaders = null, - }); + }) : this.expectedUrl = Uri.parse(expectedUrl); Exception throwException; Object expectedPostRequestBody; @@ -34,12 +34,12 @@ class FakeClient extends Fake implements Client { String expectedPutRequestBody; String putResponseBody; String sendResponseBody; - String expectedUrl; + Uri expectedUrl; Map expectedHeaders; @override - Future post(url, - {Map headers, body, Encoding encoding}) async { + Future post(Uri url, + {Map headers, Object body, Encoding encoding}) async { // check that the request was made with expected values if (url != expectedUrl) { throw StateError( @@ -67,7 +67,7 @@ class FakeClient extends Fake implements Client { } @override - Future get(url, {Map headers}) async { + Future get(Uri url, {Map headers}) async { // check that the request was made with expected values if (url != expectedUrl) { throw StateError( @@ -85,7 +85,8 @@ class FakeClient extends Fake implements Client { } @override - Future delete(url, {Map headers}) async { + Future delete(Uri url, + {Map headers, Object body, Encoding encoding}) async { // check that the request was made with expected values if (url != expectedUrl) { throw StateError( @@ -103,8 +104,8 @@ class FakeClient extends Fake implements Client { } @override - Future put(url, - {Map headers, body, Encoding encoding}) async { + Future put(Uri url, + {Map headers, Object body, Encoding encoding}) async { // check that the request was made with expected values if (url != expectedUrl) { throw StateError( diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/order_model_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/order_model_test.dart index 9cdc65fe52dc..7048659e8942 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/order_model_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/order_model_test.dart @@ -2,8 +2,8 @@ import 'package:openapi/api.dart'; import 'package:test/test.dart'; void main() { - test('Check if default value is generated', () async { - var order = Order(); - expect(order.complete, equals(false)); - }); + test('Check if default value is generated', () async { + var order = Order(); + expect(order.complete, equals(false)); + }); } diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/pet_faked_client_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/pet_faked_client_test.dart index 277c49b3971a..9737df5d4881 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/pet_faked_client_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/pet_faked_client_test.dart @@ -26,11 +26,10 @@ void main() { ..id = 124321 ..name = 'Jose' ]; - return Pet() + return Pet(name: name) ..id = id ..category = category ..tags = tags - ..name = name ..status = PetStatusEnum.fromJson(status) ..photoUrls = ['https://petstore.com/sample/photo1.jpg']; } @@ -53,8 +52,7 @@ void main() { // use the pet api to add a pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: - await petApi.apiClient.serializeAsync(newPet), + expectedPostRequestBody: await petApi.apiClient.serializeAsync(newPet), postResponseBody: await petApi.apiClient.serializeAsync(newPet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); @@ -76,8 +74,7 @@ void main() { expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', throwException: ApiException(400, 'not found'), ); - expect( - petApi.getPetById(id), throwsA(equals(TypeMatcher()))); + expect(petApi.getPetById(id), throwsA(equals(TypeMatcher()))); }); test('deletes existing pet by id', () async { @@ -87,8 +84,7 @@ void main() { // add a new pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: - await petApi.apiClient.serializeAsync(newPet), + expectedPostRequestBody: await petApi.apiClient.serializeAsync(newPet), postResponseBody: await petApi.apiClient.serializeAsync(newPet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); @@ -106,8 +102,7 @@ void main() { expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', throwException: ApiException(400, 'Not found'), ); - expect( - petApi.getPetById(id), throwsA(equals(TypeMatcher()))); + expect(petApi.getPetById(id), throwsA(equals(TypeMatcher()))); }); test('updates pet with form', () async { @@ -117,16 +112,11 @@ void main() { // add a new pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: - await petApi.apiClient.serializeAsync(newPet), + expectedPostRequestBody: await petApi.apiClient.serializeAsync(newPet), postResponseBody: await petApi.apiClient.serializeAsync(newPet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); - final multipartRequest = MultipartRequest(null, null); - multipartRequest.fields['name'] = 'Doge'; - multipartRequest.fields['status'] = ''; - // update with form petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', @@ -157,8 +147,7 @@ void main() { // add a new pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: - await petApi.apiClient.serializeAsync(newPet), + expectedPostRequestBody: await petApi.apiClient.serializeAsync(newPet), postResponseBody: await petApi.apiClient.serializeAsync(newPet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); @@ -166,8 +155,7 @@ void main() { // update the same pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPutRequestBody: - await petApi.apiClient.serializeAsync(updatePet), + expectedPutRequestBody: await petApi.apiClient.serializeAsync(updatePet), putResponseBody: await petApi.apiClient.serializeAsync(updatePet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.updatePet(updatePet); @@ -196,15 +184,13 @@ void main() { // retrieve pets by status petApi.apiClient.client = FakeClient( - expectedUrl: - 'http://petstore.swagger.io/v2/pet/findByStatus?status=$status', + expectedUrl: 'http://petstore.swagger.io/v2/pet/findByStatus?status=$status', getResponseBody: await petApi.apiClient.serializeAsync([pet1, pet2]), ); final pets = await petApi.findPetsByStatus([status]); // tests serialisation and deserialisation of enum - final petsByStatus = - pets.where((p) => p.status == PetStatusEnum.available); + final petsByStatus = pets.where((p) => p.status == PetStatusEnum.available); expect(petsByStatus.length, equals(2)); final petIds = pets.map((pet) => pet.id).toList(); expect(petIds, contains(id1)); @@ -216,14 +202,12 @@ void main() { final id = newId(); final newPet = makePet(id: id); // get some test data (recorded from live response) - final uploadResponse = - await File('test/file_upload_response.json').readAsString(); + final uploadResponse = await File('test/file_upload_response.json').readAsString(); // add a new pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: - await petApi.apiClient.serializeAsync(newPet), + expectedPostRequestBody: await petApi.apiClient.serializeAsync(newPet), postResponseBody: await petApi.apiClient.serializeAsync(newPet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); @@ -232,9 +216,8 @@ void main() { expectedUrl: 'http://petstore.swagger.io/v2/pet', sendResponseBody: uploadResponse, ); - final file = - new MultipartFile.fromBytes('file', [104, 101, 108, 108, 111]); - await petApi.uploadFile(id, additionalMetadata: '', file: file); + final file = new MultipartFile.fromBytes('file', [104, 101, 108, 108, 111]); + await petApi.uploadFile(id, file: file); }); }); } diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/pet_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/pet_test.dart index 72126ba6a904..cbd26c68c7ee 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/pet_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/pet_test.dart @@ -1,5 +1,4 @@ -import 'dart:async'; - +@Skip('Needs real petstore') import 'package:http/http.dart'; import 'package:openapi/api.dart'; import 'package:test/test.dart'; @@ -46,16 +45,14 @@ void main() { }); test('doesn\'t get non-existing pet by id', () { - expect(petApi.getPetById(newId()), - throwsA(equals(TypeMatcher()))); + expect(petApi.getPetById(newId()), throwsA(equals(TypeMatcher()))); }); test('deletes existing pet by id', () async { var id = newId(); await petApi.addPet(makePet(id: id)); await petApi.deletePet(id, apiKey: 'special-key'); - expect( - petApi.getPetById(id), throwsA(equals(TypeMatcher()))); + expect(petApi.getPetById(id), throwsA(equals(TypeMatcher()))); }); test('updates pet with form', () async { @@ -100,5 +97,5 @@ void main() { var file = new MultipartFile.fromBytes('file', [104, 101, 108, 108, 111]); await petApi.uploadFile(id, additionalMetadata: '', file: file); }); - }, skip: 'e2e tests for CI'); + }); } diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/random_id.dart b/samples/openapi3/client/petstore/dart2/petstore/test/random_id.dart index 0457428c7dd4..ca67ac209934 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/random_id.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/random_id.dart @@ -4,4 +4,4 @@ final _random = new Random(); int newId() { return _random.nextInt(999999); -} \ No newline at end of file +} diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/store_faked_client_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/store_faked_client_test.dart index 9f75fd55d863..541d08b8c6a7 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/store_faked_client_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/store_faked_client_test.dart @@ -21,62 +21,56 @@ void main() { group('Store API with faked client', () { test('places an order and gets it by id', () async { - // TODO: Please uncomment this after a content type of the petstore order in petstore.yaml is fixed. - // final id = newId(); - // final newOrder = makeOrder(id: id); + final id = newId(); + final newOrder = makeOrder(id: id); - // // use the store api to add an order - // storeApi.apiClient.client = FakeClient( - // expectedUrl: 'http://petstore.swagger.io/v2/store/order', - // expectedPostRequestBody: await storeApi.apiClient.serializeAsync(newOrder), - // postResponseBody: await storeApi.apiClient.serializeAsync(newOrder), - // expectedHeaders: {"Content-Type": "application/json"} - // ); - // await storeApi.placeOrder(newOrder); + // use the store api to add an order + storeApi.apiClient.client = FakeClient( + expectedUrl: 'http://petstore.swagger.io/v2/store/order', + expectedPostRequestBody: await storeApi.apiClient.serializeAsync(newOrder), + postResponseBody: await storeApi.apiClient.serializeAsync(newOrder), + expectedHeaders: {"Content-Type": "application/json"}); + await storeApi.placeOrder(newOrder); - // // retrieve the same order by id - // storeApi.apiClient.client = FakeClient( - // expectedUrl: 'http://petstore.swagger.io/v2/store/order/$id', - // getResponseBody: await storeApi.apiClient.serializeAsync(newOrder), - // ); - // final placedOrder = await storeApi.getOrderById(id); - // expect(placedOrder.id, equals(id)); + // retrieve the same order by id + storeApi.apiClient.client = FakeClient( + expectedUrl: 'http://petstore.swagger.io/v2/store/order/$id', + getResponseBody: await storeApi.apiClient.serializeAsync(newOrder), + ); + final placedOrder = await storeApi.getOrderById(id); + expect(placedOrder.id, equals(id)); }); test('deletes an order', () async { - // TODO: Please uncomment this after a content type of the petstore order in petstore.yaml is fixed. - // final id = newId(); - // final newOrder = makeOrder(id: id); + final id = newId(); + final newOrder = makeOrder(id: id); - // // use the store api to add an order - // storeApi.apiClient.client = FakeClient( - // expectedUrl: 'http://petstore.swagger.io/v2/store/order', - // expectedPostRequestBody: await storeApi.apiClient.serializeAsync(newOrder), - // postResponseBody: await storeApi.apiClient.serializeAsync(newOrder), - // expectedHeaders: {"Content-Type": "application/json"} - // ); - // await storeApi.placeOrder(newOrder); + // use the store api to add an order + storeApi.apiClient.client = FakeClient( + expectedUrl: 'http://petstore.swagger.io/v2/store/order', + expectedPostRequestBody: await storeApi.apiClient.serializeAsync(newOrder), + postResponseBody: await storeApi.apiClient.serializeAsync(newOrder), + expectedHeaders: {"Content-Type": "application/json"}); + await storeApi.placeOrder(newOrder); - // // delete the same order - // storeApi.apiClient.client = FakeClient( - // expectedUrl: 'http://petstore.swagger.io/v2/store/order/$id', - // deleteResponseBody: '', - // ); - // await storeApi.deleteOrder(id.toString()); + // delete the same order + storeApi.apiClient.client = FakeClient( + expectedUrl: 'http://petstore.swagger.io/v2/store/order/$id', + deleteResponseBody: '', + ); + await storeApi.deleteOrder(id.toString()); - // // try and retrieve the order - // storeApi.apiClient.client = FakeClient( - // expectedUrl: 'http://petstore.swagger.io/v2/store/order/$id', - // throwException: ApiException(400, 'Not found'), - // ); - // expect(storeApi.getOrderById(id), - // throwsA(equals(TypeMatcher()))); + // try and retrieve the order + storeApi.apiClient.client = FakeClient( + expectedUrl: 'http://petstore.swagger.io/v2/store/order/$id', + throwException: ApiException(400, 'Not found'), + ); + expect(storeApi.getOrderById(id), throwsA(equals(TypeMatcher()))); }); test('gets the store inventory', () async { // get some test data (recorded from live response) - final inventoryResponse = - await File('test/inventory_response.json').readAsString(); + final inventoryResponse = await File('test/inventory_response.json').readAsString(); // use the store api to get the inventory storeApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/store/inventory', diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/store_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/store_test.dart index b2175238819c..a5b19cd1de59 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/store_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/store_test.dart @@ -1,3 +1,4 @@ +@Skip('Needs real petstore') import 'package:openapi/api.dart'; import 'package:test/test.dart'; @@ -18,27 +19,24 @@ void main() { group('Store API with live client', () { test('places an order and gets it by id', () async { - // TODO: Please uncomment this after a content type of the petstore order in petstore.yaml is fixed. - // var id = newId(); + var id = newId(); - // await storeApi.placeOrder(makeOrder(id: id)); - // var order = await storeApi.getOrderById(id); - // expect(order.id, equals(id)); + await storeApi.placeOrder(makeOrder(id: id)); + var order = await storeApi.getOrderById(id); + expect(order.id, equals(id)); }); test('deletes an order', () async { - // TODO: Please uncomment this after a content type of the petstore order in petstore.yaml is fixed. - // var id = newId(); + var id = newId(); - // await storeApi.placeOrder(makeOrder(id: id)); - // await storeApi.deleteOrder(id.toString()); - // expect(storeApi.getOrderById(id), - // throwsA(equals(TypeMatcher()))); + await storeApi.placeOrder(makeOrder(id: id)); + await storeApi.deleteOrder(id.toString()); + expect(storeApi.getOrderById(id), throwsA(equals(TypeMatcher()))); }); test('gets the store inventory', () async { Map inventory = await storeApi.getInventory(); expect(inventory.length, isNot(equals(0))); }); - }); // , skip: 'e2e tests for CI' + }); } diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/user_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/user_test.dart index ea34b3713fa7..d604363622d6 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/user_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/user_test.dart @@ -1,3 +1,4 @@ +@Skip('Needs real petstore') import 'package:openapi/api.dart'; import 'package:test/test.dart'; @@ -6,8 +7,7 @@ import 'random_id.dart'; void main() { var userApi = new UserApi(); - User makeUser( - {int id, String userName = 'username', String password = 'password'}) { + User makeUser({int id, String userName = 'username', String password = 'password'}) { return User() ..id = id ..username = userName @@ -63,8 +63,7 @@ void main() { var username = 'Riddlem325'; await userApi.createUser(makeUser(id: newId(), userName: username)); await userApi.deleteUser(username); - expect(userApi.getUserByName(username), - throwsA(TypeMatcher())); + expect(userApi.getUserByName(username), throwsA(TypeMatcher())); }); test('logs a user in', () async { @@ -76,5 +75,5 @@ void main() { var result = await userApi.loginUser(username, password); expect(result, contains('logged in user session:')); }); - }, skip: 'e2e tests for CI'); + }); } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart2/petstore_client_lib/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart index 2ec34d475e27..ee5c6f0d24cb 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart @@ -41,17 +41,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -118,17 +107,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -187,17 +165,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -265,17 +232,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -342,17 +298,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -414,17 +359,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -491,30 +425,11 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (name != null) { - hasFields = true; - mp.fields[r'name'] = parameterToString(name); - } - if (status != null) { - hasFields = true; - mp.fields[r'status'] = parameterToString(status); - } - if (hasFields) { - postBody = mp; - } - } else { - if (name != null) { - formParams[r'name'] = parameterToString(name); - } - if (status != null) { - formParams[r'status'] = parameterToString(status); - } + if (name != null) { + formParams[r'name'] = parameterToString(name); + } + if (status != null) { + formParams[r'status'] = parameterToString(status); } return await apiClient.invokeAPI( @@ -581,28 +496,19 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (additionalMetadata != null) { - hasFields = true; - mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); - } - if (file != null) { - hasFields = true; - mp.fields[r'file'] = file.field; - mp.files.add(file); - } - if (hasFields) { - postBody = mp; - } - } else { - if (additionalMetadata != null) { - formParams[r'additionalMetadata'] = parameterToString(additionalMetadata); - } + bool hasFields = false; + final mp = MultipartRequest('POST', Uri.parse(path)); + if (additionalMetadata != null) { + hasFields = true; + mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); + } + if (file != null) { + hasFields = true; + mp.fields[r'file'] = file.field; + mp.files.add(file); + } + if (hasFields) { + postBody = mp; } return await apiClient.invokeAPI( diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart index 9696bacc9de1..4ff0cee3e1a0 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart @@ -44,17 +44,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -101,17 +90,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -171,17 +149,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -243,17 +210,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart index fc19afb4e93e..274b176291b3 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart @@ -43,17 +43,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -108,17 +97,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -171,17 +149,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -237,17 +204,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -303,17 +259,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -382,17 +327,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -445,17 +379,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -512,17 +435,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart index c847d27f60b1..35b984b86a13 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart @@ -77,7 +77,7 @@ class ApiClient { ? '?${urlEncodedQueryParams.join('&')}' : ''; - final url = '$basePath$path$queryString'; + final Uri uri = Uri.parse('$basePath$path$queryString'); if (nullableContentType != null) { headerParams['Content-Type'] = nullableContentType; @@ -89,7 +89,7 @@ class ApiClient { body is MultipartFile && (nullableContentType == null || !nullableContentType.toLowerCase().startsWith('multipart/form-data')) ) { - final request = StreamedRequest(method, Uri.parse(url)); + final request = StreamedRequest(method, uri); request.headers.addAll(headerParams); request.contentLength = body.length; body.finalize().listen( @@ -103,7 +103,7 @@ class ApiClient { } if (body is MultipartRequest) { - final request = MultipartRequest(method, Uri.parse(url)); + final request = MultipartRequest(method, uri); request.fields.addAll(body.fields); request.files.addAll(body.files); request.headers.addAll(body.headers); @@ -118,12 +118,12 @@ class ApiClient { final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; switch(method) { - case 'POST': return await _client.post(url, headers: nullableHeaderParams, body: msgBody,); - case 'PUT': return await _client.put(url, headers: nullableHeaderParams, body: msgBody,); - case 'DELETE': return await _client.delete(url, headers: nullableHeaderParams,); - case 'PATCH': return await _client.patch(url, headers: nullableHeaderParams, body: msgBody,); - case 'HEAD': return await _client.head(url, headers: nullableHeaderParams,); - case 'GET': return await _client.get(url, headers: nullableHeaderParams,); + case 'POST': return await _client.post(uri, headers: nullableHeaderParams, body: msgBody,); + case 'PUT': return await _client.put(uri, headers: nullableHeaderParams, body: msgBody,); + case 'DELETE': return await _client.delete(uri, headers: nullableHeaderParams,); + case 'PATCH': return await _client.patch(uri, headers: nullableHeaderParams, body: msgBody,); + case 'HEAD': return await _client.head(uri, headers: nullableHeaderParams,); + case 'GET': return await _client.get(uri, headers: nullableHeaderParams,); } } on SocketException catch (e, trace) { throw ApiException.withInner(HttpStatus.badRequest, 'Socket operation failed: $method $path', e, trace,); diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_exception.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_exception.dart index 1537c9769b21..86e2054bffec 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_exception.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_exception.dart @@ -19,6 +19,7 @@ class ApiException implements Exception { Exception innerException; StackTrace stackTrace; + @override String toString() { if (message == null) { return 'ApiException'; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart index 4135dcf95b26..cb1db7f0a015 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart @@ -28,7 +28,7 @@ Iterable _convertParametersForCollectionFormat( final params = []; // preconditions - if (name != null && !name.isEmpty && value != null) { + if (name != null && name.isNotEmpty && value != null) { if (value is List) { // get the collection format, default: csv collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/pubspec.yaml b/samples/openapi3/client/petstore/dart2/petstore_client_lib/pubspec.yaml index 06e772631725..163b29ec3ecc 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/pubspec.yaml @@ -5,16 +5,14 @@ name: 'openapi' version: '1.0.0' description: 'OpenAPI API client' -authors: - - 'Author ' homepage: 'homepage' environment: - sdk: '>=2.0.0 <3.0.0' + sdk: '>=2.12.0 <3.0.0' dependencies: - http: '>=0.12.0 <0.13.0' - intl: '^0.16.1' + http: '>=0.13.0 <0.14.0' + intl: '^0.17.0' meta: '^1.1.8' dev_dependencies: - test: '>=1.3.0 <1.16.0' + test: '>=1.16.0 <1.18.0' diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/README.md b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/README.md index fe39c2f21264..ec001c87cea3 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/README.md +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/README.md @@ -67,6 +67,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterNumberSerialize**](doc//FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | *FakeApi* | [**fakeOuterStringSerialize**](doc//FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | *FakeApi* | [**fakePropertyEnumIntegerSerialize**](doc//FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**testBodyWithBinary**](doc//FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | *FakeApi* | [**testBodyWithFileSchema**](doc//FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](doc//FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**testClientModel**](doc//FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/FakeApi.md b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/FakeApi.md index 8b7f63bf8bde..6d613003880f 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/FakeApi.md +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/FakeApi.md @@ -16,6 +16,7 @@ Method | HTTP request | Description [**fakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | [**fakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +[**testBodyWithBinary**](FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | [**testBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | [**testClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model @@ -323,12 +324,54 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **testBodyWithBinary** +> testBodyWithBinary(body) + + + +For this test, the body has to be a binary file. + +### Example +```dart +import 'package:openapi/api.dart'; + +final api_instance = FakeApi(); +final body = MultipartFile(); // MultipartFile | image to upload + +try { + api_instance.testBodyWithBinary(body); +} catch (e) { + print('Exception when calling FakeApi->testBodyWithBinary: $e\n'); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **MultipartFile**| image to upload | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: image/png + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **testBodyWithFileSchema** > testBodyWithFileSchema(fileSchemaTestClass) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example ```dart diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/another_fake_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/another_fake_api.dart index c297f77a8a34..8f8b96abc53e 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/another_fake_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/another_fake_api.dart @@ -43,17 +43,6 @@ class AnotherFakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/default_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/default_api.dart index 1185af2521cd..e811495110f0 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/default_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/default_api.dart @@ -29,17 +29,6 @@ class DefaultApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_api.dart index 20db8f0c9b06..07742e02082f 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_api.dart @@ -31,17 +31,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -110,17 +99,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['http_signature_test']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -176,17 +154,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -243,17 +210,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -310,17 +266,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -377,17 +322,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -447,17 +381,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -491,7 +414,59 @@ class FakeApi { return Future.value(null); } - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body has to be a binary file. + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: + /// + /// * [MultipartFile] body (required): + /// image to upload + Future testBodyWithBinaryWithHttpInfo(MultipartFile body) async { + // Verify required params are set. + if (body == null) { + throw ApiException(HttpStatus.badRequest, 'Missing required param: body'); + } + + final path = r'/fake/body-with-binary'; + + Object postBody = body; + + final queryParams = []; + final headerParams = {}; + final formParams = {}; + + final contentTypes = ['image/png']; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = []; + + + return await apiClient.invokeAPI( + path, + 'PUT', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); + } + + /// For this test, the body has to be a binary file. + /// + /// Parameters: + /// + /// * [MultipartFile] body (required): + /// image to upload + Future testBodyWithBinary(MultipartFile body) async { + final response = await testBodyWithBinaryWithHttpInfo(body); + if (response.statusCode >= HttpStatus.badRequest) { + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); + } + } + + /// For this test, the body for this request must reference a schema named `File`. /// /// Note: This method returns the HTTP [Response]. /// @@ -516,17 +491,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -540,7 +504,7 @@ class FakeApi { ); } - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body for this request must reference a schema named `File`. /// /// Parameters: /// @@ -581,17 +545,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -645,17 +598,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -767,112 +709,44 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['http_basic_test']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (integer != null) { - hasFields = true; - mp.fields[r'integer'] = parameterToString(integer); - } - if (int32 != null) { - hasFields = true; - mp.fields[r'int32'] = parameterToString(int32); - } - if (int64 != null) { - hasFields = true; - mp.fields[r'int64'] = parameterToString(int64); - } - if (number != null) { - hasFields = true; - mp.fields[r'number'] = parameterToString(number); - } - if (float != null) { - hasFields = true; - mp.fields[r'float'] = parameterToString(float); - } - if (double_ != null) { - hasFields = true; - mp.fields[r'double'] = parameterToString(double_); - } - if (string != null) { - hasFields = true; - mp.fields[r'string'] = parameterToString(string); - } - if (patternWithoutDelimiter != null) { - hasFields = true; - mp.fields[r'pattern_without_delimiter'] = parameterToString(patternWithoutDelimiter); - } - if (byte != null) { - hasFields = true; - mp.fields[r'byte'] = parameterToString(byte); - } - if (binary != null) { - hasFields = true; - mp.fields[r'binary'] = binary.field; - mp.files.add(binary); - } - if (date != null) { - hasFields = true; - mp.fields[r'date'] = parameterToString(date); - } - if (dateTime != null) { - hasFields = true; - mp.fields[r'dateTime'] = parameterToString(dateTime); - } - if (password != null) { - hasFields = true; - mp.fields[r'password'] = parameterToString(password); - } - if (callback != null) { - hasFields = true; - mp.fields[r'callback'] = parameterToString(callback); - } - if (hasFields) { - postBody = mp; - } - } else { - if (integer != null) { - formParams[r'integer'] = parameterToString(integer); - } - if (int32 != null) { - formParams[r'int32'] = parameterToString(int32); - } - if (int64 != null) { - formParams[r'int64'] = parameterToString(int64); - } - if (number != null) { - formParams[r'number'] = parameterToString(number); - } - if (float != null) { - formParams[r'float'] = parameterToString(float); - } - if (double_ != null) { - formParams[r'double'] = parameterToString(double_); - } - if (string != null) { - formParams[r'string'] = parameterToString(string); - } - if (patternWithoutDelimiter != null) { - formParams[r'pattern_without_delimiter'] = parameterToString(patternWithoutDelimiter); - } - if (byte != null) { - formParams[r'byte'] = parameterToString(byte); - } - if (date != null) { - formParams[r'date'] = parameterToString(date); - } - if (dateTime != null) { - formParams[r'dateTime'] = parameterToString(dateTime); - } - if (password != null) { - formParams[r'password'] = parameterToString(password); - } - if (callback != null) { - formParams[r'callback'] = parameterToString(callback); - } + if (integer != null) { + formParams[r'integer'] = parameterToString(integer); + } + if (int32 != null) { + formParams[r'int32'] = parameterToString(int32); + } + if (int64 != null) { + formParams[r'int64'] = parameterToString(int64); + } + if (number != null) { + formParams[r'number'] = parameterToString(number); + } + if (float != null) { + formParams[r'float'] = parameterToString(float); + } + if (double_ != null) { + formParams[r'double'] = parameterToString(double_); + } + if (string != null) { + formParams[r'string'] = parameterToString(string); + } + if (patternWithoutDelimiter != null) { + formParams[r'pattern_without_delimiter'] = parameterToString(patternWithoutDelimiter); + } + if (byte != null) { + formParams[r'byte'] = parameterToString(byte); + } + if (date != null) { + formParams[r'date'] = parameterToString(date); + } + if (dateTime != null) { + formParams[r'dateTime'] = parameterToString(dateTime); + } + if (password != null) { + formParams[r'password'] = parameterToString(password); + } + if (callback != null) { + formParams[r'callback'] = parameterToString(callback); } return await apiClient.invokeAPI( @@ -1007,30 +881,11 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (enumFormStringArray != null) { - hasFields = true; - mp.fields[r'enum_form_string_array'] = parameterToString(enumFormStringArray); - } - if (enumFormString != null) { - hasFields = true; - mp.fields[r'enum_form_string'] = parameterToString(enumFormString); - } - if (hasFields) { - postBody = mp; - } - } else { - if (enumFormStringArray != null) { - formParams[r'enum_form_string_array'] = parameterToString(enumFormStringArray); - } - if (enumFormString != null) { - formParams[r'enum_form_string'] = parameterToString(enumFormString); - } + if (enumFormStringArray != null) { + formParams[r'enum_form_string_array'] = parameterToString(enumFormStringArray); + } + if (enumFormString != null) { + formParams[r'enum_form_string'] = parameterToString(enumFormString); } return await apiClient.invokeAPI( @@ -1144,17 +999,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['bearer_test']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -1224,17 +1068,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -1293,30 +1126,11 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (param != null) { - hasFields = true; - mp.fields[r'param'] = parameterToString(param); - } - if (param2 != null) { - hasFields = true; - mp.fields[r'param2'] = parameterToString(param2); - } - if (hasFields) { - postBody = mp; - } - } else { - if (param != null) { - formParams[r'param'] = parameterToString(param); - } - if (param2 != null) { - formParams[r'param2'] = parameterToString(param2); - } + if (param != null) { + formParams[r'param'] = parameterToString(param); + } + if (param2 != null) { + formParams[r'param2'] = parameterToString(param2); } return await apiClient.invokeAPI( @@ -1388,7 +1202,7 @@ class FakeApi { final headerParams = {}; final formParams = {}; - queryParams.addAll(_convertParametersForCollectionFormat('multi', 'pipe', pipe)); + queryParams.addAll(_convertParametersForCollectionFormat('pipes', 'pipe', pipe)); queryParams.addAll(_convertParametersForCollectionFormat('csv', 'ioutil', ioutil)); queryParams.addAll(_convertParametersForCollectionFormat('ssv', 'http', http)); queryParams.addAll(_convertParametersForCollectionFormat('csv', 'url', url)); @@ -1398,17 +1212,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart index f7e337dbee5d..79ec2cbed45c 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart @@ -43,17 +43,6 @@ class FakeClassnameTags123Api { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key_query']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/pet_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/pet_api.dart index af2215c4db76..50d001f61ced 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/pet_api.dart @@ -41,17 +41,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -111,17 +100,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -180,17 +158,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -258,17 +225,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -335,17 +291,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -407,17 +352,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -477,30 +411,11 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (name != null) { - hasFields = true; - mp.fields[r'name'] = parameterToString(name); - } - if (status != null) { - hasFields = true; - mp.fields[r'status'] = parameterToString(status); - } - if (hasFields) { - postBody = mp; - } - } else { - if (name != null) { - formParams[r'name'] = parameterToString(name); - } - if (status != null) { - formParams[r'status'] = parameterToString(status); - } + if (name != null) { + formParams[r'name'] = parameterToString(name); + } + if (status != null) { + formParams[r'status'] = parameterToString(status); } return await apiClient.invokeAPI( @@ -567,28 +482,19 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (additionalMetadata != null) { - hasFields = true; - mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); - } - if (file != null) { - hasFields = true; - mp.fields[r'file'] = file.field; - mp.files.add(file); - } - if (hasFields) { - postBody = mp; - } - } else { - if (additionalMetadata != null) { - formParams[r'additionalMetadata'] = parameterToString(additionalMetadata); - } + bool hasFields = false; + final mp = MultipartRequest('POST', Uri.parse(path)); + if (additionalMetadata != null) { + hasFields = true; + mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); + } + if (file != null) { + hasFields = true; + mp.fields[r'file'] = file.field; + mp.files.add(file); + } + if (hasFields) { + postBody = mp; } return await apiClient.invokeAPI( @@ -665,28 +571,19 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (additionalMetadata != null) { - hasFields = true; - mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); - } - if (requiredFile != null) { - hasFields = true; - mp.fields[r'requiredFile'] = requiredFile.field; - mp.files.add(requiredFile); - } - if (hasFields) { - postBody = mp; - } - } else { - if (additionalMetadata != null) { - formParams[r'additionalMetadata'] = parameterToString(additionalMetadata); - } + bool hasFields = false; + final mp = MultipartRequest('POST', Uri.parse(path)); + if (additionalMetadata != null) { + hasFields = true; + mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); + } + if (requiredFile != null) { + hasFields = true; + mp.fields[r'requiredFile'] = requiredFile.field; + mp.files.add(requiredFile); + } + if (hasFields) { + postBody = mp; } return await apiClient.invokeAPI( diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/store_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/store_api.dart index ea459d16052a..08a73bb8fcaf 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/store_api.dart @@ -44,17 +44,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -101,17 +90,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -171,17 +149,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -243,17 +210,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/user_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/user_api.dart index 0a2c54c75feb..d45509dcac57 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/user_api.dart @@ -43,17 +43,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -108,17 +97,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -171,17 +149,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -237,17 +204,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -303,17 +259,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -382,17 +327,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -445,17 +379,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -512,17 +435,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart index 83cad2d3ded6..0aa83cf01972 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart @@ -80,7 +80,7 @@ class ApiClient { ? '?${urlEncodedQueryParams.join('&')}' : ''; - final url = '$basePath$path$queryString'; + final Uri uri = Uri.parse('$basePath$path$queryString'); if (nullableContentType != null) { headerParams['Content-Type'] = nullableContentType; @@ -92,7 +92,7 @@ class ApiClient { body is MultipartFile && (nullableContentType == null || !nullableContentType.toLowerCase().startsWith('multipart/form-data')) ) { - final request = StreamedRequest(method, Uri.parse(url)); + final request = StreamedRequest(method, uri); request.headers.addAll(headerParams); request.contentLength = body.length; body.finalize().listen( @@ -106,7 +106,7 @@ class ApiClient { } if (body is MultipartRequest) { - final request = MultipartRequest(method, Uri.parse(url)); + final request = MultipartRequest(method, uri); request.fields.addAll(body.fields); request.files.addAll(body.files); request.headers.addAll(body.headers); @@ -121,12 +121,12 @@ class ApiClient { final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; switch(method) { - case 'POST': return await _client.post(url, headers: nullableHeaderParams, body: msgBody,); - case 'PUT': return await _client.put(url, headers: nullableHeaderParams, body: msgBody,); - case 'DELETE': return await _client.delete(url, headers: nullableHeaderParams,); - case 'PATCH': return await _client.patch(url, headers: nullableHeaderParams, body: msgBody,); - case 'HEAD': return await _client.head(url, headers: nullableHeaderParams,); - case 'GET': return await _client.get(url, headers: nullableHeaderParams,); + case 'POST': return await _client.post(uri, headers: nullableHeaderParams, body: msgBody,); + case 'PUT': return await _client.put(uri, headers: nullableHeaderParams, body: msgBody,); + case 'DELETE': return await _client.delete(uri, headers: nullableHeaderParams,); + case 'PATCH': return await _client.patch(uri, headers: nullableHeaderParams, body: msgBody,); + case 'HEAD': return await _client.head(uri, headers: nullableHeaderParams,); + case 'GET': return await _client.get(uri, headers: nullableHeaderParams,); } } on SocketException catch (e, trace) { throw ApiException.withInner(HttpStatus.badRequest, 'Socket operation failed: $method $path', e, trace,); diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_exception.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_exception.dart index 1537c9769b21..86e2054bffec 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_exception.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_exception.dart @@ -19,6 +19,7 @@ class ApiException implements Exception { Exception innerException; StackTrace stackTrace; + @override String toString() { if (message == null) { return 'ApiException'; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_helper.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_helper.dart index 96214037944d..474cfb4294fb 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_helper.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_helper.dart @@ -28,7 +28,7 @@ Iterable _convertParametersForCollectionFormat( final params = []; // preconditions - if (name != null && !name.isEmpty && value != null) { + if (name != null && name.isNotEmpty && value != null) { if (value is List) { // get the collection format, default: csv collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/pubspec.yaml b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/pubspec.yaml index 06e772631725..163b29ec3ecc 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/pubspec.yaml @@ -5,16 +5,14 @@ name: 'openapi' version: '1.0.0' description: 'OpenAPI API client' -authors: - - 'Author ' homepage: 'homepage' environment: - sdk: '>=2.0.0 <3.0.0' + sdk: '>=2.12.0 <3.0.0' dependencies: - http: '>=0.12.0 <0.13.0' - intl: '^0.16.1' + http: '>=0.13.0 <0.14.0' + intl: '^0.17.0' meta: '^1.1.8' dev_dependencies: - test: '>=1.3.0 <1.16.0' + test: '>=1.16.0 <1.18.0' diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/README.md b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/README.md index fe39c2f21264..ec001c87cea3 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/README.md +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/README.md @@ -67,6 +67,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterNumberSerialize**](doc//FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | *FakeApi* | [**fakeOuterStringSerialize**](doc//FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | *FakeApi* | [**fakePropertyEnumIntegerSerialize**](doc//FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**testBodyWithBinary**](doc//FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | *FakeApi* | [**testBodyWithFileSchema**](doc//FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](doc//FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**testClientModel**](doc//FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/build.yaml b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/build.yaml index b5399b955dbc..89a4dd6e1c2e 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/build.yaml +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/build.yaml @@ -16,4 +16,3 @@ targets: field_rename: none ignore_unannotated: false include_if_null: false - nullable: true diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/doc/FakeApi.md b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/doc/FakeApi.md index 8b7f63bf8bde..6d613003880f 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/doc/FakeApi.md +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/doc/FakeApi.md @@ -16,6 +16,7 @@ Method | HTTP request | Description [**fakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | [**fakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +[**testBodyWithBinary**](FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | [**testBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | [**testClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model @@ -323,12 +324,54 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **testBodyWithBinary** +> testBodyWithBinary(body) + + + +For this test, the body has to be a binary file. + +### Example +```dart +import 'package:openapi/api.dart'; + +final api_instance = FakeApi(); +final body = MultipartFile(); // MultipartFile | image to upload + +try { + api_instance.testBodyWithBinary(body); +} catch (e) { + print('Exception when calling FakeApi->testBodyWithBinary: $e\n'); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **MultipartFile**| image to upload | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: image/png + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **testBodyWithFileSchema** > testBodyWithFileSchema(fileSchemaTestClass) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example ```dart diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/another_fake_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/another_fake_api.dart index b712431a035f..f0115e6907b7 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/another_fake_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/another_fake_api.dart @@ -43,17 +43,6 @@ class AnotherFakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/default_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/default_api.dart index 779bdec8b3a6..182442cbd42f 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/default_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/default_api.dart @@ -29,17 +29,6 @@ class DefaultApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_api.dart index edcd08cfa4a6..30111f17ac25 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_api.dart @@ -31,17 +31,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -111,17 +100,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['http_signature_test']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -177,17 +155,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -245,17 +212,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -313,17 +269,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -381,17 +326,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -452,17 +386,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -497,7 +420,59 @@ class FakeApi { return Future.value(null); } - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body has to be a binary file. + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: + /// + /// * [MultipartFile] body (required): + /// image to upload + Future testBodyWithBinaryWithHttpInfo(MultipartFile body) async { + // Verify required params are set. + if (body == null) { + throw ApiException(HttpStatus.badRequest, 'Missing required param: body'); + } + + final path = r'/fake/body-with-binary'; + + Object postBody = body; + + final queryParams = []; + final headerParams = {}; + final formParams = {}; + + final contentTypes = ['image/png']; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = []; + + + return await apiClient.invokeAPI( + path, + 'PUT', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); + } + + /// For this test, the body has to be a binary file. + /// + /// Parameters: + /// + /// * [MultipartFile] body (required): + /// image to upload + Future testBodyWithBinary(MultipartFile body) async { + final response = await testBodyWithBinaryWithHttpInfo(body); + if (response.statusCode >= HttpStatus.badRequest) { + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); + } + } + + /// For this test, the body for this request must reference a schema named `File`. /// /// Note: This method returns the HTTP [Response]. /// @@ -522,17 +497,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -546,7 +510,7 @@ class FakeApi { ); } - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body for this request must reference a schema named `File`. /// /// Parameters: /// @@ -587,17 +551,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -651,17 +604,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -774,112 +716,44 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['http_basic_test']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (integer != null) { - hasFields = true; - mp.fields[r'integer'] = parameterToString(integer); - } - if (int32 != null) { - hasFields = true; - mp.fields[r'int32'] = parameterToString(int32); - } - if (int64 != null) { - hasFields = true; - mp.fields[r'int64'] = parameterToString(int64); - } - if (number != null) { - hasFields = true; - mp.fields[r'number'] = parameterToString(number); - } - if (float != null) { - hasFields = true; - mp.fields[r'float'] = parameterToString(float); - } - if (double_ != null) { - hasFields = true; - mp.fields[r'double'] = parameterToString(double_); - } - if (string != null) { - hasFields = true; - mp.fields[r'string'] = parameterToString(string); - } - if (patternWithoutDelimiter != null) { - hasFields = true; - mp.fields[r'pattern_without_delimiter'] = parameterToString(patternWithoutDelimiter); - } - if (byte != null) { - hasFields = true; - mp.fields[r'byte'] = parameterToString(byte); - } - if (binary != null) { - hasFields = true; - mp.fields[r'binary'] = binary.field; - mp.files.add(binary); - } - if (date != null) { - hasFields = true; - mp.fields[r'date'] = parameterToString(date); - } - if (dateTime != null) { - hasFields = true; - mp.fields[r'dateTime'] = parameterToString(dateTime); - } - if (password != null) { - hasFields = true; - mp.fields[r'password'] = parameterToString(password); - } - if (callback != null) { - hasFields = true; - mp.fields[r'callback'] = parameterToString(callback); - } - if (hasFields) { - postBody = mp; - } - } else { - if (integer != null) { - formParams[r'integer'] = parameterToString(integer); - } - if (int32 != null) { - formParams[r'int32'] = parameterToString(int32); - } - if (int64 != null) { - formParams[r'int64'] = parameterToString(int64); - } - if (number != null) { - formParams[r'number'] = parameterToString(number); - } - if (float != null) { - formParams[r'float'] = parameterToString(float); - } - if (double_ != null) { - formParams[r'double'] = parameterToString(double_); - } - if (string != null) { - formParams[r'string'] = parameterToString(string); - } - if (patternWithoutDelimiter != null) { - formParams[r'pattern_without_delimiter'] = parameterToString(patternWithoutDelimiter); - } - if (byte != null) { - formParams[r'byte'] = parameterToString(byte); - } - if (date != null) { - formParams[r'date'] = parameterToString(date); - } - if (dateTime != null) { - formParams[r'dateTime'] = parameterToString(dateTime); - } - if (password != null) { - formParams[r'password'] = parameterToString(password); - } - if (callback != null) { - formParams[r'callback'] = parameterToString(callback); - } + if (integer != null) { + formParams[r'integer'] = parameterToString(integer); + } + if (int32 != null) { + formParams[r'int32'] = parameterToString(int32); + } + if (int64 != null) { + formParams[r'int64'] = parameterToString(int64); + } + if (number != null) { + formParams[r'number'] = parameterToString(number); + } + if (float != null) { + formParams[r'float'] = parameterToString(float); + } + if (double_ != null) { + formParams[r'double'] = parameterToString(double_); + } + if (string != null) { + formParams[r'string'] = parameterToString(string); + } + if (patternWithoutDelimiter != null) { + formParams[r'pattern_without_delimiter'] = parameterToString(patternWithoutDelimiter); + } + if (byte != null) { + formParams[r'byte'] = parameterToString(byte); + } + if (date != null) { + formParams[r'date'] = parameterToString(date); + } + if (dateTime != null) { + formParams[r'dateTime'] = parameterToString(dateTime); + } + if (password != null) { + formParams[r'password'] = parameterToString(password); + } + if (callback != null) { + formParams[r'callback'] = parameterToString(callback); } return await apiClient.invokeAPI( @@ -1014,30 +888,11 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (enumFormStringArray != null) { - hasFields = true; - mp.fields[r'enum_form_string_array'] = parameterToString(enumFormStringArray); - } - if (enumFormString != null) { - hasFields = true; - mp.fields[r'enum_form_string'] = parameterToString(enumFormString); - } - if (hasFields) { - postBody = mp; - } - } else { - if (enumFormStringArray != null) { - formParams[r'enum_form_string_array'] = parameterToString(enumFormStringArray); - } - if (enumFormString != null) { - formParams[r'enum_form_string'] = parameterToString(enumFormString); - } + if (enumFormStringArray != null) { + formParams[r'enum_form_string_array'] = parameterToString(enumFormStringArray); + } + if (enumFormString != null) { + formParams[r'enum_form_string'] = parameterToString(enumFormString); } return await apiClient.invokeAPI( @@ -1151,17 +1006,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['bearer_test']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -1231,17 +1075,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -1300,30 +1133,11 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (param != null) { - hasFields = true; - mp.fields[r'param'] = parameterToString(param); - } - if (param2 != null) { - hasFields = true; - mp.fields[r'param2'] = parameterToString(param2); - } - if (hasFields) { - postBody = mp; - } - } else { - if (param != null) { - formParams[r'param'] = parameterToString(param); - } - if (param2 != null) { - formParams[r'param2'] = parameterToString(param2); - } + if (param != null) { + formParams[r'param'] = parameterToString(param); + } + if (param2 != null) { + formParams[r'param2'] = parameterToString(param2); } return await apiClient.invokeAPI( @@ -1395,7 +1209,7 @@ class FakeApi { final headerParams = {}; final formParams = {}; - queryParams.addAll(_convertParametersForCollectionFormat('multi', 'pipe', pipe)); + queryParams.addAll(_convertParametersForCollectionFormat('pipes', 'pipe', pipe)); queryParams.addAll(_convertParametersForCollectionFormat('csv', 'ioutil', ioutil)); queryParams.addAll(_convertParametersForCollectionFormat('ssv', 'http', http)); queryParams.addAll(_convertParametersForCollectionFormat('csv', 'url', url)); @@ -1405,17 +1219,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_classname_tags123_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_classname_tags123_api.dart index 49f4ce7cde23..c9fc34d194c4 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_classname_tags123_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_classname_tags123_api.dart @@ -43,17 +43,6 @@ class FakeClassnameTags123Api { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key_query']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/pet_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/pet_api.dart index cd2a65ab9397..dec9efa15f7a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/pet_api.dart @@ -41,17 +41,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -111,17 +100,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -180,17 +158,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -259,17 +226,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -337,17 +293,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -410,17 +355,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -480,30 +414,11 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (name != null) { - hasFields = true; - mp.fields[r'name'] = parameterToString(name); - } - if (status != null) { - hasFields = true; - mp.fields[r'status'] = parameterToString(status); - } - if (hasFields) { - postBody = mp; - } - } else { - if (name != null) { - formParams[r'name'] = parameterToString(name); - } - if (status != null) { - formParams[r'status'] = parameterToString(status); - } + if (name != null) { + formParams[r'name'] = parameterToString(name); + } + if (status != null) { + formParams[r'status'] = parameterToString(status); } return await apiClient.invokeAPI( @@ -570,28 +485,19 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (additionalMetadata != null) { - hasFields = true; - mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); - } - if (file != null) { - hasFields = true; - mp.fields[r'file'] = file.field; - mp.files.add(file); - } - if (hasFields) { - postBody = mp; - } - } else { - if (additionalMetadata != null) { - formParams[r'additionalMetadata'] = parameterToString(additionalMetadata); - } + bool hasFields = false; + final mp = MultipartRequest('POST', Uri.parse(path)); + if (additionalMetadata != null) { + hasFields = true; + mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); + } + if (file != null) { + hasFields = true; + mp.fields[r'file'] = file.field; + mp.files.add(file); + } + if (hasFields) { + postBody = mp; } return await apiClient.invokeAPI( @@ -669,28 +575,19 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (additionalMetadata != null) { - hasFields = true; - mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); - } - if (requiredFile != null) { - hasFields = true; - mp.fields[r'requiredFile'] = requiredFile.field; - mp.files.add(requiredFile); - } - if (hasFields) { - postBody = mp; - } - } else { - if (additionalMetadata != null) { - formParams[r'additionalMetadata'] = parameterToString(additionalMetadata); - } + bool hasFields = false; + final mp = MultipartRequest('POST', Uri.parse(path)); + if (additionalMetadata != null) { + hasFields = true; + mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); + } + if (requiredFile != null) { + hasFields = true; + mp.fields[r'requiredFile'] = requiredFile.field; + mp.files.add(requiredFile); + } + if (hasFields) { + postBody = mp; } return await apiClient.invokeAPI( diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/store_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/store_api.dart index 9e262c18b98f..f7a67632d331 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/store_api.dart @@ -44,17 +44,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -101,17 +90,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -172,17 +150,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -245,17 +212,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/user_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/user_api.dart index 3291afc26708..13e62586ac99 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/user_api.dart @@ -43,17 +43,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -108,17 +97,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -171,17 +149,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -237,17 +204,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -303,17 +259,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -383,17 +328,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -447,17 +381,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -514,17 +437,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_client.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_client.dart index f54d8cad38d4..65c9ec57844d 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_client.dart @@ -80,7 +80,7 @@ class ApiClient { ? '?${urlEncodedQueryParams.join('&')}' : ''; - final url = '$basePath$path$queryString'; + final Uri uri = Uri.parse('$basePath$path$queryString'); if (nullableContentType != null) { headerParams['Content-Type'] = nullableContentType; @@ -92,7 +92,7 @@ class ApiClient { body is MultipartFile && (nullableContentType == null || !nullableContentType.toLowerCase().startsWith('multipart/form-data')) ) { - final request = StreamedRequest(method, Uri.parse(url)); + final request = StreamedRequest(method, uri); request.headers.addAll(headerParams); request.contentLength = body.length; body.finalize().listen( @@ -106,7 +106,7 @@ class ApiClient { } if (body is MultipartRequest) { - final request = MultipartRequest(method, Uri.parse(url)); + final request = MultipartRequest(method, uri); request.fields.addAll(body.fields); request.files.addAll(body.files); request.headers.addAll(body.headers); @@ -121,12 +121,12 @@ class ApiClient { final nullableHeaderParams = headerParams.isEmpty ? null : headerParams; switch(method) { - case 'POST': return await _client.post(url, headers: nullableHeaderParams, body: msgBody,); - case 'PUT': return await _client.put(url, headers: nullableHeaderParams, body: msgBody,); - case 'DELETE': return await _client.delete(url, headers: nullableHeaderParams,); - case 'PATCH': return await _client.patch(url, headers: nullableHeaderParams, body: msgBody,); - case 'HEAD': return await _client.head(url, headers: nullableHeaderParams,); - case 'GET': return await _client.get(url, headers: nullableHeaderParams,); + case 'POST': return await _client.post(uri, headers: nullableHeaderParams, body: msgBody,); + case 'PUT': return await _client.put(uri, headers: nullableHeaderParams, body: msgBody,); + case 'DELETE': return await _client.delete(uri, headers: nullableHeaderParams,); + case 'PATCH': return await _client.patch(uri, headers: nullableHeaderParams, body: msgBody,); + case 'HEAD': return await _client.head(uri, headers: nullableHeaderParams,); + case 'GET': return await _client.get(uri, headers: nullableHeaderParams,); } } on SocketException catch (e, trace) { throw ApiException.withInner(HttpStatus.badRequest, 'Socket operation failed: $method $path', e, trace,); diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_exception.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_exception.dart index 1537c9769b21..86e2054bffec 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_exception.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_exception.dart @@ -19,6 +19,7 @@ class ApiException implements Exception { Exception innerException; StackTrace stackTrace; + @override String toString() { if (message == null) { return 'ApiException'; diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_helper.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_helper.dart index 51db433eb307..e88f8cc2987a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_helper.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_helper.dart @@ -28,7 +28,7 @@ Iterable _convertParametersForCollectionFormat( final params = []; // preconditions - if (name != null && !name.isEmpty && value != null) { + if (name != null && name.isNotEmpty && value != null) { if (value is List) { // get the collection format, default: csv collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/pubspec.yaml b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/pubspec.yaml index a54b8ac20063..66b0d5a7acde 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/pubspec.yaml @@ -5,17 +5,15 @@ name: 'openapi' version: '1.0.0' description: 'OpenAPI API client' -authors: - - 'Author ' homepage: 'homepage' environment: - sdk: '>=2.0.0 <3.0.0' + sdk: '>=2.12.0 <3.0.0' dependencies: - http: '>=0.12.0 <0.13.0' - intl: '^0.16.1' + http: '>=0.13.0 <0.14.0' + intl: '^0.17.0' meta: '^1.1.8' json_annotation: '^3.1.1' dev_dependencies: - test: '>=1.3.0 <1.16.0' - build_runner: '^1.0.0' + test: '>=1.16.0 <1.18.0' + build_runner: '^1.10.9' json_serializable: '^3.5.1' diff --git a/samples/openapi3/client/petstore/go/go-petstore/.openapi-generator/VERSION b/samples/openapi3/client/petstore/go/go-petstore/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/go/go-petstore/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/.openapi-generator/VERSION b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/.openapi-generator/VERSION b/samples/openapi3/client/petstore/java/jersey2-java8/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/java/jersey2-java8/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/java/native/.openapi-generator/VERSION b/samples/openapi3/client/petstore/java/native/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/petstore/java/native/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/java/native/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ApiClient.java index 98cdbf0646b1..4b5a1fb4bd34 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/ApiClient.java @@ -175,7 +175,7 @@ public ApiClient() { public ApiClient(HttpClient.Builder builder, ObjectMapper mapper, String baseUri) { this.builder = builder; this.mapper = mapper; - updateBaseUri(baseUri); + updateBaseUri(baseUri != null ? baseUri : getDefaultBaseUri()); interceptor = null; readTimeout = null; responseInterceptor = null; diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index 388e0b3f4526..1d87022e718b 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -58,6 +58,14 @@ public AnotherFakeApi(ApiClient apiClient) { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * To test special tags * To test special tags and operation ID starting with number @@ -87,10 +95,7 @@ public ApiResponse call123testSpecialTagsWithHttpInfo(Client client) thr memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "call123testSpecialTags call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "call123testSpecialTags call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/DefaultApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/DefaultApi.java index efd1d4ca939f..fc06f1fc039b 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/DefaultApi.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/DefaultApi.java @@ -58,6 +58,14 @@ public DefaultApi(ApiClient apiClient) { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * * @@ -85,10 +93,7 @@ public ApiResponse fooGetWithHttpInfo() throws ApiExcepti memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "fooGet call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "fooGet call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java index 402c28afcd23..b5b0a141d330 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java @@ -67,6 +67,14 @@ public FakeApi(ApiClient apiClient) { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * Health check endpoint * @@ -94,10 +102,7 @@ public ApiResponse fakeHealthGetWithHttpInfo() throws ApiExce memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "fakeHealthGet call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "fakeHealthGet call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -161,10 +166,7 @@ public ApiResponse fakeOuterBooleanSerializeWithHttpInfo(Boolean body) memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "fakeOuterBooleanSerialize call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "fakeOuterBooleanSerialize call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -234,10 +236,7 @@ public ApiResponse fakeOuterCompositeSerializeWithHttpInfo(Outer memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "fakeOuterCompositeSerialize call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "fakeOuterCompositeSerialize call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -307,10 +306,7 @@ public ApiResponse fakeOuterNumberSerializeWithHttpInfo(BigDecimal b memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "fakeOuterNumberSerialize call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "fakeOuterNumberSerialize call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -380,10 +376,7 @@ public ApiResponse fakeOuterStringSerializeWithHttpInfo(String body) thr memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "fakeOuterStringSerialize call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "fakeOuterStringSerialize call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -451,10 +444,7 @@ public ApiResponse> getArrayOfEnumsWithHttpInfo() throws ApiExce memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "getArrayOfEnums call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "getArrayOfEnums call received non-success response"); } return new ApiResponse>( localVarResponse.statusCode(), @@ -516,10 +506,7 @@ public ApiResponse testBodyWithFileSchemaWithHttpInfo(FileSchemaTestClass memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "testBodyWithFileSchema call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "testBodyWithFileSchema call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -593,10 +580,7 @@ public ApiResponse testBodyWithQueryParamsWithHttpInfo(String query, User memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "testBodyWithQueryParams call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "testBodyWithQueryParams call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -683,10 +667,7 @@ public ApiResponse testClientModelWithHttpInfo(Client client) throws Api memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "testClientModel call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "testClientModel call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -784,10 +765,7 @@ public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, D memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "testEndpointParameters call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "testEndpointParameters call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -879,10 +857,7 @@ public ApiResponse testEnumParametersWithHttpInfo(List enumHeaderS memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "testEnumParameters call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "testEnumParameters call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -1005,10 +980,7 @@ public ApiResponse testGroupParametersWithHttpInfo(Integer requiredStringG memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "testGroupParameters call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "testGroupParameters call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -1177,10 +1149,7 @@ public ApiResponse testInlineAdditionalPropertiesWithHttpInfo(Map( localVarResponse.statusCode(), @@ -1254,10 +1223,7 @@ public ApiResponse testJsonFormDataWithHttpInfo(String param, String param memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "testJsonFormData call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "testJsonFormData call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -1335,10 +1301,7 @@ public ApiResponse testQueryParameterCollectionFormatWithHttpInfo(List( localVarResponse.statusCode(), diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index 8200797995f6..caeaf872f788 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -58,6 +58,14 @@ public FakeClassnameTags123Api(ApiClient apiClient) { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * To test class name in snake case * To test class name in snake case @@ -87,10 +95,7 @@ public ApiResponse testClassnameWithHttpInfo(Client client) throws ApiEx memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "testClassname call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "testClassname call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java index d97fb68b9083..530d75960d95 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java @@ -60,6 +60,14 @@ public PetApi(ApiClient apiClient) { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * Add a new pet to the store * @@ -87,10 +95,7 @@ public ApiResponse addPetWithHttpInfo(Pet pet) throws ApiException { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "addPet call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "addPet call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -164,10 +169,7 @@ public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "deletePet call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "deletePet call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -239,10 +241,7 @@ public ApiResponse> findPetsByStatusWithHttpInfo(List status) memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "findPetsByStatus call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "findPetsByStatus call received non-success response"); } return new ApiResponse>( localVarResponse.statusCode(), @@ -323,10 +322,7 @@ public ApiResponse> findPetsByTagsWithHttpInfo(List tags) thro memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "findPetsByTags call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "findPetsByTags call received non-success response"); } return new ApiResponse>( localVarResponse.statusCode(), @@ -403,10 +399,7 @@ public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "getPetById call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "getPetById call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -473,10 +466,7 @@ public ApiResponse updatePetWithHttpInfo(Pet pet) throws ApiException { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "updatePet call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "updatePet call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -552,10 +542,7 @@ public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "updatePetWithForm call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "updatePetWithForm call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -628,10 +615,7 @@ public ApiResponse uploadFileWithHttpInfo(Long petId, String a memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "uploadFile call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "uploadFile call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -704,10 +688,7 @@ public ApiResponse uploadFileWithRequiredFileWithHttpInfo(Long memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "uploadFileWithRequiredFile call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "uploadFileWithRequiredFile call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java index 0a4ad7902690..c06efabb4a8d 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java @@ -58,6 +58,14 @@ public StoreApi(ApiClient apiClient) { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -85,10 +93,7 @@ public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiExcep memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "deleteOrder call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "deleteOrder call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -155,10 +160,7 @@ public ApiResponse> getInventoryWithHttpInfo() throws ApiEx memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "getInventory call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "getInventory call received non-success response"); } return new ApiResponse>( localVarResponse.statusCode(), @@ -222,10 +224,7 @@ public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiExcep memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "getOrderById call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "getOrderById call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -294,10 +293,7 @@ public ApiResponse placeOrderWithHttpInfo(Order order) throws ApiExceptio memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "placeOrder call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "placeOrder call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java index 56579ab17f04..3c1a68c98815 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java @@ -58,6 +58,14 @@ public UserApi(ApiClient apiClient) { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } + protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + if (body != null) { + msgPrefix += ": " + body; + } + return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + } + /** * Create user * This can only be done by the logged in user. @@ -85,10 +93,7 @@ public ApiResponse createUserWithHttpInfo(User user) throws ApiException { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "createUser call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "createUser call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -160,10 +165,7 @@ public ApiResponse createUsersWithArrayInputWithHttpInfo(List user) memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "createUsersWithArrayInput call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "createUsersWithArrayInput call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -235,10 +237,7 @@ public ApiResponse createUsersWithListInputWithHttpInfo(List user) t memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "createUsersWithListInput call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "createUsersWithListInput call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -310,10 +309,7 @@ public ApiResponse deleteUserWithHttpInfo(String username) throws ApiExcep memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "deleteUser call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "deleteUser call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -382,10 +378,7 @@ public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiEx memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "getUserByName call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "getUserByName call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -456,10 +449,7 @@ public ApiResponse loginUserWithHttpInfo(String username, String passwor memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "loginUser call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "loginUser call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -537,10 +527,7 @@ public ApiResponse logoutUserWithHttpInfo() throws ApiException { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "logoutUser call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "logoutUser call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), @@ -604,10 +591,7 @@ public ApiResponse updateUserWithHttpInfo(String username, User user) thro memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw new ApiException(localVarResponse.statusCode(), - "updateUser call received non-success response", - localVarResponse.headers(), - localVarResponse.body() == null ? null : new String(localVarResponse.body().readAllBytes())); + throw createApiException(localVarResponse, "updateUser call received non-success response"); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/openapi3/client/petstore/python-experimental/.coverage b/samples/openapi3/client/petstore/python-experimental/.coverage new file mode 100644 index 000000000000..9e8563e13450 Binary files /dev/null and b/samples/openapi3/client/petstore/python-experimental/.coverage differ diff --git a/samples/openapi3/client/petstore/python-legacy/.openapi-generator/VERSION b/samples/openapi3/client/petstore/python-legacy/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100755 --- a/samples/openapi3/client/petstore/python-legacy/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/python-legacy/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python-legacy/README.md b/samples/openapi3/client/petstore/python-legacy/README.md index 65ce00102b4c..507b849f5b23 100755 --- a/samples/openapi3/client/petstore/python-legacy/README.md +++ b/samples/openapi3/client/petstore/python-legacy/README.md @@ -90,6 +90,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | *FakeApi* | [**fake_outer_string_serialize**](docs/FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | *FakeApi* | [**fake_property_enum_integer_serialize**](docs/FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**test_body_with_binary**](docs/FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | *FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | *FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model diff --git a/samples/openapi3/client/petstore/python-legacy/docs/FakeApi.md b/samples/openapi3/client/petstore/python-legacy/docs/FakeApi.md index f7bbbecdce6c..f958d8f71a00 100755 --- a/samples/openapi3/client/petstore/python-legacy/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/python-legacy/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**fake_outer_number_serialize**](FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | [**fake_outer_string_serialize**](FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | [**fake_property_enum_integer_serialize**](FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +[**test_body_with_binary**](FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | [**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | [**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model @@ -510,12 +511,72 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_body_with_binary** +> test_body_with_binary(body) + + + +For this test, the body has to be a binary file. + +### Example + +```python +from __future__ import print_function +import time +import petstore_api +from petstore_api.rest import ApiException +from pprint import pprint +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient() as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + body = '/path/to/file' # file | image to upload + + try: + api_instance.test_body_with_binary(body) + except ApiException as e: + print("Exception when calling FakeApi->test_body_with_binary: %s\n" % e) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **file**| image to upload | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: image/png + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_body_with_file_schema** > test_body_with_file_schema(file_schema_test_class) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/fake_api.py index d5dd027679ea..f2bf00824f90 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/fake_api.py @@ -982,10 +982,139 @@ def fake_property_enum_integer_serialize_with_http_info(self, outer_object_with_ collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) + def test_body_with_binary(self, body, **kwargs): # noqa: E501 + """test_body_with_binary # noqa: E501 + + For this test, the body has to be a binary file. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_body_with_binary(body, async_req=True) + >>> result = thread.get() + + :param body: image to upload (required) + :type body: file + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :type _preload_content: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + kwargs['_return_http_data_only'] = True + return self.test_body_with_binary_with_http_info(body, **kwargs) # noqa: E501 + + def test_body_with_binary_with_http_info(self, body, **kwargs): # noqa: E501 + """test_body_with_binary # noqa: E501 + + For this test, the body has to be a binary file. # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_body_with_binary_with_http_info(body, async_req=True) + >>> result = thread.get() + + :param body: image to upload (required) + :type body: file + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _return_http_data_only: response data without head status code + and headers + :type _return_http_data_only: bool, optional + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :type _preload_content: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + + local_var_params = locals() + + all_params = [ + 'body' + ] + all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth' + ] + ) + + for key, val in six.iteritems(local_var_params['kwargs']): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method test_body_with_binary" % key + ) + local_var_params[key] = val + del local_var_params['kwargs'] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if 'body' in local_var_params: + body_params = local_var_params['body'] + # HTTP header `Content-Type` + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['image/png']) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + response_types_map = {} + + return self.api_client.call_api( + '/fake/body-with-binary', 'PUT', + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_types_map=response_types_map, + auth_settings=auth_settings, + async_req=local_var_params.get('async_req'), + _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=local_var_params.get('_preload_content', True), + _request_timeout=local_var_params.get('_request_timeout'), + collection_formats=collection_formats, + _request_auth=local_var_params.get('_request_auth')) + def test_body_with_file_schema(self, file_schema_test_class, **kwargs): # noqa: E501 """test_body_with_file_schema # noqa: E501 - For this test, the body for this request much reference a schema named `File`. # noqa: E501 + For this test, the body for this request must reference a schema named `File`. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True @@ -1015,7 +1144,7 @@ def test_body_with_file_schema(self, file_schema_test_class, **kwargs): # noqa: def test_body_with_file_schema_with_http_info(self, file_schema_test_class, **kwargs): # noqa: E501 """test_body_with_file_schema # noqa: E501 - For this test, the body for this request much reference a schema named `File`. # noqa: E501 + For this test, the body for this request must reference a schema named `File`. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True @@ -2422,7 +2551,7 @@ def test_query_parameter_collection_format_with_http_info(self, pipe, ioutil, ht query_params = [] if 'pipe' in local_var_params and local_var_params['pipe'] is not None: # noqa: E501 query_params.append(('pipe', local_var_params['pipe'])) # noqa: E501 - collection_formats['pipe'] = 'multi' # noqa: E501 + collection_formats['pipe'] = 'pipes' # noqa: E501 if 'ioutil' in local_var_params and local_var_params['ioutil'] is not None: # noqa: E501 query_params.append(('ioutil', local_var_params['ioutil'])) # noqa: E501 collection_formats['ioutil'] = 'csv' # noqa: E501 diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/additional_properties_class.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/additional_properties_class.py index a846775889f8..f8303e680b26 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/additional_properties_class.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/additional_properties_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/animal.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/animal.py index 2427f910a97e..1a36f3398fff 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/animal.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/animal.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -117,7 +120,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/api_response.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/api_response.py index ab5e7999dd2f..bddac1eb10a3 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/api_response.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/api_response.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_of_array_of_number_only.py index c9b65c7e5315..2975adc20e31 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_of_array_of_number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_of_number_only.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_of_number_only.py index 870286e0fc08..2a3400e76660 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_of_number_only.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_of_number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_test.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_test.py index 0e0c17ef1909..5501a637f633 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_test.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/array_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -137,7 +140,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/capitalization.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/capitalization.py index 064dc2eb2ff5..cb8b0d985842 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/capitalization.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/capitalization.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -211,7 +214,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/cat.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/cat.py index 3b6e6aa4c2e8..0d9a0b20bf1a 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/cat.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/cat.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/cat_all_of.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/cat_all_of.py index 7755fd65b0c3..0633bbf58d0d 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/cat_all_of.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/cat_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/category.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/category.py index c3dd5a4b9a17..ef52dcbf8c91 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/category.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/category.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -106,7 +109,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/class_model.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/class_model.py index cd9439763d20..84c0de65b472 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/class_model.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/class_model.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/client.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/client.py index f896b35240c7..8d7c83ecfe6b 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/client.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/client.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/dog.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/dog.py index 39514284d5f2..61acd35cdfe2 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/dog.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/dog.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/dog_all_of.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/dog_all_of.py index 207103a48745..3a052c3258ae 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/dog_all_of.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/dog_all_of.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_arrays.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_arrays.py index b87cd37456e1..eb4f3ea4ca32 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_arrays.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_arrays.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -119,7 +122,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_class.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_class.py index 4b11877863ac..79aac3570cb9 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_class.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_test.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_test.py index 09d7d1e3d809..93333df88781 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_test.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/enum_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -285,7 +288,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/file.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/file.py index e40cd04b0149..2c1cccac0e11 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/file.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/file.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -81,7 +84,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/file_schema_test_class.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/file_schema_test_class.py index d266755d260a..c5a23842d4f6 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/file_schema_test_class.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/file_schema_test_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/foo.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/foo.py index 05abc6e9b9fe..cab632f369c4 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/foo.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/foo.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/format_test.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/format_test.py index a8323ade641e..4e96a7b9175e 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/format_test.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/format_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -522,7 +525,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/has_only_read_only.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/has_only_read_only.py index dac8cfaff937..7175c2acc721 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/has_only_read_only.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/has_only_read_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/health_check_result.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/health_check_result.py index cde33f5146a4..64a3f4b2b903 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/health_check_result.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/health_check_result.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -78,7 +81,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/inline_response_default.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/inline_response_default.py index d9da22a5fd3e..a199122621ff 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/inline_response_default.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/inline_response_default.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/list.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/list.py index b44257224741..6e1dea4e33b5 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/list.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/list.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/map_test.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/map_test.py index 406f35db7500..21bd2ccda980 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/map_test.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/map_test.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -165,7 +168,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/mixed_properties_and_additional_properties_class.py index 14428a6536a8..9e727b07d5c7 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/model200_response.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/model200_response.py index 5c90147467b5..db587fd24e2f 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/model200_response.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/model200_response.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/model_return.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/model_return.py index 88174ef23083..5354fd56e2ce 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/model_return.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/model_return.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/name.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/name.py index 528988ebd437..0191a3a934ae 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/name.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/name.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -158,7 +161,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/nullable_class.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/nullable_class.py index 490eb2ba7d01..d36862f8526d 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/nullable_class.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/nullable_class.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -355,7 +358,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/number_only.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/number_only.py index ebbcc8996d01..59a252e0bb66 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/number_only.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/number_only.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/order.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/order.py index 6513d48a3a5e..a267324d0d19 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/order.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/order.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -217,7 +220,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_composite.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_composite.py index 44124e13c09b..e26160ab4302 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_composite.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_composite.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -131,7 +134,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum.py index 77624ba15408..27cdfd1fb791 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_default_value.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_default_value.py index aae43db66e67..982e9599d0e5 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_default_value.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_default_value.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_integer.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_integer.py index d3d9ca3dbf9f..3feec9c5a5a2 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_integer.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_integer.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_integer_default_value.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_integer_default_value.py index 9e0ed2c1a8b1..6757a4d63674 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_integer_default_value.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_enum_integer_default_value.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -60,7 +63,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_object_with_enum_property.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_object_with_enum_property.py index 8a50b129a7fb..b9572300b6f6 100644 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_object_with_enum_property.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/outer_object_with_enum_property.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -80,7 +83,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/pet.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/pet.py index e71589429ca0..22bb4a585e47 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/pet.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/pet.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -219,7 +222,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/read_only_first.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/read_only_first.py index 3a320fe64f06..c2888eba7500 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/read_only_first.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/read_only_first.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/special_model_name.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/special_model_name.py index 7669a508789f..4c848e1887c0 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/special_model_name.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/special_model_name.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -79,7 +82,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/tag.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/tag.py index dbac885ad8e9..a3e6789078d8 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/tag.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/tag.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -105,7 +108,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/user.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/user.py index b70d84a6b40e..7ae2898f6c5a 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/models/user.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/models/user.py @@ -10,7 +10,10 @@ """ -import inspect +try: + from inspect import getfullargspec +except ImportError: + from inspect import getargspec as getfullargspec import pprint import re # noqa: F401 import six @@ -263,7 +266,7 @@ def to_dict(self, serialize=False): def convert(x): if hasattr(x, "to_dict"): - args = inspect.getargspec(x.to_dict).args + args = getfullargspec(x.to_dict).args if len(args) == 1: return x.to_dict() else: diff --git a/samples/openapi3/client/petstore/python-legacy/pom.xml b/samples/openapi3/client/petstore/python-legacy/pom.xml index 98955483eb8f..3a9cf7273065 100755 --- a/samples/openapi3/client/petstore/python-legacy/pom.xml +++ b/samples/openapi3/client/petstore/python-legacy/pom.xml @@ -1,7 +1,7 @@ 4.0.0 org.openapitools - PythonOAS3PetstoreTests + PythonLegacyOAS3PetstoreTests pom 1.0-SNAPSHOT Python OpenAPI3 Petstore Client diff --git a/samples/openapi3/client/petstore/python/.openapi-generator/FILES b/samples/openapi3/client/petstore/python/.openapi-generator/FILES index 6a324e4e94a0..bf96206001f5 100644 --- a/samples/openapi3/client/petstore/python/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python/.openapi-generator/FILES @@ -28,6 +28,7 @@ docs/ClassModel.md docs/Client.md docs/ComplexQuadrilateral.md docs/ComposedOneOfNumberWithValidations.md +docs/ComposedSchemaWithPropsAndNoAddProps.md docs/DanishPig.md docs/DefaultApi.md docs/Dog.md @@ -39,7 +40,7 @@ docs/EnumTest.md docs/EquilateralTriangle.md docs/FakeApi.md docs/FakeClassnameTags123Api.md -docs/FakeGetInlineAdditionalPropertiesPayloadArrayData.md +docs/FakePostInlineAdditionalPropertiesPayloadArrayData.md docs/File.md docs/FileSchemaTestClass.md docs/Foo.md @@ -63,6 +64,7 @@ docs/MapTest.md docs/MixedPropertiesAndAdditionalPropertiesClass.md docs/Model200Response.md docs/ModelReturn.md +docs/Mole.md docs/Name.md docs/NullableClass.md docs/NullableShape.md @@ -79,6 +81,7 @@ docs/Pig.md docs/Quadrilateral.md docs/QuadrilateralInterface.md docs/ReadOnlyFirst.md +docs/Readonly.md docs/ScaleneTriangle.md docs/Shape.md docs/ShapeInterface.md @@ -138,6 +141,7 @@ petstore_api/model/class_model.py petstore_api/model/client.py petstore_api/model/complex_quadrilateral.py petstore_api/model/composed_one_of_number_with_validations.py +petstore_api/model/composed_schema_with_props_and_no_add_props.py petstore_api/model/danish_pig.py petstore_api/model/dog.py petstore_api/model/dog_all_of.py @@ -146,7 +150,7 @@ petstore_api/model/enum_arrays.py petstore_api/model/enum_class.py petstore_api/model/enum_test.py petstore_api/model/equilateral_triangle.py -petstore_api/model/fake_get_inline_additional_properties_payload_array_data.py +petstore_api/model/fake_post_inline_additional_properties_payload_array_data.py petstore_api/model/file.py petstore_api/model/file_schema_test_class.py petstore_api/model/foo.py @@ -170,6 +174,7 @@ petstore_api/model/map_test.py petstore_api/model/mixed_properties_and_additional_properties_class.py petstore_api/model/model200_response.py petstore_api/model/model_return.py +petstore_api/model/mole.py petstore_api/model/name.py petstore_api/model/nullable_class.py petstore_api/model/nullable_shape.py @@ -185,6 +190,7 @@ petstore_api/model/pig.py petstore_api/model/quadrilateral.py petstore_api/model/quadrilateral_interface.py petstore_api/model/read_only_first.py +petstore_api/model/readonly.py petstore_api/model/scalene_triangle.py petstore_api/model/shape.py petstore_api/model/shape_interface.py diff --git a/samples/openapi3/client/petstore/python/.openapi-generator/VERSION b/samples/openapi3/client/petstore/python/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/petstore/python/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/python/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/README.md b/samples/openapi3/client/petstore/python/README.md index afe16c9ab23c..beb64bb7e04e 100644 --- a/samples/openapi3/client/petstore/python/README.md +++ b/samples/openapi3/client/petstore/python/README.md @@ -91,11 +91,11 @@ Class | Method | HTTP request | Description *FakeApi* | [**download_attachment**](docs/FakeApi.md#download_attachment) | **GET** /{fileName} | downloads a file using Content-Disposition *FakeApi* | [**enum_test**](docs/FakeApi.md#enum_test) | **POST** /fake/refs/enum-test | Object contains enum properties and array properties containing enums *FakeApi* | [**fake_health_get**](docs/FakeApi.md#fake_health_get) | **GET** /fake/health | Health check endpoint -*FakeApi* | [**get_inline_additional_properties_payload**](docs/FakeApi.md#get_inline_additional_properties_payload) | **GET** /fake/getInlineAdditionalPropertiesPayload | -*FakeApi* | [**get_inline_additional_properties_ref_payload**](docs/FakeApi.md#get_inline_additional_properties_ref_payload) | **GET** /fake/getInlineAdditionalPropertiesRefPayload | *FakeApi* | [**mammal**](docs/FakeApi.md#mammal) | **POST** /fake/refs/mammal | *FakeApi* | [**number_with_validations**](docs/FakeApi.md#number_with_validations) | **POST** /fake/refs/number | *FakeApi* | [**object_model_with_ref_props**](docs/FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | +*FakeApi* | [**post_inline_additional_properties_payload**](docs/FakeApi.md#post_inline_additional_properties_payload) | **POST** /fake/postInlineAdditionalPropertiesPayload | +*FakeApi* | [**post_inline_additional_properties_ref_payload**](docs/FakeApi.md#post_inline_additional_properties_ref_payload) | **POST** /fake/postInlineAdditionalPropertiesRefPayload | *FakeApi* | [**string**](docs/FakeApi.md#string) | **POST** /fake/refs/string | *FakeApi* | [**string_enum**](docs/FakeApi.md#string_enum) | **POST** /fake/refs/enum | *FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | @@ -159,6 +159,7 @@ Class | Method | HTTP request | Description - [Client](docs/Client.md) - [ComplexQuadrilateral](docs/ComplexQuadrilateral.md) - [ComposedOneOfNumberWithValidations](docs/ComposedOneOfNumberWithValidations.md) + - [ComposedSchemaWithPropsAndNoAddProps](docs/ComposedSchemaWithPropsAndNoAddProps.md) - [DanishPig](docs/DanishPig.md) - [Dog](docs/Dog.md) - [DogAllOf](docs/DogAllOf.md) @@ -167,7 +168,7 @@ Class | Method | HTTP request | Description - [EnumClass](docs/EnumClass.md) - [EnumTest](docs/EnumTest.md) - [EquilateralTriangle](docs/EquilateralTriangle.md) - - [FakeGetInlineAdditionalPropertiesPayloadArrayData](docs/FakeGetInlineAdditionalPropertiesPayloadArrayData.md) + - [FakePostInlineAdditionalPropertiesPayloadArrayData](docs/FakePostInlineAdditionalPropertiesPayloadArrayData.md) - [File](docs/File.md) - [FileSchemaTestClass](docs/FileSchemaTestClass.md) - [Foo](docs/Foo.md) @@ -191,6 +192,7 @@ Class | Method | HTTP request | Description - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Model200Response](docs/Model200Response.md) - [ModelReturn](docs/ModelReturn.md) + - [Mole](docs/Mole.md) - [Name](docs/Name.md) - [NullableClass](docs/NullableClass.md) - [NullableShape](docs/NullableShape.md) @@ -206,6 +208,7 @@ Class | Method | HTTP request | Description - [Quadrilateral](docs/Quadrilateral.md) - [QuadrilateralInterface](docs/QuadrilateralInterface.md) - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Readonly](docs/Readonly.md) - [ScaleneTriangle](docs/ScaleneTriangle.md) - [Shape](docs/Shape.md) - [ShapeInterface](docs/ShapeInterface.md) diff --git a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesClass.md index 460813c12231..b8d54e3c9bf1 100644 --- a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesClass.md @@ -10,8 +10,9 @@ Name | Type | Description | Notes **map_with_undeclared_properties_anytype_1** | **{str: (bool, date, datetime, dict, float, int, list, str, none_type)}** | | [optional] **map_with_undeclared_properties_anytype_2** | **{str: (bool, date, datetime, dict, float, int, list, str, none_type)}** | | [optional] **map_with_undeclared_properties_anytype_3** | **{str: (bool, date, datetime, dict, float, int, list, str, none_type)}** | | [optional] -**empty_map** | **bool, date, datetime, dict, float, int, list, str** | an object with no declared properties and no undeclared properties, hence it's an empty map. | [optional] +**empty_map** | **dict** | an object with no declared properties and no undeclared properties, hence it's an empty map. | [optional] **map_with_undeclared_properties_string** | **{str: (str,)}** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithArrayOfEnums.md b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithArrayOfEnums.md index 49ca7b3d7540..5cdb2f4c9221 100644 --- a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithArrayOfEnums.md +++ b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithArrayOfEnums.md @@ -4,7 +4,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**any string name** | **[EnumClass]** | any string name can be used but the value must be the correct type | [optional] +**any string name** | [**[EnumClass]**](EnumClass.md) | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Animal.md b/samples/openapi3/client/petstore/python/docs/Animal.md index 1d1c77c01abc..d36c66a5d882 100644 --- a/samples/openapi3/client/petstore/python/docs/Animal.md +++ b/samples/openapi3/client/petstore/python/docs/Animal.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **str** | | **color** | **str** | | [optional] if omitted the server will use the default value of "red" +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/AnimalFarm.md b/samples/openapi3/client/petstore/python/docs/AnimalFarm.md index fc299cf27d34..fb3b33c9c9c2 100644 --- a/samples/openapi3/client/petstore/python/docs/AnimalFarm.md +++ b/samples/openapi3/client/petstore/python/docs/AnimalFarm.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **value** | [**[Animal]**](Animal.md) | | +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ApiResponse.md b/samples/openapi3/client/petstore/python/docs/ApiResponse.md index 81a7d0d85227..bedefea9a9cb 100644 --- a/samples/openapi3/client/petstore/python/docs/ApiResponse.md +++ b/samples/openapi3/client/petstore/python/docs/ApiResponse.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **code** | **int** | | [optional] **type** | **str** | | [optional] **message** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Apple.md b/samples/openapi3/client/petstore/python/docs/Apple.md index d8ba5ec0711b..d7634278906b 100644 --- a/samples/openapi3/client/petstore/python/docs/Apple.md +++ b/samples/openapi3/client/petstore/python/docs/Apple.md @@ -4,8 +4,9 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**cultivar** | **str** | | [optional] +**cultivar** | **str** | | **origin** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md index 6ab77963788b..11cd25c98ee4 100644 --- a/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **array_array_number** | **[[float]]** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ArrayOfEnums.md b/samples/openapi3/client/petstore/python/docs/ArrayOfEnums.md index d2f8ea80a3d9..f1593c10afd0 100644 --- a/samples/openapi3/client/petstore/python/docs/ArrayOfEnums.md +++ b/samples/openapi3/client/petstore/python/docs/ArrayOfEnums.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **value** | [**[StringEnum]**](StringEnum.md) | | +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python/docs/ArrayOfNumberOnly.md index ebc65a54ba7e..1e9bb12e4e8b 100644 --- a/samples/openapi3/client/petstore/python/docs/ArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/python/docs/ArrayOfNumberOnly.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **array_number** | **[float]** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ArrayTest.md b/samples/openapi3/client/petstore/python/docs/ArrayTest.md index 4e1bda8fc3af..9eac1f8874c4 100644 --- a/samples/openapi3/client/petstore/python/docs/ArrayTest.md +++ b/samples/openapi3/client/petstore/python/docs/ArrayTest.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **array_of_string** | **[str]** | | [optional] **array_array_of_integer** | **[[int]]** | | [optional] **array_array_of_model** | [**[[ReadOnlyFirst]]**](ReadOnlyFirst.md) | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Banana.md b/samples/openapi3/client/petstore/python/docs/Banana.md index 54e06a1de596..2e38614e0f83 100644 --- a/samples/openapi3/client/petstore/python/docs/Banana.md +++ b/samples/openapi3/client/petstore/python/docs/Banana.md @@ -4,7 +4,8 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**length_cm** | **float** | | [optional] +**length_cm** | **float** | | +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/BasquePig.md b/samples/openapi3/client/petstore/python/docs/BasquePig.md index 6c583c5bc9f5..0d92ecbe02bb 100644 --- a/samples/openapi3/client/petstore/python/docs/BasquePig.md +++ b/samples/openapi3/client/petstore/python/docs/BasquePig.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **str** | | +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Capitalization.md b/samples/openapi3/client/petstore/python/docs/Capitalization.md index 1ddeadeb3f46..df9989f8db57 100644 --- a/samples/openapi3/client/petstore/python/docs/Capitalization.md +++ b/samples/openapi3/client/petstore/python/docs/Capitalization.md @@ -10,6 +10,7 @@ Name | Type | Description | Notes **capital_snake** | **str** | | [optional] **sca_eth_flow_points** | **str** | | [optional] **att_name** | **str** | Name of the pet | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/CatAllOf.md b/samples/openapi3/client/petstore/python/docs/CatAllOf.md index 0ff7809a99ac..6fd1390a749b 100644 --- a/samples/openapi3/client/petstore/python/docs/CatAllOf.md +++ b/samples/openapi3/client/petstore/python/docs/CatAllOf.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **declawed** | **bool** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Category.md b/samples/openapi3/client/petstore/python/docs/Category.md index 940f6a45e641..7650eccafba5 100644 --- a/samples/openapi3/client/petstore/python/docs/Category.md +++ b/samples/openapi3/client/petstore/python/docs/Category.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | defaults to "default-name" **id** | **int** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ChildCatAllOf.md b/samples/openapi3/client/petstore/python/docs/ChildCatAllOf.md index c5883b9a87c8..c5b2f58f28ce 100644 --- a/samples/openapi3/client/petstore/python/docs/ChildCatAllOf.md +++ b/samples/openapi3/client/petstore/python/docs/ChildCatAllOf.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ClassModel.md b/samples/openapi3/client/petstore/python/docs/ClassModel.md index 48ed7cbf2ff0..6605a16d74a9 100644 --- a/samples/openapi3/client/petstore/python/docs/ClassModel.md +++ b/samples/openapi3/client/petstore/python/docs/ClassModel.md @@ -6,6 +6,7 @@ Model for testing model with \"_class\" property Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **_class** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Client.md b/samples/openapi3/client/petstore/python/docs/Client.md index c3986008d6c3..1b293140f348 100644 --- a/samples/openapi3/client/petstore/python/docs/Client.md +++ b/samples/openapi3/client/petstore/python/docs/Client.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **client** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ComposedSchemaWithPropsAndNoAddProps.md b/samples/openapi3/client/petstore/python/docs/ComposedSchemaWithPropsAndNoAddProps.md new file mode 100644 index 000000000000..5930b762b0c2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/ComposedSchemaWithPropsAndNoAddProps.md @@ -0,0 +1,13 @@ +# ComposedSchemaWithPropsAndNoAddProps + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**color** | **str** | | [optional] +**id** | **int** | | [optional] +**name** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/docs/DanishPig.md b/samples/openapi3/client/petstore/python/docs/DanishPig.md index dd7fe16ea4a9..4d1ebe4f68a0 100644 --- a/samples/openapi3/client/petstore/python/docs/DanishPig.md +++ b/samples/openapi3/client/petstore/python/docs/DanishPig.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **str** | | +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/DogAllOf.md b/samples/openapi3/client/petstore/python/docs/DogAllOf.md index 6382bbd80671..2907a9fd5c43 100644 --- a/samples/openapi3/client/petstore/python/docs/DogAllOf.md +++ b/samples/openapi3/client/petstore/python/docs/DogAllOf.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **breed** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Drawing.md b/samples/openapi3/client/petstore/python/docs/Drawing.md index 0f0390a3f720..a4fc4830562f 100644 --- a/samples/openapi3/client/petstore/python/docs/Drawing.md +++ b/samples/openapi3/client/petstore/python/docs/Drawing.md @@ -8,7 +8,7 @@ Name | Type | Description | Notes **shape_or_null** | [**ShapeOrNull**](ShapeOrNull.md) | | [optional] **nullable_shape** | [**NullableShape**](NullableShape.md) | | [optional] **shapes** | [**[Shape]**](Shape.md) | | [optional] -**any string name** | **Fruit** | any string name can be used but the value must be the correct type | [optional] +**any string name** | [**Fruit**](Fruit.md) | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/EnumArrays.md b/samples/openapi3/client/petstore/python/docs/EnumArrays.md index 9be5c645a809..ad4e9d2fcb7c 100644 --- a/samples/openapi3/client/petstore/python/docs/EnumArrays.md +++ b/samples/openapi3/client/petstore/python/docs/EnumArrays.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **just_symbol** | **str** | | [optional] **array_enum** | **[str]** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/EnumClass.md b/samples/openapi3/client/petstore/python/docs/EnumClass.md index a1f9aae58190..39bb0e1644c5 100644 --- a/samples/openapi3/client/petstore/python/docs/EnumClass.md +++ b/samples/openapi3/client/petstore/python/docs/EnumClass.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **value** | **str** | | defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/EnumTest.md b/samples/openapi3/client/petstore/python/docs/EnumTest.md index b9181858434c..27b6997e695d 100644 --- a/samples/openapi3/client/petstore/python/docs/EnumTest.md +++ b/samples/openapi3/client/petstore/python/docs/EnumTest.md @@ -15,6 +15,7 @@ Name | Type | Description | Notes **integer_enum_one_value** | [**IntegerEnumOneValue**](IntegerEnumOneValue.md) | | [optional] **inline_array_of_str_enum** | [**[StringEnum]**](StringEnum.md) | | [optional] **array_of_str_enum** | [**ArrayOfEnums**](ArrayOfEnums.md) | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/FakeApi.md b/samples/openapi3/client/petstore/python/docs/FakeApi.md index acc41cb48998..5802b45cb399 100644 --- a/samples/openapi3/client/petstore/python/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/python/docs/FakeApi.md @@ -12,11 +12,11 @@ Method | HTTP request | Description [**download_attachment**](FakeApi.md#download_attachment) | **GET** /{fileName} | downloads a file using Content-Disposition [**enum_test**](FakeApi.md#enum_test) | **POST** /fake/refs/enum-test | Object contains enum properties and array properties containing enums [**fake_health_get**](FakeApi.md#fake_health_get) | **GET** /fake/health | Health check endpoint -[**get_inline_additional_properties_payload**](FakeApi.md#get_inline_additional_properties_payload) | **GET** /fake/getInlineAdditionalPropertiesPayload | -[**get_inline_additional_properties_ref_payload**](FakeApi.md#get_inline_additional_properties_ref_payload) | **GET** /fake/getInlineAdditionalPropertiesRefPayload | [**mammal**](FakeApi.md#mammal) | **POST** /fake/refs/mammal | [**number_with_validations**](FakeApi.md#number_with_validations) | **POST** /fake/refs/number | [**object_model_with_ref_props**](FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | +[**post_inline_additional_properties_payload**](FakeApi.md#post_inline_additional_properties_payload) | **POST** /fake/postInlineAdditionalPropertiesPayload | +[**post_inline_additional_properties_ref_payload**](FakeApi.md#post_inline_additional_properties_ref_payload) | **POST** /fake/postInlineAdditionalPropertiesRefPayload | [**string**](FakeApi.md#string) | **POST** /fake/refs/string | [**string_enum**](FakeApi.md#string_enum) | **POST** /fake/refs/enum | [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | @@ -564,18 +564,20 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) -# **get_inline_additional_properties_payload** -> InlineObject6 get_inline_additional_properties_payload() +# **mammal** +> Mammal mammal(mammal) +Test serialization of mammals + ### Example ```python import time import petstore_api from petstore_api.api import fake_api -from petstore_api.model.inline_object6 import InlineObject6 +from petstore_api.model.mammal import Mammal from pprint import pprint # Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 # See configuration.py for a list of all supported configuration parameters. @@ -588,23 +590,18 @@ configuration = petstore_api.Configuration( with petstore_api.ApiClient() as api_client: # Create an instance of the API class api_instance = fake_api.FakeApi(api_client) - inline_object6 = InlineObject6( - array_data=[ - FakeGetInlineAdditionalPropertiesPayloadArrayData( - labels=[ - "labels_example", - ], - ), - ], - ) # InlineObject6 | (optional) + mammal = Mammal( + has_baleen=True, + has_teeth=True, + class_name="whale", + ) # Mammal | Input mammal # example passing only required values which don't have defaults set - # and optional values try: - api_response = api_instance.get_inline_additional_properties_payload(inline_object6=inline_object6) + api_response = api_instance.mammal(mammal) pprint(api_response) except petstore_api.ApiException as e: - print("Exception when calling FakeApi->get_inline_additional_properties_payload: %s\n" % e) + print("Exception when calling FakeApi->mammal: %s\n" % e) ``` @@ -612,11 +609,11 @@ with petstore_api.ApiClient() as api_client: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **inline_object6** | [**InlineObject6**](InlineObject6.md)| | [optional] + **mammal** | [**Mammal**](Mammal.md)| Input mammal | ### Return type -[**InlineObject6**](InlineObject6.md) +[**Mammal**](Mammal.md) ### Authorization @@ -631,14 +628,16 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -**200** | InlineAdditionalPropertiesPayload | - | +**200** | Output mammal | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) -# **get_inline_additional_properties_ref_payload** -> InlineAdditionalPropertiesRefPayload get_inline_additional_properties_ref_payload() +# **number_with_validations** +> NumberWithValidations number_with_validations() + +Test serialization of outer number types ### Example @@ -646,7 +645,7 @@ No authorization required import time import petstore_api from petstore_api.api import fake_api -from petstore_api.model.inline_additional_properties_ref_payload import InlineAdditionalPropertiesRefPayload +from petstore_api.model.number_with_validations import NumberWithValidations from pprint import pprint # Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 # See configuration.py for a list of all supported configuration parameters. @@ -659,23 +658,15 @@ configuration = petstore_api.Configuration( with petstore_api.ApiClient() as api_client: # Create an instance of the API class api_instance = fake_api.FakeApi(api_client) - inline_additional_properties_ref_payload = InlineAdditionalPropertiesRefPayload( - array_data=[ - FakeGetInlineAdditionalPropertiesPayloadArrayData( - labels=[ - "labels_example", - ], - ), - ], - ) # InlineAdditionalPropertiesRefPayload | (optional) + body = NumberWithValidations(10) # NumberWithValidations | Input number as post body (optional) # example passing only required values which don't have defaults set # and optional values try: - api_response = api_instance.get_inline_additional_properties_ref_payload(inline_additional_properties_ref_payload=inline_additional_properties_ref_payload) + api_response = api_instance.number_with_validations(body=body) pprint(api_response) except petstore_api.ApiException as e: - print("Exception when calling FakeApi->get_inline_additional_properties_ref_payload: %s\n" % e) + print("Exception when calling FakeApi->number_with_validations: %s\n" % e) ``` @@ -683,11 +674,11 @@ with petstore_api.ApiClient() as api_client: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **inline_additional_properties_ref_payload** | [**InlineAdditionalPropertiesRefPayload**](InlineAdditionalPropertiesRefPayload.md)| | [optional] + **body** | [**NumberWithValidations**](NumberWithValidations.md)| Input number as post body | [optional] ### Return type -[**InlineAdditionalPropertiesRefPayload**](InlineAdditionalPropertiesRefPayload.md) +[**NumberWithValidations**](NumberWithValidations.md) ### Authorization @@ -702,16 +693,16 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -**200** | InlineAdditionalPropertiesRefPayload | - | +**200** | Output number | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) -# **mammal** -> Mammal mammal(mammal) +# **object_model_with_ref_props** +> ObjectModelWithRefProps object_model_with_ref_props() -Test serialization of mammals +Test serialization of object with $refed properties ### Example @@ -719,7 +710,7 @@ Test serialization of mammals import time import petstore_api from petstore_api.api import fake_api -from petstore_api.model.mammal import Mammal +from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps from pprint import pprint # Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 # See configuration.py for a list of all supported configuration parameters. @@ -732,18 +723,19 @@ configuration = petstore_api.Configuration( with petstore_api.ApiClient() as api_client: # Create an instance of the API class api_instance = fake_api.FakeApi(api_client) - mammal = Mammal( - has_baleen=True, - has_teeth=True, - class_name="whale", - ) # Mammal | Input mammal + body = ObjectModelWithRefProps( + my_number=NumberWithValidations(10), + my_string="my_string_example", + my_boolean=True, + ) # ObjectModelWithRefProps | Input model (optional) # example passing only required values which don't have defaults set + # and optional values try: - api_response = api_instance.mammal(mammal) + api_response = api_instance.object_model_with_ref_props(body=body) pprint(api_response) except petstore_api.ApiException as e: - print("Exception when calling FakeApi->mammal: %s\n" % e) + print("Exception when calling FakeApi->object_model_with_ref_props: %s\n" % e) ``` @@ -751,11 +743,11 @@ with petstore_api.ApiClient() as api_client: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **mammal** | [**Mammal**](Mammal.md)| Input mammal | + **body** | [**ObjectModelWithRefProps**](ObjectModelWithRefProps.md)| Input model | [optional] ### Return type -[**Mammal**](Mammal.md) +[**ObjectModelWithRefProps**](ObjectModelWithRefProps.md) ### Authorization @@ -770,24 +762,22 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -**200** | Output mammal | - | +**200** | Output model | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) -# **number_with_validations** -> NumberWithValidations number_with_validations() +# **post_inline_additional_properties_payload** +> InlineObject6 post_inline_additional_properties_payload() -Test serialization of outer number types - ### Example ```python import time import petstore_api from petstore_api.api import fake_api -from petstore_api.model.number_with_validations import NumberWithValidations +from petstore_api.model.inline_object6 import InlineObject6 from pprint import pprint # Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 # See configuration.py for a list of all supported configuration parameters. @@ -800,15 +790,23 @@ configuration = petstore_api.Configuration( with petstore_api.ApiClient() as api_client: # Create an instance of the API class api_instance = fake_api.FakeApi(api_client) - body = NumberWithValidations(10) # NumberWithValidations | Input number as post body (optional) + inline_object6 = InlineObject6( + array_data=[ + FakePostInlineAdditionalPropertiesPayloadArrayData( + labels=[ + "labels_example", + ], + ), + ], + ) # InlineObject6 | (optional) # example passing only required values which don't have defaults set # and optional values try: - api_response = api_instance.number_with_validations(body=body) + api_response = api_instance.post_inline_additional_properties_payload(inline_object6=inline_object6) pprint(api_response) except petstore_api.ApiException as e: - print("Exception when calling FakeApi->number_with_validations: %s\n" % e) + print("Exception when calling FakeApi->post_inline_additional_properties_payload: %s\n" % e) ``` @@ -816,11 +814,11 @@ with petstore_api.ApiClient() as api_client: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**NumberWithValidations**](NumberWithValidations.md)| Input number as post body | [optional] + **inline_object6** | [**InlineObject6**](InlineObject6.md)| | [optional] ### Return type -[**NumberWithValidations**](NumberWithValidations.md) +[**InlineObject6**](InlineObject6.md) ### Authorization @@ -835,16 +833,14 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -**200** | Output number | - | +**200** | InlineAdditionalPropertiesPayload | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) -# **object_model_with_ref_props** -> ObjectModelWithRefProps object_model_with_ref_props() - +# **post_inline_additional_properties_ref_payload** +> InlineAdditionalPropertiesRefPayload post_inline_additional_properties_ref_payload() -Test serialization of object with $refed properties ### Example @@ -852,7 +848,7 @@ Test serialization of object with $refed properties import time import petstore_api from petstore_api.api import fake_api -from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps +from petstore_api.model.inline_additional_properties_ref_payload import InlineAdditionalPropertiesRefPayload from pprint import pprint # Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 # See configuration.py for a list of all supported configuration parameters. @@ -865,19 +861,23 @@ configuration = petstore_api.Configuration( with petstore_api.ApiClient() as api_client: # Create an instance of the API class api_instance = fake_api.FakeApi(api_client) - body = ObjectModelWithRefProps( - my_number=NumberWithValidations(10), - my_string="my_string_example", - my_boolean=True, - ) # ObjectModelWithRefProps | Input model (optional) + inline_additional_properties_ref_payload = InlineAdditionalPropertiesRefPayload( + array_data=[ + FakePostInlineAdditionalPropertiesPayloadArrayData( + labels=[ + "labels_example", + ], + ), + ], + ) # InlineAdditionalPropertiesRefPayload | (optional) # example passing only required values which don't have defaults set # and optional values try: - api_response = api_instance.object_model_with_ref_props(body=body) + api_response = api_instance.post_inline_additional_properties_ref_payload(inline_additional_properties_ref_payload=inline_additional_properties_ref_payload) pprint(api_response) except petstore_api.ApiException as e: - print("Exception when calling FakeApi->object_model_with_ref_props: %s\n" % e) + print("Exception when calling FakeApi->post_inline_additional_properties_ref_payload: %s\n" % e) ``` @@ -885,11 +885,11 @@ with petstore_api.ApiClient() as api_client: Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**ObjectModelWithRefProps**](ObjectModelWithRefProps.md)| Input model | [optional] + **inline_additional_properties_ref_payload** | [**InlineAdditionalPropertiesRefPayload**](InlineAdditionalPropertiesRefPayload.md)| | [optional] ### Return type -[**ObjectModelWithRefProps**](ObjectModelWithRefProps.md) +[**InlineAdditionalPropertiesRefPayload**](InlineAdditionalPropertiesRefPayload.md) ### Authorization @@ -904,7 +904,7 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -**200** | Output model | - | +**200** | InlineAdditionalPropertiesRefPayload | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/FakePostInlineAdditionalPropertiesPayloadArrayData.md b/samples/openapi3/client/petstore/python/docs/FakePostInlineAdditionalPropertiesPayloadArrayData.md new file mode 100644 index 000000000000..23ec35f5dcd3 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/FakePostInlineAdditionalPropertiesPayloadArrayData.md @@ -0,0 +1,12 @@ +# FakePostInlineAdditionalPropertiesPayloadArrayData + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**labels** | **[str, none_type]** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/docs/File.md b/samples/openapi3/client/petstore/python/docs/File.md index 63b1d1a65186..f84547d19331 100644 --- a/samples/openapi3/client/petstore/python/docs/File.md +++ b/samples/openapi3/client/petstore/python/docs/File.md @@ -6,6 +6,7 @@ Must be named `File` for test. Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **source_uri** | **str** | Test capitalization | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/FileSchemaTestClass.md b/samples/openapi3/client/petstore/python/docs/FileSchemaTestClass.md index caf2440821da..4572aa0905b3 100644 --- a/samples/openapi3/client/petstore/python/docs/FileSchemaTestClass.md +++ b/samples/openapi3/client/petstore/python/docs/FileSchemaTestClass.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **file** | [**File**](File.md) | | [optional] **files** | [**[File]**](File.md) | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Foo.md b/samples/openapi3/client/petstore/python/docs/Foo.md index 23fb5e1678ed..c9c54d1ee40a 100644 --- a/samples/openapi3/client/petstore/python/docs/Foo.md +++ b/samples/openapi3/client/petstore/python/docs/Foo.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **bar** | **str** | | [optional] if omitted the server will use the default value of "bar" +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/FormatTest.md b/samples/openapi3/client/petstore/python/docs/FormatTest.md index 4fcec135190f..3c8cc8697c1c 100644 --- a/samples/openapi3/client/petstore/python/docs/FormatTest.md +++ b/samples/openapi3/client/petstore/python/docs/FormatTest.md @@ -20,6 +20,7 @@ Name | Type | Description | Notes **uuid_no_example** | **str** | | [optional] **pattern_with_digits** | **str** | A string that is a 10 digit number. Can have leading zeros. | [optional] **pattern_with_digits_and_delimiter** | **str** | A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Fruit.md b/samples/openapi3/client/petstore/python/docs/Fruit.md index 92700e79e084..d65f4cb14b4f 100644 --- a/samples/openapi3/client/petstore/python/docs/Fruit.md +++ b/samples/openapi3/client/petstore/python/docs/Fruit.md @@ -1,13 +1,15 @@ # Fruit +a schema that tests oneOf and includes a schema level property ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**cultivar** | **str** | | +**length_cm** | **float** | | **color** | **str** | | [optional] -**cultivar** | **str** | | [optional] **origin** | **str** | | [optional] -**length_cm** | **float** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/FruitReq.md b/samples/openapi3/client/petstore/python/docs/FruitReq.md index 7ff54d6ae022..096dde573091 100644 --- a/samples/openapi3/client/petstore/python/docs/FruitReq.md +++ b/samples/openapi3/client/petstore/python/docs/FruitReq.md @@ -1,5 +1,6 @@ # FruitReq +a schema where additionalProperties is on in the composed schema and off in the oneOf object schemas also, this schem accepts null as a value ## Properties Name | Type | Description | Notes @@ -8,6 +9,7 @@ Name | Type | Description | Notes **sweet** | **bool** | | [optional] **cultivar** | **str** | | [optional] **length_cm** | **float** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/GmFruit.md b/samples/openapi3/client/petstore/python/docs/GmFruit.md index f2af2abe5cef..4da4dd53ad44 100644 --- a/samples/openapi3/client/petstore/python/docs/GmFruit.md +++ b/samples/openapi3/client/petstore/python/docs/GmFruit.md @@ -4,10 +4,11 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**cultivar** | **str** | | +**length_cm** | **float** | | **color** | **str** | | [optional] -**cultivar** | **str** | | [optional] **origin** | **str** | | [optional] -**length_cm** | **float** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/GrandparentAnimal.md b/samples/openapi3/client/petstore/python/docs/GrandparentAnimal.md index 15db0708bb1a..a1c340378106 100644 --- a/samples/openapi3/client/petstore/python/docs/GrandparentAnimal.md +++ b/samples/openapi3/client/petstore/python/docs/GrandparentAnimal.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **pet_type** | **str** | | +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/HasOnlyReadOnly.md b/samples/openapi3/client/petstore/python/docs/HasOnlyReadOnly.md index 0e1334519a8b..88bc03d4ff5c 100644 --- a/samples/openapi3/client/petstore/python/docs/HasOnlyReadOnly.md +++ b/samples/openapi3/client/petstore/python/docs/HasOnlyReadOnly.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **bar** | **str** | | [optional] [readonly] **foo** | **str** | | [optional] [readonly] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/HealthCheckResult.md b/samples/openapi3/client/petstore/python/docs/HealthCheckResult.md index ab8b660e667f..e20455fb377a 100644 --- a/samples/openapi3/client/petstore/python/docs/HealthCheckResult.md +++ b/samples/openapi3/client/petstore/python/docs/HealthCheckResult.md @@ -6,6 +6,7 @@ Just a string to inform instance is up and running. Make it nullable in hope to Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **nullable_message** | **str, none_type** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/InlineAdditionalPropertiesRefPayload.md b/samples/openapi3/client/petstore/python/docs/InlineAdditionalPropertiesRefPayload.md index 130320d1daa0..f99ed143d3f8 100644 --- a/samples/openapi3/client/petstore/python/docs/InlineAdditionalPropertiesRefPayload.md +++ b/samples/openapi3/client/petstore/python/docs/InlineAdditionalPropertiesRefPayload.md @@ -5,7 +5,8 @@ this payload is used for verification that some model_to_dict issues are fixed ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**array_data** | [**[FakeGetInlineAdditionalPropertiesPayloadArrayData], none_type**](FakeGetInlineAdditionalPropertiesPayloadArrayData.md) | | [optional] +**array_data** | [**[FakePostInlineAdditionalPropertiesPayloadArrayData], none_type**](FakePostInlineAdditionalPropertiesPayloadArrayData.md) | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/InlineObject6.md b/samples/openapi3/client/petstore/python/docs/InlineObject6.md index 6e4975b3542a..b4a7a55a2c7f 100644 --- a/samples/openapi3/client/petstore/python/docs/InlineObject6.md +++ b/samples/openapi3/client/petstore/python/docs/InlineObject6.md @@ -5,7 +5,8 @@ this payload is used for verification that some model_to_dict issues are fixed ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**array_data** | [**[FakeGetInlineAdditionalPropertiesPayloadArrayData], none_type**](FakeGetInlineAdditionalPropertiesPayloadArrayData.md) | | [optional] +**array_data** | [**[FakePostInlineAdditionalPropertiesPayloadArrayData], none_type**](FakePostInlineAdditionalPropertiesPayloadArrayData.md) | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/InlineResponseDefault.md b/samples/openapi3/client/petstore/python/docs/InlineResponseDefault.md index f0a52bc4639c..b8823d383bac 100644 --- a/samples/openapi3/client/petstore/python/docs/InlineResponseDefault.md +++ b/samples/openapi3/client/petstore/python/docs/InlineResponseDefault.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **string** | [**Foo**](Foo.md) | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/IntegerEnum.md b/samples/openapi3/client/petstore/python/docs/IntegerEnum.md index 9567a76cc2e2..a5b38556bf8c 100644 --- a/samples/openapi3/client/petstore/python/docs/IntegerEnum.md +++ b/samples/openapi3/client/petstore/python/docs/IntegerEnum.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **value** | **int** | | must be one of [0, 1, 2, ] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/IntegerEnumOneValue.md b/samples/openapi3/client/petstore/python/docs/IntegerEnumOneValue.md index 99dcaa7a4ec3..d92f3080973d 100644 --- a/samples/openapi3/client/petstore/python/docs/IntegerEnumOneValue.md +++ b/samples/openapi3/client/petstore/python/docs/IntegerEnumOneValue.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **value** | **int** | | defaults to 0, must be one of [0, ] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/IntegerEnumWithDefaultValue.md b/samples/openapi3/client/petstore/python/docs/IntegerEnumWithDefaultValue.md index 4b8e39d9cadd..2fd432edc69d 100644 --- a/samples/openapi3/client/petstore/python/docs/IntegerEnumWithDefaultValue.md +++ b/samples/openapi3/client/petstore/python/docs/IntegerEnumWithDefaultValue.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **value** | **int** | | defaults to 0, must be one of [0, 1, 2, ] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/IsoscelesTriangle.md b/samples/openapi3/client/petstore/python/docs/IsoscelesTriangle.md index e7fffa3be03a..57cfa6d12ad1 100644 --- a/samples/openapi3/client/petstore/python/docs/IsoscelesTriangle.md +++ b/samples/openapi3/client/petstore/python/docs/IsoscelesTriangle.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **shape_type** | **str** | | **triangle_type** | **str** | | +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/List.md b/samples/openapi3/client/petstore/python/docs/List.md index 4b60956971aa..13f2694de358 100644 --- a/samples/openapi3/client/petstore/python/docs/List.md +++ b/samples/openapi3/client/petstore/python/docs/List.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **_123_list** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/MapTest.md b/samples/openapi3/client/petstore/python/docs/MapTest.md index 15228ee1f282..e6584f3811e0 100644 --- a/samples/openapi3/client/petstore/python/docs/MapTest.md +++ b/samples/openapi3/client/petstore/python/docs/MapTest.md @@ -8,6 +8,7 @@ Name | Type | Description | Notes **map_of_enum_string** | **{str: (str,)}** | | [optional] **direct_map** | **{str: (bool,)}** | | [optional] **indirect_map** | [**StringBooleanMap**](StringBooleanMap.md) | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md index f489944a20af..f32c4e04134b 100644 --- a/samples/openapi3/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **uuid** | **str** | | [optional] **date_time** | **datetime** | | [optional] **map** | [**{str: (Animal,)}**](Animal.md) | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Model200Response.md b/samples/openapi3/client/petstore/python/docs/Model200Response.md index c958bd4b33f8..f7ef7d79acf6 100644 --- a/samples/openapi3/client/petstore/python/docs/Model200Response.md +++ b/samples/openapi3/client/petstore/python/docs/Model200Response.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **int** | | [optional] **_class** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ModelReturn.md b/samples/openapi3/client/petstore/python/docs/ModelReturn.md index 043e9d466fab..75fb39a88698 100644 --- a/samples/openapi3/client/petstore/python/docs/ModelReturn.md +++ b/samples/openapi3/client/petstore/python/docs/ModelReturn.md @@ -6,6 +6,7 @@ Model for testing reserved words Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **_return** | **int** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Mole.md b/samples/openapi3/client/petstore/python/docs/Mole.md new file mode 100644 index 000000000000..6c4f714963e2 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/Mole.md @@ -0,0 +1,17 @@ +# Mole + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**blind** | **bool** | | [readonly] +**smell** | **str** | | +**hearing** | **bool** | | +**touch** | **bool** | | [optional] [readonly] +**taste** | **str** | | [optional] +**seeing_ghosts** | **bool** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/docs/Name.md b/samples/openapi3/client/petstore/python/docs/Name.md index 3be719cdbfba..6e58fae6d0bb 100644 --- a/samples/openapi3/client/petstore/python/docs/Name.md +++ b/samples/openapi3/client/petstore/python/docs/Name.md @@ -9,6 +9,7 @@ Name | Type | Description | Notes **snake_case** | **int** | | [optional] [readonly] **_property** | **str** | | [optional] **_123_number** | **int** | | [optional] [readonly] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/NullableClass.md b/samples/openapi3/client/petstore/python/docs/NullableClass.md index 863e93ddfbbc..48a27469f6c9 100644 --- a/samples/openapi3/client/petstore/python/docs/NullableClass.md +++ b/samples/openapi3/client/petstore/python/docs/NullableClass.md @@ -13,10 +13,11 @@ Name | Type | Description | Notes **array_nullable_prop** | **[{str: (bool, date, datetime, dict, float, int, list, str, none_type)}], none_type** | | [optional] **array_and_items_nullable_prop** | **[{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type], none_type** | | [optional] **array_items_nullable** | **[{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type]** | | [optional] +**object_nullable** | **{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type** | | [optional] **object_nullable_prop** | **{str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},)}, none_type** | | [optional] **object_and_items_nullable_prop** | **{str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}, none_type** | | [optional] **object_items_nullable** | **{str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}** | | [optional] -**any string name** | **{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type** | any string name can be used but the value must be the correct type | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/NumberOnly.md b/samples/openapi3/client/petstore/python/docs/NumberOnly.md index 37195c5d8994..172e86163a44 100644 --- a/samples/openapi3/client/petstore/python/docs/NumberOnly.md +++ b/samples/openapi3/client/petstore/python/docs/NumberOnly.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **just_number** | **float** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/NumberWithValidations.md b/samples/openapi3/client/petstore/python/docs/NumberWithValidations.md index 119e0f678239..cc6f77c152c6 100644 --- a/samples/openapi3/client/petstore/python/docs/NumberWithValidations.md +++ b/samples/openapi3/client/petstore/python/docs/NumberWithValidations.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **value** | **float** | | +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ObjectModelWithRefProps.md b/samples/openapi3/client/petstore/python/docs/ObjectModelWithRefProps.md index 5ff4e52033d6..60fe997afa05 100644 --- a/samples/openapi3/client/petstore/python/docs/ObjectModelWithRefProps.md +++ b/samples/openapi3/client/petstore/python/docs/ObjectModelWithRefProps.md @@ -6,8 +6,10 @@ a model that includes properties which should stay primitive (String + Boolean) Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **my_number** | [**NumberWithValidations**](NumberWithValidations.md) | | [optional] +**my_readonly** | [**Readonly**](Readonly.md) | | [optional] **my_string** | **str** | | [optional] **my_boolean** | **bool** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Order.md b/samples/openapi3/client/petstore/python/docs/Order.md index d29e1a381de8..0423082932d5 100644 --- a/samples/openapi3/client/petstore/python/docs/Order.md +++ b/samples/openapi3/client/petstore/python/docs/Order.md @@ -10,6 +10,7 @@ Name | Type | Description | Notes **ship_date** | **datetime** | | [optional] **status** | **str** | Order Status | [optional] **complete** | **bool** | | [optional] if omitted the server will use the default value of False +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Pet.md b/samples/openapi3/client/petstore/python/docs/Pet.md index ea4abdeb13d3..bb6e8d344e64 100644 --- a/samples/openapi3/client/petstore/python/docs/Pet.md +++ b/samples/openapi3/client/petstore/python/docs/Pet.md @@ -11,6 +11,7 @@ Name | Type | Description | Notes **category** | [**Category**](Category.md) | | [optional] **tags** | [**[Tag]**](Tag.md) | | [optional] **status** | **str** | pet status in the store | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/QuadrilateralInterface.md b/samples/openapi3/client/petstore/python/docs/QuadrilateralInterface.md index 3b9c39d22306..05573544bd79 100644 --- a/samples/openapi3/client/petstore/python/docs/QuadrilateralInterface.md +++ b/samples/openapi3/client/petstore/python/docs/QuadrilateralInterface.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **quadrilateral_type** | **str** | | +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ReadOnlyFirst.md b/samples/openapi3/client/petstore/python/docs/ReadOnlyFirst.md index 53b4c61d8445..ba39ec3d04e4 100644 --- a/samples/openapi3/client/petstore/python/docs/ReadOnlyFirst.md +++ b/samples/openapi3/client/petstore/python/docs/ReadOnlyFirst.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **bar** | **str** | | [optional] [readonly] **baz** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Readonly.md b/samples/openapi3/client/petstore/python/docs/Readonly.md new file mode 100644 index 000000000000..e94598c9d388 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/Readonly.md @@ -0,0 +1,12 @@ +# Readonly + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/docs/ShapeInterface.md b/samples/openapi3/client/petstore/python/docs/ShapeInterface.md index 4d094158faba..012d4a0cdd86 100644 --- a/samples/openapi3/client/petstore/python/docs/ShapeInterface.md +++ b/samples/openapi3/client/petstore/python/docs/ShapeInterface.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **shape_type** | **str** | | +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/SomeObjectWithSelfAttr.md b/samples/openapi3/client/petstore/python/docs/SomeObjectWithSelfAttr.md index ee0aeb17ce1a..6704f480eb3b 100644 --- a/samples/openapi3/client/petstore/python/docs/SomeObjectWithSelfAttr.md +++ b/samples/openapi3/client/petstore/python/docs/SomeObjectWithSelfAttr.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **_self** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/SpecialModelName.md b/samples/openapi3/client/petstore/python/docs/SpecialModelName.md index 268e1134192d..4a1c86ff4de0 100644 --- a/samples/openapi3/client/petstore/python/docs/SpecialModelName.md +++ b/samples/openapi3/client/petstore/python/docs/SpecialModelName.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **special_property_name** | **int** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/StringEnum.md b/samples/openapi3/client/petstore/python/docs/StringEnum.md index b03f3b1e6c64..29e160a9b07e 100644 --- a/samples/openapi3/client/petstore/python/docs/StringEnum.md +++ b/samples/openapi3/client/petstore/python/docs/StringEnum.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **value** | **str** | | must be one of ["placed", "approved", "delivered", "single quoted", '''multiple lines''', '''double quote with newline''', ] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/StringEnumWithDefaultValue.md b/samples/openapi3/client/petstore/python/docs/StringEnumWithDefaultValue.md index 7799b93d8223..700a2caf3b84 100644 --- a/samples/openapi3/client/petstore/python/docs/StringEnumWithDefaultValue.md +++ b/samples/openapi3/client/petstore/python/docs/StringEnumWithDefaultValue.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **value** | **str** | | defaults to "placed", must be one of ["placed", "approved", "delivered", ] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Tag.md b/samples/openapi3/client/petstore/python/docs/Tag.md index 4ccac4949afc..8a95090c036d 100644 --- a/samples/openapi3/client/petstore/python/docs/Tag.md +++ b/samples/openapi3/client/petstore/python/docs/Tag.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] **name** | **str** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/TriangleInterface.md b/samples/openapi3/client/petstore/python/docs/TriangleInterface.md index 494c224cd313..9f8411eabdf2 100644 --- a/samples/openapi3/client/petstore/python/docs/TriangleInterface.md +++ b/samples/openapi3/client/petstore/python/docs/TriangleInterface.md @@ -5,6 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **triangle_type** | **str** | | +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/User.md b/samples/openapi3/client/petstore/python/docs/User.md index a4cb117e63a9..4d2da357adb1 100644 --- a/samples/openapi3/client/petstore/python/docs/User.md +++ b/samples/openapi3/client/petstore/python/docs/User.md @@ -16,6 +16,7 @@ Name | Type | Description | Notes **object_with_no_declared_props_nullable** | **{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] **any_type_prop** | **bool, date, datetime, dict, float, int, list, str, none_type** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] **any_type_prop_nullable** | **bool, date, datetime, dict, float, int, list, str, none_type** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Whale.md b/samples/openapi3/client/petstore/python/docs/Whale.md index ea48bff6bc39..500786012ead 100644 --- a/samples/openapi3/client/petstore/python/docs/Whale.md +++ b/samples/openapi3/client/petstore/python/docs/Whale.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **class_name** | **str** | | **has_baleen** | **bool** | | [optional] **has_teeth** | **bool** | | [optional] +**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py index 5f98e228c3be..7dea3785aecd 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py @@ -945,21 +945,24 @@ def __fake_health_get( callable=__fake_health_get ) - def __get_inline_additional_properties_payload( + def __mammal( self, + mammal, **kwargs ): - """get_inline_additional_properties_payload # noqa: E501 + """mammal # noqa: E501 + Test serialization of mammals # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True - >>> thread = api.get_inline_additional_properties_payload(async_req=True) + >>> thread = api.mammal(mammal, async_req=True) >>> result = thread.get() + Args: + mammal (Mammal): Input mammal Keyword Args: - inline_object6 (InlineObject6): [optional] _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object @@ -981,7 +984,7 @@ def __get_inline_additional_properties_payload( async_req (bool): execute request asynchronously Returns: - InlineObject6 + Mammal If the method is called asynchronously, returns the request thread. """ @@ -1004,22 +1007,26 @@ def __get_inline_additional_properties_payload( '_check_return_type', True ) kwargs['_host_index'] = kwargs.get('_host_index') + kwargs['mammal'] = \ + mammal return self.call_with_http_info(**kwargs) - self.get_inline_additional_properties_payload = _Endpoint( + self.mammal = _Endpoint( settings={ - 'response_type': (InlineObject6,), + 'response_type': (Mammal,), 'auth': [], - 'endpoint_path': '/fake/getInlineAdditionalPropertiesPayload', - 'operation_id': 'get_inline_additional_properties_payload', - 'http_method': 'GET', + 'endpoint_path': '/fake/refs/mammal', + 'operation_id': 'mammal', + 'http_method': 'POST', 'servers': None, }, params_map={ 'all': [ - 'inline_object6', + 'mammal', + ], + 'required': [ + 'mammal', ], - 'required': [], 'nullable': [ ], 'enum': [ @@ -1033,13 +1040,13 @@ def __get_inline_additional_properties_payload( 'allowed_values': { }, 'openapi_types': { - 'inline_object6': - (InlineObject6,), + 'mammal': + (Mammal,), }, 'attribute_map': { }, 'location_map': { - 'inline_object6': 'body', + 'mammal': 'body', }, 'collection_format_map': { } @@ -1053,24 +1060,25 @@ def __get_inline_additional_properties_payload( ] }, api_client=api_client, - callable=__get_inline_additional_properties_payload + callable=__mammal ) - def __get_inline_additional_properties_ref_payload( + def __number_with_validations( self, **kwargs ): - """get_inline_additional_properties_ref_payload # noqa: E501 + """number_with_validations # noqa: E501 + Test serialization of outer number types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True - >>> thread = api.get_inline_additional_properties_ref_payload(async_req=True) + >>> thread = api.number_with_validations(async_req=True) >>> result = thread.get() Keyword Args: - inline_additional_properties_ref_payload (InlineAdditionalPropertiesRefPayload): [optional] + body (NumberWithValidations): Input number as post body. [optional] _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object @@ -1092,7 +1100,7 @@ def __get_inline_additional_properties_ref_payload( async_req (bool): execute request asynchronously Returns: - InlineAdditionalPropertiesRefPayload + NumberWithValidations If the method is called asynchronously, returns the request thread. """ @@ -1117,18 +1125,18 @@ def __get_inline_additional_properties_ref_payload( kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) - self.get_inline_additional_properties_ref_payload = _Endpoint( + self.number_with_validations = _Endpoint( settings={ - 'response_type': (InlineAdditionalPropertiesRefPayload,), + 'response_type': (NumberWithValidations,), 'auth': [], - 'endpoint_path': '/fake/getInlineAdditionalPropertiesRefPayload', - 'operation_id': 'get_inline_additional_properties_ref_payload', - 'http_method': 'GET', + 'endpoint_path': '/fake/refs/number', + 'operation_id': 'number_with_validations', + 'http_method': 'POST', 'servers': None, }, params_map={ 'all': [ - 'inline_additional_properties_ref_payload', + 'body', ], 'required': [], 'nullable': [ @@ -1144,13 +1152,13 @@ def __get_inline_additional_properties_ref_payload( 'allowed_values': { }, 'openapi_types': { - 'inline_additional_properties_ref_payload': - (InlineAdditionalPropertiesRefPayload,), + 'body': + (NumberWithValidations,), }, 'attribute_map': { }, 'location_map': { - 'inline_additional_properties_ref_payload': 'body', + 'body': 'body', }, 'collection_format_map': { } @@ -1164,27 +1172,25 @@ def __get_inline_additional_properties_ref_payload( ] }, api_client=api_client, - callable=__get_inline_additional_properties_ref_payload + callable=__number_with_validations ) - def __mammal( + def __object_model_with_ref_props( self, - mammal, **kwargs ): - """mammal # noqa: E501 + """object_model_with_ref_props # noqa: E501 - Test serialization of mammals # noqa: E501 + Test serialization of object with $refed properties # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True - >>> thread = api.mammal(mammal, async_req=True) + >>> thread = api.object_model_with_ref_props(async_req=True) >>> result = thread.get() - Args: - mammal (Mammal): Input mammal Keyword Args: + body (ObjectModelWithRefProps): Input model. [optional] _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object @@ -1206,7 +1212,7 @@ def __mammal( async_req (bool): execute request asynchronously Returns: - Mammal + ObjectModelWithRefProps If the method is called asynchronously, returns the request thread. """ @@ -1229,26 +1235,22 @@ def __mammal( '_check_return_type', True ) kwargs['_host_index'] = kwargs.get('_host_index') - kwargs['mammal'] = \ - mammal return self.call_with_http_info(**kwargs) - self.mammal = _Endpoint( + self.object_model_with_ref_props = _Endpoint( settings={ - 'response_type': (Mammal,), + 'response_type': (ObjectModelWithRefProps,), 'auth': [], - 'endpoint_path': '/fake/refs/mammal', - 'operation_id': 'mammal', + 'endpoint_path': '/fake/refs/object_model_with_ref_props', + 'operation_id': 'object_model_with_ref_props', 'http_method': 'POST', 'servers': None, }, params_map={ 'all': [ - 'mammal', - ], - 'required': [ - 'mammal', + 'body', ], + 'required': [], 'nullable': [ ], 'enum': [ @@ -1262,13 +1264,13 @@ def __mammal( 'allowed_values': { }, 'openapi_types': { - 'mammal': - (Mammal,), + 'body': + (ObjectModelWithRefProps,), }, 'attribute_map': { }, 'location_map': { - 'mammal': 'body', + 'body': 'body', }, 'collection_format_map': { } @@ -1282,25 +1284,24 @@ def __mammal( ] }, api_client=api_client, - callable=__mammal + callable=__object_model_with_ref_props ) - def __number_with_validations( + def __post_inline_additional_properties_payload( self, **kwargs ): - """number_with_validations # noqa: E501 + """post_inline_additional_properties_payload # noqa: E501 - Test serialization of outer number types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True - >>> thread = api.number_with_validations(async_req=True) + >>> thread = api.post_inline_additional_properties_payload(async_req=True) >>> result = thread.get() Keyword Args: - body (NumberWithValidations): Input number as post body. [optional] + inline_object6 (InlineObject6): [optional] _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object @@ -1322,7 +1323,7 @@ def __number_with_validations( async_req (bool): execute request asynchronously Returns: - NumberWithValidations + InlineObject6 If the method is called asynchronously, returns the request thread. """ @@ -1347,18 +1348,18 @@ def __number_with_validations( kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) - self.number_with_validations = _Endpoint( + self.post_inline_additional_properties_payload = _Endpoint( settings={ - 'response_type': (NumberWithValidations,), + 'response_type': (InlineObject6,), 'auth': [], - 'endpoint_path': '/fake/refs/number', - 'operation_id': 'number_with_validations', + 'endpoint_path': '/fake/postInlineAdditionalPropertiesPayload', + 'operation_id': 'post_inline_additional_properties_payload', 'http_method': 'POST', 'servers': None, }, params_map={ 'all': [ - 'body', + 'inline_object6', ], 'required': [], 'nullable': [ @@ -1374,13 +1375,13 @@ def __number_with_validations( 'allowed_values': { }, 'openapi_types': { - 'body': - (NumberWithValidations,), + 'inline_object6': + (InlineObject6,), }, 'attribute_map': { }, 'location_map': { - 'body': 'body', + 'inline_object6': 'body', }, 'collection_format_map': { } @@ -1394,25 +1395,24 @@ def __number_with_validations( ] }, api_client=api_client, - callable=__number_with_validations + callable=__post_inline_additional_properties_payload ) - def __object_model_with_ref_props( + def __post_inline_additional_properties_ref_payload( self, **kwargs ): - """object_model_with_ref_props # noqa: E501 + """post_inline_additional_properties_ref_payload # noqa: E501 - Test serialization of object with $refed properties # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True - >>> thread = api.object_model_with_ref_props(async_req=True) + >>> thread = api.post_inline_additional_properties_ref_payload(async_req=True) >>> result = thread.get() Keyword Args: - body (ObjectModelWithRefProps): Input model. [optional] + inline_additional_properties_ref_payload (InlineAdditionalPropertiesRefPayload): [optional] _return_http_data_only (bool): response data without head status code and headers. Default is True. _preload_content (bool): if False, the urllib3.HTTPResponse object @@ -1434,7 +1434,7 @@ def __object_model_with_ref_props( async_req (bool): execute request asynchronously Returns: - ObjectModelWithRefProps + InlineAdditionalPropertiesRefPayload If the method is called asynchronously, returns the request thread. """ @@ -1459,18 +1459,18 @@ def __object_model_with_ref_props( kwargs['_host_index'] = kwargs.get('_host_index') return self.call_with_http_info(**kwargs) - self.object_model_with_ref_props = _Endpoint( + self.post_inline_additional_properties_ref_payload = _Endpoint( settings={ - 'response_type': (ObjectModelWithRefProps,), + 'response_type': (InlineAdditionalPropertiesRefPayload,), 'auth': [], - 'endpoint_path': '/fake/refs/object_model_with_ref_props', - 'operation_id': 'object_model_with_ref_props', + 'endpoint_path': '/fake/postInlineAdditionalPropertiesRefPayload', + 'operation_id': 'post_inline_additional_properties_ref_payload', 'http_method': 'POST', 'servers': None, }, params_map={ 'all': [ - 'body', + 'inline_additional_properties_ref_payload', ], 'required': [], 'nullable': [ @@ -1486,13 +1486,13 @@ def __object_model_with_ref_props( 'allowed_values': { }, 'openapi_types': { - 'body': - (ObjectModelWithRefProps,), + 'inline_additional_properties_ref_payload': + (InlineAdditionalPropertiesRefPayload,), }, 'attribute_map': { }, 'location_map': { - 'body': 'body', + 'inline_additional_properties_ref_payload': 'body', }, 'collection_format_map': { } @@ -1506,7 +1506,7 @@ def __object_model_with_ref_props( ] }, api_client=api_client, - callable=__object_model_with_ref_props + callable=__post_inline_additional_properties_ref_payload ) def __string( @@ -2239,7 +2239,7 @@ def __test_endpoint_parameters( }, ('double',): { - 'inclusive_maximum': 123.4, + 'exclusive_maximum': 123.4, 'inclusive_minimum': 67.8, }, ('pattern_without_delimiter',): { @@ -2260,7 +2260,7 @@ def __test_endpoint_parameters( }, ('float',): { - 'inclusive_maximum': 987.6, + 'exclusive_maximum': 987.6, }, ('string',): { diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.py index 3b526cd54e36..6540576f957b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AdditionalPropertiesClass(ModelNormal): @@ -57,7 +60,13 @@ class AdditionalPropertiesClass(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -78,7 +87,7 @@ def openapi_types(): 'map_with_undeclared_properties_anytype_1': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 'map_with_undeclared_properties_anytype_2': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 'map_with_undeclared_properties_anytype_3': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), # noqa: E501 - 'empty_map': (bool, date, datetime, dict, float, int, list, str,), # noqa: E501 + 'empty_map': (dict,), # noqa: E501 'map_with_undeclared_properties_string': ({str: (str,)},), # noqa: E501 } @@ -98,8 +107,92 @@ def discriminator(): 'map_with_undeclared_properties_string': 'map_with_undeclared_properties_string', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_property ({str: (str,)}): [optional] # noqa: E501 + map_of_map_property ({str: ({str: (str,)},)}): [optional] # noqa: E501 + anytype_1 (bool, date, datetime, dict, float, int, list, str, none_type): [optional] # noqa: E501 + map_with_undeclared_properties_anytype_1 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 + map_with_undeclared_properties_anytype_2 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 + map_with_undeclared_properties_anytype_3 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 + empty_map (dict): an object with no declared properties and no undeclared properties, hence it's an empty map.. [optional] # noqa: E501 + map_with_undeclared_properties_string ({str: (str,)}): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -150,7 +243,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 map_with_undeclared_properties_anytype_1 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 map_with_undeclared_properties_anytype_2 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 map_with_undeclared_properties_anytype_3 ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): [optional] # noqa: E501 - empty_map (bool, date, datetime, dict, float, int, list, str): an object with no declared properties and no undeclared properties, hence it's an empty map.. [optional] # noqa: E501 + empty_map (dict): an object with no declared properties and no undeclared properties, hence it's an empty map.. [optional] # noqa: E501 map_with_undeclared_properties_string ({str: (str,)}): [optional] # noqa: E501 """ @@ -185,3 +278,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.py b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.py index 67d43acfe532..f8e0b8529ccd 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.enum_class import EnumClass @@ -94,8 +97,84 @@ def discriminator(): attribute_map = { } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """AdditionalPropertiesWithArrayOfEnums - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -173,3 +252,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/address.py b/samples/openapi3/client/petstore/python/petstore_api/model/address.py index b1504407903d..a7c88b8fec25 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/address.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/address.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Address(ModelNormal): @@ -88,8 +91,84 @@ def discriminator(): attribute_map = { } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Address - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +246,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/animal.py b/samples/openapi3/client/petstore/python/petstore_api/model/animal.py index a3d48b6ea975..fda6c283ebdc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/animal.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/animal.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.cat import Cat @@ -63,7 +66,14 @@ class Animal(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -99,8 +109,89 @@ def discriminator(): 'color': 'color', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """Animal - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -183,3 +274,6 @@ def __init__(self, class_name, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.py b/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.py index 838b18a12970..59bde51a2907 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -57,7 +60,14 @@ class AnimalFarm(ModelSimple): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -83,6 +93,8 @@ def discriminator(): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -182,3 +194,97 @@ def __init__(self, *args, **kwargs): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """AnimalFarm - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] ([Animal]): # noqa: E501 + + Keyword Args: + value ([Animal]): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/api_response.py b/samples/openapi3/client/petstore/python/petstore_api/model/api_response.py index 01e2175b8004..d1f3b363bef5 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/api_response.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/api_response.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ApiResponse(ModelNormal): @@ -57,7 +60,13 @@ class ApiResponse(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -88,8 +97,87 @@ def discriminator(): 'message': 'message', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ApiResponse - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + code (int): [optional] # noqa: E501 + type (str): [optional] # noqa: E501 + message (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +258,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/apple.py b/samples/openapi3/client/petstore/python/petstore_api/model/apple.py index 29d34a1efe8b..b5d3d62826d8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/apple.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/apple.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Apple(ModelNormal): @@ -68,7 +71,13 @@ class Apple(ModelNormal): }, } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = True @@ -97,8 +106,89 @@ def discriminator(): 'origin': 'origin', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, cultivar, *args, **kwargs): # noqa: E501 + """Apple - a model defined in OpenAPI + + Args: + cultivar (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + origin (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.cultivar = cultivar + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -109,9 +199,12 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 + def __init__(self, cultivar, *args, **kwargs): # noqa: E501 """Apple - a model defined in OpenAPI + Args: + cultivar (str): + Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be @@ -143,7 +236,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - cultivar (str): [optional] # noqa: E501 origin (str): [optional] # noqa: E501 """ @@ -170,6 +262,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.cultivar = cultivar for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ @@ -178,3 +271,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.py b/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.py index fb161cd4c0fc..469aa6e1f6e6 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class AppleReq(ModelNormal): @@ -86,8 +89,89 @@ def discriminator(): 'mealy': 'mealy', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, cultivar, *args, **kwargs): # noqa: E501 + """AppleReq - a model defined in OpenAPI + + Args: + cultivar (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + mealy (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.cultivar = cultivar + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +254,6 @@ def __init__(self, cultivar, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py index 008b74dd42a3..16d9bda29f1f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ArrayOfArrayOfNumberOnly(ModelNormal): @@ -57,7 +60,13 @@ class ArrayOfArrayOfNumberOnly(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'array_array_number': 'ArrayArrayNumber', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayOfArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_array_number ([[float]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.py index a3dc283969ae..1a4166a6e675 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.string_enum import StringEnum @@ -57,7 +60,14 @@ class ArrayOfEnums(ModelSimple): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -83,6 +93,8 @@ def discriminator(): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -182,3 +194,97 @@ def __init__(self, *args, **kwargs): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """ArrayOfEnums - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] ([StringEnum]): # noqa: E501 + + Keyword Args: + value ([StringEnum]): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.py index f2e080bc258e..0e44ab61aff5 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ArrayOfNumberOnly(ModelNormal): @@ -57,7 +60,13 @@ class ArrayOfNumberOnly(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'array_number': 'ArrayNumber', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayOfNumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_number ([float]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_test.py index ac42b07b93c9..64c180d11bc5 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/array_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_test.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.read_only_first import ReadOnlyFirst @@ -61,7 +64,14 @@ class ArrayTest(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -93,8 +103,87 @@ def discriminator(): 'array_array_of_model': 'array_array_of_model', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ArrayTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_of_string ([str]): [optional] # noqa: E501 + array_array_of_integer ([[int]]): [optional] # noqa: E501 + array_array_of_model ([[ReadOnlyFirst]]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -175,3 +264,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/banana.py b/samples/openapi3/client/petstore/python/petstore_api/model/banana.py index 513bd6bf06b1..2e2249d2f5e1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/banana.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/banana.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Banana(ModelNormal): @@ -57,7 +60,13 @@ class Banana(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,88 @@ def discriminator(): 'length_cm': 'lengthCm', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, length_cm, *args, **kwargs): # noqa: E501 + """Banana - a model defined in OpenAPI + + Args: + length_cm (float): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.length_cm = length_cm + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -96,9 +185,12 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 + def __init__(self, length_cm, *args, **kwargs): # noqa: E501 """Banana - a model defined in OpenAPI + Args: + length_cm (float): + Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be @@ -130,7 +222,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - length_cm (float): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -156,6 +247,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.length_cm = length_cm for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ @@ -164,3 +256,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.py b/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.py index 472678bd20e0..ff367d1d550f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class BananaReq(ModelNormal): @@ -86,8 +89,89 @@ def discriminator(): 'sweet': 'sweet', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, length_cm, *args, **kwargs): # noqa: E501 + """BananaReq - a model defined in OpenAPI + + Args: + length_cm (float): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + sweet (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.length_cm = length_cm + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +254,6 @@ def __init__(self, length_cm, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.py b/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.py index 603f7761867c..bdf993909529 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class BasquePig(ModelNormal): @@ -57,7 +60,13 @@ class BasquePig(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,88 @@ def discriminator(): 'class_name': 'className', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """BasquePig - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +256,6 @@ def __init__(self, class_name, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.py b/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.py index 710c17e51a56..2f1323481dca 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Capitalization(ModelNormal): @@ -57,7 +60,13 @@ class Capitalization(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -94,8 +103,90 @@ def discriminator(): 'att_name': 'ATT_NAME', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Capitalization - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + small_camel (str): [optional] # noqa: E501 + capital_camel (str): [optional] # noqa: E501 + small_snake (str): [optional] # noqa: E501 + capital_snake (str): [optional] # noqa: E501 + sca_eth_flow_points (str): [optional] # noqa: E501 + att_name (str): Name of the pet . [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -179,3 +270,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/cat.py b/samples/openapi3/client/petstore/python/petstore_api/model/cat.py index 1d62177c6c2e..be46fe5abd8c 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/cat.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/cat.py @@ -25,12 +25,13 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): - from petstore_api.model.address import Address from petstore_api.model.animal import Animal from petstore_api.model.cat_all_of import CatAllOf - globals()['Address'] = Address globals()['Animal'] = Animal globals()['CatAllOf'] = CatAllOf @@ -107,6 +108,100 @@ def discriminator(): 'color': 'color', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Cat - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + declawed (bool): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -120,13 +215,11 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, class_name, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """Cat - a model defined in OpenAPI - Args: - class_name (str): - Keyword Args: + class_name (str): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -191,29 +284,24 @@ def __init__(self, class_name, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'class_name': class_name, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): @@ -229,7 +317,6 @@ def _composed_schemas(): 'anyOf': [ ], 'allOf': [ - Address, Animal, CatAllOf, ], diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/cat_all_of.py b/samples/openapi3/client/petstore/python/petstore_api/model/cat_all_of.py index 50b046510dfa..a5bef948f72b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/cat_all_of.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/cat_all_of.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class CatAllOf(ModelNormal): @@ -57,7 +60,13 @@ class CatAllOf(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'declawed': 'declawed', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """CatAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + declawed (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/category.py b/samples/openapi3/client/petstore/python/petstore_api/model/category.py index ed167471d356..b40329c9424d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/category.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/category.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Category(ModelNormal): @@ -57,7 +60,13 @@ class Category(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -86,8 +95,90 @@ def discriminator(): 'id': 'id', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Category - a model defined in OpenAPI + + Args: + + Keyword Args: + name (str): defaults to "default-name" # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + """ + + name = kwargs.get('name', "default-name") + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -171,3 +262,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.py b/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.py index e1869c917cd8..3644df82fc54 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_cat_all_of import ChildCatAllOf @@ -103,6 +106,99 @@ def discriminator(): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildCat - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -116,13 +212,11 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, pet_type, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """ChildCat - a model defined in OpenAPI - Args: - pet_type (str): - Keyword Args: + pet_type (str): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -186,29 +280,24 @@ def __init__(self, pet_type, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'pet_type': pet_type, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/child_cat_all_of.py b/samples/openapi3/client/petstore/python/petstore_api/model/child_cat_all_of.py index f0f1a1ae6bd4..48b725d7c3c6 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/child_cat_all_of.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/child_cat_all_of.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ChildCatAllOf(ModelNormal): @@ -57,7 +60,13 @@ class ChildCatAllOf(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ChildCatAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/class_model.py b/samples/openapi3/client/petstore/python/petstore_api/model/class_model.py index 18c16f89f908..a3f2b58f87f3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/class_model.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/class_model.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ClassModel(ModelNormal): @@ -57,7 +60,13 @@ class ClassModel(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): '_class': '_class', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ClassModel - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/client.py b/samples/openapi3/client/petstore/python/petstore_api/model/client.py index da615c547731..3dca32f7926b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/client.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/client.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Client(ModelNormal): @@ -57,7 +60,13 @@ class Client(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'client': 'client', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Client - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + client (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.py b/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.py index 56853f5f34f1..bd835d9a39a1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.quadrilateral_interface import QuadrilateralInterface @@ -100,6 +103,99 @@ def discriminator(): 'quadrilateral_type': 'quadrilateralType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ComplexQuadrilateral - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + quadrilateral_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -113,14 +209,12 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, shape_type, quadrilateral_type, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """ComplexQuadrilateral - a model defined in OpenAPI - Args: + Keyword Args: shape_type (str): quadrilateral_type (str): - - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -183,30 +277,24 @@ def __init__(self, shape_type, quadrilateral_type, *args, **kwargs): # noqa: E5 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'shape_type': shape_type, - 'quadrilateral_type': quadrilateral_type, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_number_with_validations.py b/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_number_with_validations.py index 4a1129432f54..68847c276eee 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_number_with_validations.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_number_with_validations.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -100,6 +103,99 @@ def discriminator(): 'class_name': 'className', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ComposedOneOfNumberWithValidations - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + class_name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -181,28 +277,24 @@ def __init__(self, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_schema_with_props_and_no_add_props.py b/samples/openapi3/client/petstore/python/petstore_api/model/composed_schema_with_props_and_no_add_props.py new file mode 100644 index 000000000000..2cba94f64090 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_schema_with_props_and_no_add_props.py @@ -0,0 +1,312 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + +def lazy_import(): + from petstore_api.model.tag import Tag + globals()['Tag'] = Tag + + +class ComposedSchemaWithPropsAndNoAddProps(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + lazy_import() + return { + 'color': (str,), # noqa: E501 + 'id': (int,), # noqa: E501 + 'name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'color': 'color', # noqa: E501 + 'id': 'id', # noqa: E501 + 'name': 'name', # noqa: E501 + } + + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ComposedSchemaWithPropsAndNoAddProps - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] # noqa: E501 + id (int): [optional] # noqa: E501 + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """ComposedSchemaWithPropsAndNoAddProps - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] # noqa: E501 + id (int): [optional] # noqa: E501 + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") + + @cached_property + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + lazy_import() + return { + 'anyOf': [ + ], + 'allOf': [ + Tag, + ], + 'oneOf': [ + ], + } diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.py b/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.py index 5a6e424a4ec9..c102f99cd285 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class DanishPig(ModelNormal): @@ -57,7 +60,13 @@ class DanishPig(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,88 @@ def discriminator(): 'class_name': 'className', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """DanishPig - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +256,6 @@ def __init__(self, class_name, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/dog.py b/samples/openapi3/client/petstore/python/petstore_api/model/dog.py index 8bf6d8fd3ade..4a20dafa46cc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/dog.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/dog.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -105,6 +108,100 @@ def discriminator(): 'color': 'color', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Dog - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + breed (str): [optional] # noqa: E501 + color (str): [optional] if omitted the server will use the default value of "red" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -118,13 +215,11 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, class_name, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """Dog - a model defined in OpenAPI - Args: - class_name (str): - Keyword Args: + class_name (str): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -189,29 +284,24 @@ def __init__(self, class_name, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'class_name': class_name, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/dog_all_of.py b/samples/openapi3/client/petstore/python/petstore_api/model/dog_all_of.py index b7b2e7db66d9..dbc36cb2c8f3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/dog_all_of.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/dog_all_of.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class DogAllOf(ModelNormal): @@ -57,7 +60,13 @@ class DogAllOf(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'breed': 'breed', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """DogAllOf - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + breed (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/drawing.py b/samples/openapi3/client/petstore/python/petstore_api/model/drawing.py index 24d402c3a820..41b4a5802c03 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/drawing.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/drawing.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.fruit import Fruit @@ -108,8 +111,88 @@ def discriminator(): 'shapes': 'shapes', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Drawing - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + main_shape (Shape): [optional] # noqa: E501 + shape_or_null (ShapeOrNull): [optional] # noqa: E501 + nullable_shape (NullableShape): [optional] # noqa: E501 + shapes ([Shape]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -191,3 +274,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.py b/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.py index 43ebac57de38..da42763d9c32 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class EnumArrays(ModelNormal): @@ -65,7 +68,13 @@ class EnumArrays(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -94,8 +103,86 @@ def discriminator(): 'array_enum': 'array_enum', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """EnumArrays - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_symbol (str): [optional] # noqa: E501 + array_enum ([str]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -175,3 +262,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.py index 14188ca31d28..a9e7723b255f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class EnumClass(ModelSimple): @@ -58,7 +61,13 @@ class EnumClass(ModelSimple): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -83,6 +92,8 @@ def discriminator(): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -178,3 +189,93 @@ def __init__(self, *args, **kwargs): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """EnumClass - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + + Keyword Args: + value (str): if omitted defaults to "-efg", must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = "-efg" + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.py index c0284b371a93..1587b332721a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.array_of_enums import ArrayOfEnums @@ -89,7 +92,14 @@ class EnumTest(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -137,8 +147,98 @@ def discriminator(): 'array_of_str_enum': 'ArrayOfStrEnum', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, enum_string_required, *args, **kwargs): # noqa: E501 + """EnumTest - a model defined in OpenAPI + + Args: + enum_string_required (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + enum_string (str): [optional] # noqa: E501 + enum_integer (int): [optional] # noqa: E501 + enum_number (float): [optional] # noqa: E501 + string_enum (StringEnum): [optional] # noqa: E501 + integer_enum (IntegerEnum): [optional] # noqa: E501 + string_enum_with_default_value (StringEnumWithDefaultValue): [optional] # noqa: E501 + integer_enum_with_default_value (IntegerEnumWithDefaultValue): [optional] # noqa: E501 + integer_enum_one_value (IntegerEnumOneValue): [optional] # noqa: E501 + inline_array_of_str_enum ([StringEnum]): [optional] # noqa: E501 + array_of_str_enum (ArrayOfEnums): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.enum_string_required = enum_string_required + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -230,3 +330,6 @@ def __init__(self, enum_string_required, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.py b/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.py index a536701d701e..54549b982130 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.shape_interface import ShapeInterface @@ -100,6 +103,99 @@ def discriminator(): 'triangle_type': 'triangleType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """EquilateralTriangle - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + triangle_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -113,14 +209,12 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, shape_type, triangle_type, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """EquilateralTriangle - a model defined in OpenAPI - Args: + Keyword Args: shape_type (str): triangle_type (str): - - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -183,30 +277,24 @@ def __init__(self, shape_type, triangle_type, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'shape_type': shape_type, - 'triangle_type': triangle_type, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/fake_post_inline_additional_properties_payload_array_data.py b/samples/openapi3/client/petstore/python/petstore_api/model/fake_post_inline_additional_properties_payload_array_data.py new file mode 100644 index 000000000000..bf9761b084c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/fake_post_inline_additional_properties_payload_array_data.py @@ -0,0 +1,255 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class FakePostInlineAdditionalPropertiesPayloadArrayData(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'labels': ([str, none_type],), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'labels': 'labels', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """FakePostInlineAdditionalPropertiesPayloadArrayData - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + labels ([str, none_type]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """FakePostInlineAdditionalPropertiesPayloadArrayData - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + labels ([str, none_type]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/file.py b/samples/openapi3/client/petstore/python/petstore_api/model/file.py index a38cccacc6ab..849f5727dc9f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/file.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/file.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class File(ModelNormal): @@ -57,7 +60,13 @@ class File(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'source_uri': 'sourceURI', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """File - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + source_uri (str): Test capitalization. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.py index b8c519ed9c7c..f7e154e47b7c 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.file import File @@ -61,7 +64,14 @@ class FileSchemaTestClass(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -91,8 +101,86 @@ def discriminator(): 'files': 'files', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """FileSchemaTestClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + file (File): [optional] # noqa: E501 + files ([File]): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -172,3 +260,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/foo.py b/samples/openapi3/client/petstore/python/petstore_api/model/foo.py index ebbb09adf91e..ad17251f73b6 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/foo.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/foo.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Foo(ModelNormal): @@ -57,7 +60,13 @@ class Foo(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'bar': 'bar', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Foo - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] if omitted the server will use the default value of "bar" # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/format_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/format_test.py index b232da04b45e..6d4b3b79d705 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/format_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/format_test.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class FormatTest(ModelNormal): @@ -100,7 +103,13 @@ class FormatTest(ModelNormal): }, } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -157,8 +166,106 @@ def discriminator(): 'pattern_with_digits_and_delimiter': 'pattern_with_digits_and_delimiter', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, number, byte, date, password, *args, **kwargs): # noqa: E501 + """FormatTest - a model defined in OpenAPI + + Args: + number (float): + byte (str): + date (date): + password (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + integer (int): [optional] # noqa: E501 + int32 (int): [optional] # noqa: E501 + int64 (int): [optional] # noqa: E501 + float (float): [optional] # noqa: E501 + double (float): [optional] # noqa: E501 + string (str): [optional] # noqa: E501 + binary (file_type): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + uuid (str): [optional] # noqa: E501 + uuid_no_example (str): [optional] # noqa: E501 + pattern_with_digits (str): A string that is a 10 digit number. Can have leading zeros.. [optional] # noqa: E501 + pattern_with_digits_and_delimiter (str): A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.number = number + self.byte = byte + self.date = date + self.password = password + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -258,3 +365,6 @@ def __init__(self, number, byte, date, password, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/fruit.py b/samples/openapi3/client/petstore/python/petstore_api/model/fruit.py index 15ea987edf5d..fedd13c38e47 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/fruit.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/fruit.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.apple import Apple @@ -74,7 +77,14 @@ class Fruit(ModelComposed): }, } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -90,10 +100,10 @@ def openapi_types(): """ lazy_import() return { - 'color': (str,), # noqa: E501 'cultivar': (str,), # noqa: E501 - 'origin': (str,), # noqa: E501 'length_cm': (float,), # noqa: E501 + 'color': (str,), # noqa: E501 + 'origin': (str,), # noqa: E501 } @cached_property @@ -102,12 +112,107 @@ def discriminator(): attribute_map = { - 'color': 'color', # noqa: E501 'cultivar': 'cultivar', # noqa: E501 - 'origin': 'origin', # noqa: E501 'length_cm': 'lengthCm', # noqa: E501 + 'color': 'color', # noqa: E501 + 'origin': 'origin', # noqa: E501 + } + + read_only_vars = { } + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Fruit - a model defined in OpenAPI + + Keyword Args: + cultivar (str): + length_cm (float): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] # noqa: E501 + origin (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -125,6 +230,8 @@ def __init__(self, *args, **kwargs): # noqa: E501 """Fruit - a model defined in OpenAPI Keyword Args: + cultivar (str): + length_cm (float): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -156,9 +263,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 through its discriminator because we passed in _visited_composed_classes = (Animal,) color (str): [optional] # noqa: E501 - cultivar (str): [optional] # noqa: E501 origin (str): [optional] # noqa: E501 - length_cm (float): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -191,28 +296,24 @@ def __init__(self, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.py b/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.py index 13c4d6424a58..01b907c5d8cf 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.apple_req import AppleReq @@ -63,7 +66,14 @@ class FruitReq(ModelComposed): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -97,6 +107,101 @@ def discriminator(): 'length_cm': 'lengthCm', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """FruitReq - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + mealy (bool): [optional] # noqa: E501 + sweet (bool): [optional] # noqa: E501 + cultivar (str): [optional] # noqa: E501 + length_cm (float): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -180,28 +285,24 @@ def __init__(self, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.py b/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.py index f3ad29beb4c4..99efd26f0d4c 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.apple import Apple @@ -74,7 +77,14 @@ class GmFruit(ModelComposed): }, } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -90,10 +100,10 @@ def openapi_types(): """ lazy_import() return { - 'color': (str,), # noqa: E501 'cultivar': (str,), # noqa: E501 - 'origin': (str,), # noqa: E501 'length_cm': (float,), # noqa: E501 + 'color': (str,), # noqa: E501 + 'origin': (str,), # noqa: E501 } @cached_property @@ -102,12 +112,107 @@ def discriminator(): attribute_map = { - 'color': 'color', # noqa: E501 'cultivar': 'cultivar', # noqa: E501 - 'origin': 'origin', # noqa: E501 'length_cm': 'lengthCm', # noqa: E501 + 'color': 'color', # noqa: E501 + 'origin': 'origin', # noqa: E501 + } + + read_only_vars = { } + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """GmFruit - a model defined in OpenAPI + + Keyword Args: + cultivar (str): + length_cm (float): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + color (str): [optional] # noqa: E501 + origin (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -125,6 +230,8 @@ def __init__(self, *args, **kwargs): # noqa: E501 """GmFruit - a model defined in OpenAPI Keyword Args: + cultivar (str): + length_cm (float): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -156,9 +263,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 through its discriminator because we passed in _visited_composed_classes = (Animal,) color (str): [optional] # noqa: E501 - cultivar (str): [optional] # noqa: E501 origin (str): [optional] # noqa: E501 - length_cm (float): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -191,28 +296,24 @@ def __init__(self, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.py b/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.py index f7c417562ece..1580c5a7b724 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_cat import ChildCat @@ -63,7 +66,14 @@ class GrandparentAnimal(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -97,8 +107,88 @@ def discriminator(): 'pet_type': 'pet_type', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, pet_type, *args, **kwargs): # noqa: E501 + """GrandparentAnimal - a model defined in OpenAPI + + Args: + pet_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.pet_type = pet_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -180,3 +270,6 @@ def __init__(self, pet_type, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.py b/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.py index c94781ae2c46..33d1c15b58d9 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class HasOnlyReadOnly(ModelNormal): @@ -57,7 +60,13 @@ class HasOnlyReadOnly(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -86,8 +95,88 @@ def discriminator(): 'foo': 'foo', # noqa: E501 } + read_only_vars = { + 'bar', # noqa: E501 + 'foo', # noqa: E501 + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """HasOnlyReadOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + foo (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +256,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.py b/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.py index 3c0cd37dfad9..0b3818b7c506 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class HealthCheckResult(ModelNormal): @@ -57,7 +60,13 @@ class HealthCheckResult(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'nullable_message': 'NullableMessage', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """HealthCheckResult - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + nullable_message (str, none_type): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py b/samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py index 4d8e8aecff39..85d3fa5922f1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py @@ -25,10 +25,13 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): - from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData - globals()['FakeGetInlineAdditionalPropertiesPayloadArrayData'] = FakeGetInlineAdditionalPropertiesPayloadArrayData + from petstore_api.model.fake_post_inline_additional_properties_payload_array_data import FakePostInlineAdditionalPropertiesPayloadArrayData + globals()['FakePostInlineAdditionalPropertiesPayloadArrayData'] = FakePostInlineAdditionalPropertiesPayloadArrayData class InlineAdditionalPropertiesRefPayload(ModelNormal): @@ -61,7 +64,14 @@ class InlineAdditionalPropertiesRefPayload(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -77,7 +87,7 @@ def openapi_types(): """ lazy_import() return { - 'array_data': ([FakeGetInlineAdditionalPropertiesPayloadArrayData], none_type,), # noqa: E501 + 'array_data': ([FakePostInlineAdditionalPropertiesPayloadArrayData], none_type,), # noqa: E501 } @cached_property @@ -89,8 +99,85 @@ def discriminator(): 'array_data': 'arrayData', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """InlineAdditionalPropertiesRefPayload - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_data ([FakePostInlineAdditionalPropertiesPayloadArrayData], none_type): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -135,7 +222,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - array_data ([FakeGetInlineAdditionalPropertiesPayloadArrayData], none_type): [optional] # noqa: E501 + array_data ([FakePostInlineAdditionalPropertiesPayloadArrayData], none_type): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -169,3 +256,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py b/samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py index d60fec5fa687..828d30aa0762 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py @@ -25,10 +25,13 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): - from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData - globals()['FakeGetInlineAdditionalPropertiesPayloadArrayData'] = FakeGetInlineAdditionalPropertiesPayloadArrayData + from petstore_api.model.fake_post_inline_additional_properties_payload_array_data import FakePostInlineAdditionalPropertiesPayloadArrayData + globals()['FakePostInlineAdditionalPropertiesPayloadArrayData'] = FakePostInlineAdditionalPropertiesPayloadArrayData class InlineObject6(ModelNormal): @@ -61,7 +64,14 @@ class InlineObject6(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -77,7 +87,7 @@ def openapi_types(): """ lazy_import() return { - 'array_data': ([FakeGetInlineAdditionalPropertiesPayloadArrayData], none_type,), # noqa: E501 + 'array_data': ([FakePostInlineAdditionalPropertiesPayloadArrayData], none_type,), # noqa: E501 } @cached_property @@ -89,8 +99,85 @@ def discriminator(): 'array_data': 'arrayData', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """InlineObject6 - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + array_data ([FakePostInlineAdditionalPropertiesPayloadArrayData], none_type): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -135,7 +222,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - array_data ([FakeGetInlineAdditionalPropertiesPayloadArrayData], none_type): [optional] # noqa: E501 + array_data ([FakePostInlineAdditionalPropertiesPayloadArrayData], none_type): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -169,3 +256,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/inline_response_default.py b/samples/openapi3/client/petstore/python/petstore_api/model/inline_response_default.py index 8e814cf43838..b755dbadd364 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/inline_response_default.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/inline_response_default.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.foo import Foo @@ -61,7 +64,14 @@ class InlineResponseDefault(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -89,8 +99,85 @@ def discriminator(): 'string': 'string', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """InlineResponseDefault - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + string (Foo): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -169,3 +256,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.py b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.py index a01fc6149225..2d3d1293cd33 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class IntegerEnum(ModelSimple): @@ -58,7 +61,13 @@ class IntegerEnum(ModelSimple): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -83,6 +92,8 @@ def discriminator(): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -182,3 +193,97 @@ def __init__(self, *args, **kwargs): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """IntegerEnum - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int):, must be one of [0, 1, 2, ] # noqa: E501 + + Keyword Args: + value (int):, must be one of [0, 1, 2, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.py b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.py index 0d69cd535b31..63c1a0b9a7b0 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class IntegerEnumOneValue(ModelSimple): @@ -56,7 +59,13 @@ class IntegerEnumOneValue(ModelSimple): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -81,6 +90,8 @@ def discriminator(): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -176,3 +187,93 @@ def __init__(self, *args, **kwargs): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """IntegerEnumOneValue - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): if omitted defaults to 0, must be one of [0, ] # noqa: E501 + + Keyword Args: + value (int): if omitted defaults to 0, must be one of [0, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = 0 + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.py b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.py index 958b2ad2e39a..008f954a0f15 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class IntegerEnumWithDefaultValue(ModelSimple): @@ -58,7 +61,13 @@ class IntegerEnumWithDefaultValue(ModelSimple): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -83,6 +92,8 @@ def discriminator(): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -178,3 +189,93 @@ def __init__(self, *args, **kwargs): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """IntegerEnumWithDefaultValue - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (int): if omitted defaults to 0, must be one of [0, 1, 2, ] # noqa: E501 + + Keyword Args: + value (int): if omitted defaults to 0, must be one of [0, 1, 2, ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = 0 + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.py b/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.py index 27197f5a235b..bcbc721c2b6b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.shape_interface import ShapeInterface @@ -63,7 +66,14 @@ class IsoscelesTriangle(ModelComposed): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -93,6 +103,99 @@ def discriminator(): 'triangle_type': 'triangleType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """IsoscelesTriangle - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + triangle_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -106,14 +209,12 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, shape_type, triangle_type, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """IsoscelesTriangle - a model defined in OpenAPI - Args: + Keyword Args: shape_type (str): triangle_type (str): - - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -176,30 +277,24 @@ def __init__(self, shape_type, triangle_type, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'shape_type': shape_type, - 'triangle_type': triangle_type, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/list.py b/samples/openapi3/client/petstore/python/petstore_api/model/list.py index 09c762d6a794..4b71d9deec05 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/list.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/list.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class List(ModelNormal): @@ -57,7 +60,13 @@ class List(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): '_123_list': '123-list', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """List - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _123_list (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/mammal.py b/samples/openapi3/client/petstore/python/petstore_api/model/mammal.py index 067adf793505..62037474b90a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/mammal.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/mammal.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.pig import Pig @@ -118,6 +121,101 @@ def discriminator(): 'type': 'type', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Mammal - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + has_baleen (bool): [optional] # noqa: E501 + has_teeth (bool): [optional] # noqa: E501 + type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -131,13 +229,11 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, class_name, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """Mammal - a model defined in OpenAPI - Args: - class_name (str): - Keyword Args: + class_name (str): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -203,29 +299,24 @@ def __init__(self, class_name, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'class_name': class_name, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/map_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/map_test.py index 169fb9d88ee0..39c3b180e88c 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/map_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/map_test.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.string_boolean_map import StringBooleanMap @@ -65,7 +68,14 @@ class MapTest(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -99,8 +109,88 @@ def discriminator(): 'indirect_map': 'indirect_map', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """MapTest - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + map_map_of_string ({str: ({str: (str,)},)}): [optional] # noqa: E501 + map_of_enum_string ({str: (str,)}): [optional] # noqa: E501 + direct_map ({str: (bool,)}): [optional] # noqa: E501 + indirect_map (StringBooleanMap): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -182,3 +272,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py index 01df80d9d62b..f46cd0b89726 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.animal import Animal @@ -61,7 +64,14 @@ class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -93,8 +103,87 @@ def discriminator(): 'map': 'map', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """MixedPropertiesAndAdditionalPropertiesClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + uuid (str): [optional] # noqa: E501 + date_time (datetime): [optional] # noqa: E501 + map ({str: (Animal,)}): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -175,3 +264,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.py b/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.py index 46b155b65239..41a8dee5fdf2 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Model200Response(ModelNormal): @@ -57,7 +60,13 @@ class Model200Response(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -86,8 +95,86 @@ def discriminator(): '_class': 'class', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Model200Response - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (int): [optional] # noqa: E501 + _class (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +254,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/model_return.py b/samples/openapi3/client/petstore/python/petstore_api/model/model_return.py index 377b3507a8b3..f3720b05246f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/model_return.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/model_return.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ModelReturn(ModelNormal): @@ -57,7 +60,13 @@ class ModelReturn(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): '_return': 'return', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ModelReturn - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _return (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/mole.py b/samples/openapi3/client/petstore/python/petstore_api/model/mole.py new file mode 100644 index 000000000000..328168b21235 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/mole.py @@ -0,0 +1,284 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class Mole(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'blind': (bool,), # noqa: E501 + 'smell': (str,), # noqa: E501 + 'hearing': (bool,), # noqa: E501 + 'touch': (bool,), # noqa: E501 + 'taste': (str,), # noqa: E501 + 'seeing_ghosts': (bool,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'blind': 'blind', # noqa: E501 + 'smell': 'smell', # noqa: E501 + 'hearing': 'hearing', # noqa: E501 + 'touch': 'touch', # noqa: E501 + 'taste': 'taste', # noqa: E501 + 'seeing_ghosts': 'seeingGhosts', # noqa: E501 + } + + read_only_vars = { + 'blind', # noqa: E501 + 'touch', # noqa: E501 + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, blind, smell, hearing, *args, **kwargs): # noqa: E501 + """Mole - a model defined in OpenAPI + + Args: + blind (bool): + smell (str): + hearing (bool): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + touch (bool): [optional] # noqa: E501 + taste (str): [optional] # noqa: E501 + seeing_ghosts (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.blind = blind + self.smell = smell + self.hearing = hearing + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, smell, hearing, *args, **kwargs): # noqa: E501 + """Mole - a model defined in OpenAPI + + smell (str): + hearing (bool): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + touch (bool): [optional] # noqa: E501 + taste (str): [optional] # noqa: E501 + seeing_ghosts (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.smell = smell + self.hearing = hearing + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/name.py b/samples/openapi3/client/petstore/python/petstore_api/model/name.py index 1432e185ad6b..d46618c88a14 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/name.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/name.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Name(ModelNormal): @@ -57,7 +60,13 @@ class Name(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -90,8 +99,93 @@ def discriminator(): '_123_number': '123Number', # noqa: E501 } + read_only_vars = { + 'snake_case', # noqa: E501 + '_123_number', # noqa: E501 + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, *args, **kwargs): # noqa: E501 + """Name - a model defined in OpenAPI + + Args: + name (int): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + snake_case (int): [optional] # noqa: E501 + _property (str): [optional] # noqa: E501 + _123_number (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -176,3 +270,6 @@ def __init__(self, name, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.py index a117dfa69160..ad5e551dd0fd 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class NullableClass(ModelNormal): @@ -63,7 +66,7 @@ def additional_properties_type(): This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ - return ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type,) # noqa: E501 + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -87,6 +90,7 @@ def openapi_types(): 'array_nullable_prop': ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}], none_type,), # noqa: E501 'array_and_items_nullable_prop': ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type], none_type,), # noqa: E501 'array_items_nullable': ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type],), # noqa: E501 + 'object_nullable': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type,), # noqa: E501 'object_nullable_prop': ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},)}, none_type,), # noqa: E501 'object_and_items_nullable_prop': ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}, none_type,), # noqa: E501 'object_items_nullable': ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)},), # noqa: E501 @@ -107,13 +111,103 @@ def discriminator(): 'array_nullable_prop': 'array_nullable_prop', # noqa: E501 'array_and_items_nullable_prop': 'array_and_items_nullable_prop', # noqa: E501 'array_items_nullable': 'array_items_nullable', # noqa: E501 + 'object_nullable': 'object_nullable', # noqa: E501 'object_nullable_prop': 'object_nullable_prop', # noqa: E501 'object_and_items_nullable_prop': 'object_and_items_nullable_prop', # noqa: E501 'object_items_nullable': 'object_items_nullable', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """NullableClass - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + integer_prop (int, none_type): [optional] # noqa: E501 + number_prop (float, none_type): [optional] # noqa: E501 + boolean_prop (bool, none_type): [optional] # noqa: E501 + string_prop (str, none_type): [optional] # noqa: E501 + date_prop (date, none_type): [optional] # noqa: E501 + datetime_prop (datetime, none_type): [optional] # noqa: E501 + array_nullable_prop ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}], none_type): [optional] # noqa: E501 + array_and_items_nullable_prop ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type], none_type): [optional] # noqa: E501 + array_items_nullable ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type]): [optional] # noqa: E501 + object_nullable ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): [optional] # noqa: E501 + object_nullable_prop ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},)}, none_type): [optional] # noqa: E501 + object_and_items_nullable_prop ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}, none_type): [optional] # noqa: E501 + object_items_nullable ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,6 +261,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 array_nullable_prop ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}], none_type): [optional] # noqa: E501 array_and_items_nullable_prop ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type], none_type): [optional] # noqa: E501 array_items_nullable ([{str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type]): [optional] # noqa: E501 + object_nullable ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): [optional] # noqa: E501 object_nullable_prop ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},)}, none_type): [optional] # noqa: E501 object_and_items_nullable_prop ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}, none_type): [optional] # noqa: E501 object_items_nullable ({str: ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type)}): [optional] # noqa: E501 @@ -203,3 +298,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.py b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.py index fcd20ddfbc19..6b2a0573ade8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.quadrilateral import Quadrilateral @@ -108,6 +111,100 @@ def discriminator(): 'triangle_type': 'triangleType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """NullableShape - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + quadrilateral_type (str): [optional] # noqa: E501 + triangle_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -121,13 +218,11 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, shape_type, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """NullableShape - a model defined in OpenAPI - Args: - shape_type (str): - Keyword Args: + shape_type (str): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -192,29 +287,24 @@ def __init__(self, shape_type, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'shape_type': shape_type, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/number_only.py b/samples/openapi3/client/petstore/python/petstore_api/model/number_only.py index d4892dbede5b..a96d91650569 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/number_only.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class NumberOnly(ModelNormal): @@ -57,7 +60,13 @@ class NumberOnly(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'just_number': 'JustNumber', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """NumberOnly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + just_number (float): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.py b/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.py index ffa5e9cf4621..afcbf8463eaa 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class NumberWithValidations(ModelSimple): @@ -57,7 +60,13 @@ class NumberWithValidations(ModelSimple): }, } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -82,6 +91,8 @@ def discriminator(): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -181,3 +192,97 @@ def __init__(self, *args, **kwargs): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """NumberWithValidations - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (float): # noqa: E501 + + Keyword Args: + value (float): # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.py b/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.py index 7ba55b76eb24..23d16918fd60 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ObjectInterface(ModelNormal): @@ -88,8 +91,84 @@ def discriminator(): attribute_map = { } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ObjectInterface - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +246,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.py b/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.py index b1dc4bf82e2c..56a55a14c090 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.py @@ -25,10 +25,15 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.number_with_validations import NumberWithValidations + from petstore_api.model.readonly import Readonly globals()['NumberWithValidations'] = NumberWithValidations + globals()['Readonly'] = Readonly class ObjectModelWithRefProps(ModelNormal): @@ -61,7 +66,14 @@ class ObjectModelWithRefProps(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -78,6 +90,7 @@ def openapi_types(): lazy_import() return { 'my_number': (NumberWithValidations,), # noqa: E501 + 'my_readonly': (Readonly,), # noqa: E501 'my_string': (str,), # noqa: E501 'my_boolean': (bool,), # noqa: E501 } @@ -89,12 +102,93 @@ def discriminator(): attribute_map = { 'my_number': 'my_number', # noqa: E501 + 'my_readonly': 'my_readonly', # noqa: E501 'my_string': 'my_string', # noqa: E501 'my_boolean': 'my_boolean', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ObjectModelWithRefProps - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + my_number (NumberWithValidations): [optional] # noqa: E501 + my_readonly (Readonly): [optional] # noqa: E501 + my_string (str): [optional] # noqa: E501 + my_boolean (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -140,6 +234,7 @@ def __init__(self, *args, **kwargs): # noqa: E501 through its discriminator because we passed in _visited_composed_classes = (Animal,) my_number (NumberWithValidations): [optional] # noqa: E501 + my_readonly (Readonly): [optional] # noqa: E501 my_string (str): [optional] # noqa: E501 my_boolean (bool): [optional] # noqa: E501 """ @@ -175,3 +270,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.py b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.py index e03392b1154a..dd38862e11bf 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ObjectWithValidations(ModelNormal): @@ -91,8 +94,84 @@ def discriminator(): attribute_map = { } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ObjectWithValidations - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -170,3 +249,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/order.py b/samples/openapi3/client/petstore/python/petstore_api/model/order.py index b42f066848ab..eeefff1513f6 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/order.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/order.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Order(ModelNormal): @@ -62,7 +65,13 @@ class Order(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -99,8 +108,90 @@ def discriminator(): 'complete': 'complete', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Order - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + pet_id (int): [optional] # noqa: E501 + quantity (int): [optional] # noqa: E501 + ship_date (datetime): [optional] # noqa: E501 + status (str): Order Status. [optional] # noqa: E501 + complete (bool): [optional] if omitted the server will use the default value of False # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -184,3 +275,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.py b/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.py index 16099236da34..ff58abf3d793 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.child_cat import ChildCat @@ -103,6 +106,98 @@ def discriminator(): 'pet_type': 'pet_type', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ParentPet - a model defined in OpenAPI + + Keyword Args: + pet_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -116,13 +211,11 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, pet_type, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """ParentPet - a model defined in OpenAPI - Args: - pet_type (str): - Keyword Args: + pet_type (str): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -185,29 +278,24 @@ def __init__(self, pet_type, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'pet_type': pet_type, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/pet.py b/samples/openapi3/client/petstore/python/petstore_api/model/pet.py index e9f1e30a3196..8946f6d4bea3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/pet.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/pet.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.category import Category @@ -68,7 +71,14 @@ class Pet(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + lazy_import() + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -106,8 +116,94 @@ def discriminator(): 'status': 'status', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, name, photo_urls, *args, **kwargs): # noqa: E501 + """Pet - a model defined in OpenAPI + + Args: + name (str): + photo_urls ([str]): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + category (Category): [optional] # noqa: E501 + tags ([Tag]): [optional] # noqa: E501 + status (str): pet status in the store. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.name = name + self.photo_urls = photo_urls + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -195,3 +291,6 @@ def __init__(self, name, photo_urls, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/pig.py b/samples/openapi3/client/petstore/python/petstore_api/model/pig.py index 4a6f200f6ffc..07845be55eb1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/pig.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.basque_pig import BasquePig @@ -104,6 +107,98 @@ def discriminator(): 'class_name': 'className', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Pig - a model defined in OpenAPI + + Keyword Args: + class_name (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -117,13 +212,11 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, class_name, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """Pig - a model defined in OpenAPI - Args: - class_name (str): - Keyword Args: + class_name (str): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -186,29 +279,24 @@ def __init__(self, class_name, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'class_name': class_name, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.py b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.py index 4e28ac0d2389..b3aefcd1bd50 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral @@ -106,6 +109,99 @@ def discriminator(): 'shape_type': 'shapeType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Quadrilateral - a model defined in OpenAPI + + Keyword Args: + quadrilateral_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + shape_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -119,13 +215,11 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, quadrilateral_type, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """Quadrilateral - a model defined in OpenAPI - Args: - quadrilateral_type (str): - Keyword Args: + quadrilateral_type (str): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -189,29 +283,24 @@ def __init__(self, quadrilateral_type, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'quadrilateral_type': quadrilateral_type, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.py b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.py index 124d9128bc53..5ca8fae392a8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class QuadrilateralInterface(ModelNormal): @@ -57,7 +60,13 @@ class QuadrilateralInterface(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,88 @@ def discriminator(): 'quadrilateral_type': 'quadrilateralType', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, quadrilateral_type, *args, **kwargs): # noqa: E501 + """QuadrilateralInterface - a model defined in OpenAPI + + Args: + quadrilateral_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.quadrilateral_type = quadrilateral_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +256,6 @@ def __init__(self, quadrilateral_type, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.py b/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.py index 5c68eab91ea3..38cb5e2634f6 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ReadOnlyFirst(ModelNormal): @@ -57,7 +60,13 @@ class ReadOnlyFirst(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -86,8 +95,87 @@ def discriminator(): 'baz': 'baz', # noqa: E501 } + read_only_vars = { + 'bar', # noqa: E501 + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ReadOnlyFirst - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + bar (str): [optional] # noqa: E501 + baz (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +255,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/readonly.py b/samples/openapi3/client/petstore/python/petstore_api/model/readonly.py new file mode 100644 index 000000000000..9a98af452eb8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/model/readonly.py @@ -0,0 +1,255 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ApiTypeError, + ModelComposed, + ModelNormal, + ModelSimple, + cached_property, + change_keys_js_to_python, + convert_js_args_to_python_args, + date, + datetime, + file_type, + none_type, + validate_get_composed_info, +) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + + + +class Readonly(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 + + _nullable = False + + @cached_property + def openapi_types(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'name': (str,), # noqa: E501 + } + + @cached_property + def discriminator(): + return None + + + attribute_map = { + 'name': 'name', # noqa: E501 + } + + read_only_vars = { + } + + _composed_schemas = {} + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Readonly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + + required_properties = set([ + '_data_store', + '_check_type', + '_spec_property_naming', + '_path_to_item', + '_configuration', + '_visited_composed_classes', + ]) + + @convert_js_args_to_python_args + def __init__(self, *args, **kwargs): # noqa: E501 + """Readonly - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.py b/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.py index 1e3893627dad..a10ce28f172b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.shape_interface import ShapeInterface @@ -100,6 +103,99 @@ def discriminator(): 'triangle_type': 'triangleType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ScaleneTriangle - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + triangle_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -113,14 +209,12 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, shape_type, triangle_type, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """ScaleneTriangle - a model defined in OpenAPI - Args: + Keyword Args: shape_type (str): triangle_type (str): - - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -183,30 +277,24 @@ def __init__(self, shape_type, triangle_type, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'shape_type': shape_type, - 'triangle_type': triangle_type, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/shape.py b/samples/openapi3/client/petstore/python/petstore_api/model/shape.py index f5e3c142b914..50e21b8c8d8b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/shape.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/shape.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.quadrilateral import Quadrilateral @@ -108,6 +111,100 @@ def discriminator(): 'triangle_type': 'triangleType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Shape - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + quadrilateral_type (str): [optional] # noqa: E501 + triangle_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -121,13 +218,11 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, shape_type, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """Shape - a model defined in OpenAPI - Args: - shape_type (str): - Keyword Args: + shape_type (str): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -192,29 +287,24 @@ def __init__(self, shape_type, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'shape_type': shape_type, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/shape_interface.py b/samples/openapi3/client/petstore/python/petstore_api/model/shape_interface.py index 8a3c52088be3..0f11d5a14466 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/shape_interface.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/shape_interface.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class ShapeInterface(ModelNormal): @@ -57,7 +60,13 @@ class ShapeInterface(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,88 @@ def discriminator(): 'shape_type': 'shapeType', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, shape_type, *args, **kwargs): # noqa: E501 + """ShapeInterface - a model defined in OpenAPI + + Args: + shape_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.shape_type = shape_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +256,6 @@ def __init__(self, shape_type, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.py b/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.py index 480fa5bd5d65..00ae221f8a63 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.quadrilateral import Quadrilateral @@ -108,6 +111,100 @@ def discriminator(): 'triangle_type': 'triangleType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """ShapeOrNull - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + quadrilateral_type (str): [optional] # noqa: E501 + triangle_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -121,13 +218,11 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, shape_type, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """ShapeOrNull - a model defined in OpenAPI - Args: - shape_type (str): - Keyword Args: + shape_type (str): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -192,29 +287,24 @@ def __init__(self, shape_type, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'shape_type': shape_type, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.py b/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.py index f2f0a61acbd2..1a3bef4c26e2 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.quadrilateral_interface import QuadrilateralInterface @@ -100,6 +103,99 @@ def discriminator(): 'quadrilateral_type': 'quadrilateralType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """SimpleQuadrilateral - a model defined in OpenAPI + + Keyword Args: + shape_type (str): + quadrilateral_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -113,14 +209,12 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, shape_type, quadrilateral_type, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """SimpleQuadrilateral - a model defined in OpenAPI - Args: + Keyword Args: shape_type (str): quadrilateral_type (str): - - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -183,30 +277,24 @@ def __init__(self, shape_type, quadrilateral_type, *args, **kwargs): # noqa: E5 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'shape_type': shape_type, - 'quadrilateral_type': quadrilateral_type, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/some_object.py b/samples/openapi3/client/petstore/python/petstore_api/model/some_object.py index 683d1794293c..3c3215d357bb 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/some_object.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/some_object.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.object_interface import ObjectInterface @@ -94,6 +97,97 @@ def discriminator(): attribute_map = { } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """SomeObject - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -173,28 +267,24 @@ def __init__(self, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/some_object_with_self_attr.py b/samples/openapi3/client/petstore/python/petstore_api/model/some_object_with_self_attr.py index 343122b65f3b..76e776ae67fc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/some_object_with_self_attr.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/some_object_with_self_attr.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class SomeObjectWithSelfAttr(ModelNormal): @@ -57,7 +60,13 @@ class SomeObjectWithSelfAttr(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): '_self': 'self', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """SomeObjectWithSelfAttr - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + _self (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.py b/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.py index 823e77596636..cc2e49f6bcb0 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class SpecialModelName(ModelNormal): @@ -57,7 +60,13 @@ class SpecialModelName(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,85 @@ def discriminator(): 'special_property_name': '$special[property.name]', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """SpecialModelName - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + special_property_name (int): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -164,3 +250,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.py b/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.py index 4ac526991839..05f8527fec1e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class StringBooleanMap(ModelNormal): @@ -88,8 +91,84 @@ def discriminator(): attribute_map = { } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """StringBooleanMap - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +246,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.py b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.py index a6d2fbee08f2..890e25eeddcf 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class StringEnum(ModelSimple): @@ -64,7 +67,13 @@ class StringEnum(ModelSimple): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = True @@ -89,6 +98,8 @@ def discriminator(): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -192,3 +203,101 @@ def __init__(self, *args, **kwargs): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """StringEnum - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str):, must be one of ["placed", "approved", "delivered", "single quoted", '''multiple +lines''', '''double quote + with newline''', ] # noqa: E501 + + Keyword Args: + value (str):, must be one of ["placed", "approved", "delivered", "single quoted", '''multiple +lines''', '''double quote + with newline''', ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + raise ApiTypeError( + "value is required, but not passed in args or kwargs and doesn't have default", + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.py b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.py index 4dfc426446ca..3861e56a08ce 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class StringEnumWithDefaultValue(ModelSimple): @@ -58,7 +61,13 @@ class StringEnumWithDefaultValue(ModelSimple): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -83,6 +92,8 @@ def discriminator(): attribute_map = {} + read_only_vars = set() + _composed_schemas = None required_properties = set([ @@ -178,3 +189,93 @@ def __init__(self, *args, **kwargs): path_to_item=_path_to_item, valid_classes=(self.__class__,), ) + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): + """StringEnumWithDefaultValue - a model defined in OpenAPI + + Note that value can be passed either in args or in kwargs, but not in both. + + Args: + args[0] (str): if omitted defaults to "placed", must be one of ["placed", "approved", "delivered", ] # noqa: E501 + + Keyword Args: + value (str): if omitted defaults to "placed", must be one of ["placed", "approved", "delivered", ] # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + # required up here when default value is not given + _path_to_item = kwargs.pop('_path_to_item', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if 'value' in kwargs: + value = kwargs.pop('value') + elif args: + args = list(args) + value = args.pop(0) + else: + value = "placed" + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + self.value = value + if kwargs: + raise ApiTypeError( + "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( + kwargs, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + return self diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/tag.py b/samples/openapi3/client/petstore/python/petstore_api/model/tag.py index e5fc749d5149..95a08c180731 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/tag.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/tag.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Tag(ModelNormal): @@ -57,7 +60,13 @@ class Tag(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -86,8 +95,86 @@ def discriminator(): 'name': 'name', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Tag - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + name (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +254,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/triangle.py b/samples/openapi3/client/petstore/python/petstore_api/model/triangle.py index 83d6e52e8867..f9082e2098ff 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/triangle.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/triangle.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + def lazy_import(): from petstore_api.model.equilateral_triangle import EquilateralTriangle @@ -109,6 +112,99 @@ def discriminator(): 'shape_type': 'shapeType', # noqa: E501 } + read_only_vars = { + } + + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """Triangle - a model defined in OpenAPI + + Keyword Args: + triangle_type (str): + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + shape_type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_spec_property_naming': _spec_property_naming, + '_configuration': _configuration, + '_visited_composed_classes': self._visited_composed_classes, + } + composed_info = validate_get_composed_info( + constant_args, kwargs, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + discarded_args = composed_info[3] + + for var_name, var_value in kwargs.items(): + if var_name in discarded_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + return self + required_properties = set([ '_data_store', '_check_type', @@ -122,13 +218,11 @@ def discriminator(): ]) @convert_js_args_to_python_args - def __init__(self, triangle_type, *args, **kwargs): # noqa: E501 + def __init__(self, *args, **kwargs): # noqa: E501 """Triangle - a model defined in OpenAPI - Args: - triangle_type (str): - Keyword Args: + triangle_type (str): _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -192,29 +286,24 @@ def __init__(self, triangle_type, *args, **kwargs): # noqa: E501 '_configuration': _configuration, '_visited_composed_classes': self._visited_composed_classes, } - required_args = { - 'triangle_type': triangle_type, - } - model_args = {} - model_args.update(required_args) - model_args.update(kwargs) composed_info = validate_get_composed_info( - constant_args, model_args, self) + constant_args, kwargs, self) self._composed_instances = composed_info[0] self._var_name_to_model_instances = composed_info[1] self._additional_properties_model_instances = composed_info[2] - unused_args = composed_info[3] + discarded_args = composed_info[3] - for var_name, var_value in required_args.items(): - setattr(self, var_name, var_value) for var_name, var_value in kwargs.items(): - if var_name in unused_args and \ + if var_name in discarded_args and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ - not self._additional_properties_model_instances: + self._additional_properties_model_instances: # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") @cached_property def _composed_schemas(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.py b/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.py index c54bd0811720..783e5fe3bf83 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class TriangleInterface(ModelNormal): @@ -57,7 +60,13 @@ class TriangleInterface(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -84,8 +93,88 @@ def discriminator(): 'triangle_type': 'triangleType', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, triangle_type, *args, **kwargs): # noqa: E501 + """TriangleInterface - a model defined in OpenAPI + + Args: + triangle_type (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.triangle_type = triangle_type + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -167,3 +256,6 @@ def __init__(self, triangle_type, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/user.py b/samples/openapi3/client/petstore/python/petstore_api/model/user.py index 7613ac7dc263..f77ab381d217 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/user.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/user.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class User(ModelNormal): @@ -57,7 +60,13 @@ class User(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -106,8 +115,96 @@ def discriminator(): 'any_type_prop_nullable': 'anyTypePropNullable', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 + """User - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + id (int): [optional] # noqa: E501 + username (str): [optional] # noqa: E501 + first_name (str): [optional] # noqa: E501 + last_name (str): [optional] # noqa: E501 + email (str): [optional] # noqa: E501 + password (str): [optional] # noqa: E501 + phone (str): [optional] # noqa: E501 + user_status (int): User Status. [optional] # noqa: E501 + object_with_no_declared_props ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}): test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value.. [optional] # noqa: E501 + object_with_no_declared_props_nullable ({str: (bool, date, datetime, dict, float, int, list, str, none_type)}, none_type): test code generation for nullable objects. Value must be a map of strings to values or the 'null' value.. [optional] # noqa: E501 + any_type_prop (bool, date, datetime, dict, float, int, list, str, none_type): test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389. [optional] # noqa: E501 + any_type_prop_nullable (bool, date, datetime, dict, float, int, list, str, none_type): test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values.. [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -197,3 +294,6 @@ def __init__(self, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/whale.py b/samples/openapi3/client/petstore/python/petstore_api/model/whale.py index e6400ea34fc7..a8eb263b118f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/whale.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/whale.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Whale(ModelNormal): @@ -57,7 +60,13 @@ class Whale(ModelNormal): validations = { } - additional_properties_type = None + @cached_property + def additional_properties_type(): + """ + This must be a method because a model may have properties that are + of type self, this must run after the class is loaded + """ + return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @@ -88,8 +97,90 @@ def discriminator(): 'has_teeth': 'hasTeeth', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """Whale - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + has_baleen (bool): [optional] # noqa: E501 + has_teeth (bool): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -173,3 +264,6 @@ def __init__(self, class_name, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/zebra.py b/samples/openapi3/client/petstore/python/petstore_api/model/zebra.py index bf5bbbefa9ce..c348b3316715 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/zebra.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/zebra.py @@ -25,6 +25,9 @@ none_type, validate_get_composed_info, ) +from ..model_utils import OpenApiModel +from petstore_api.exceptions import ApiAttributeError + class Zebra(ModelNormal): @@ -97,8 +100,89 @@ def discriminator(): 'type': 'type', # noqa: E501 } + read_only_vars = { + } + _composed_schemas = {} + @classmethod + @convert_js_args_to_python_args + def _from_openapi_data(cls, class_name, *args, **kwargs): # noqa: E501 + """Zebra - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + _visited_composed_classes (tuple): This stores a tuple of + classes that we have traveled through so that + if we see that class again we will not use its + discriminator again. + When traveling through a discriminator, the + composed schema that is + is traveled through is added to this set. + For example if Animal has a discriminator + petType and we pass in "Dog", and the class Dog + allOf includes Animal, we move through Animal + once using the discriminator, and pick Dog. + Then in Dog, we will make an instance of the + Animal class but this time we won't travel + through its discriminator because we passed in + _visited_composed_classes = (Animal,) + type (str): [optional] # noqa: E501 + """ + + _check_type = kwargs.pop('_check_type', True) + _spec_property_naming = kwargs.pop('_spec_property_naming', False) + _path_to_item = kwargs.pop('_path_to_item', ()) + _configuration = kwargs.pop('_configuration', None) + _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) + + self = super(OpenApiModel, cls).__new__(cls) + + if args: + raise ApiTypeError( + "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( + args, + self.__class__.__name__, + ), + path_to_item=_path_to_item, + valid_classes=(self.__class__,), + ) + + self._data_store = {} + self._check_type = _check_type + self._spec_property_naming = _spec_property_naming + self._path_to_item = _path_to_item + self._configuration = _configuration + self._visited_composed_classes = _visited_composed_classes + (self.__class__,) + + self.class_name = class_name + for var_name, var_value in kwargs.items(): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) + return self + required_properties = set([ '_data_store', '_check_type', @@ -181,3 +265,6 @@ def __init__(self, class_name, *args, **kwargs): # noqa: E501 # discard variable. continue setattr(self, var_name, var_value) + if var_name in self.read_only_vars: + raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " + f"class with read only attributes.") diff --git a/samples/openapi3/client/petstore/python/petstore_api/model_utils.py b/samples/openapi3/client/petstore/python/petstore_api/model_utils.py index f73278f35cc7..97f9b2881cc5 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model_utils.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model_utils.py @@ -29,6 +29,22 @@ file_type = io.IOBase +def convert_js_args_to_python_args(fn): + from functools import wraps + @wraps(fn) + def wrapped_init(_self, *args, **kwargs): + """ + An attribute named `self` received from the api will conflicts with the reserved `self` + parameter of a class method. During generation, `self` attributes are mapped + to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. + """ + spec_property_naming = kwargs.get('_spec_property_naming', False) + if spec_property_naming: + kwargs = change_keys_js_to_python(kwargs, _self if isinstance(_self, type) else _self.__class__) + return fn(_self, *args, **kwargs) + return wrapped_init + + class cached_property(object): # this caches the result of the function call for fn with no inputs # use this as a decorator on fuction methods that you want converted @@ -284,6 +300,121 @@ def __new__(cls, *args, **kwargs): return new_inst + @classmethod + @convert_js_args_to_python_args + def _new_from_openapi_data(cls, *args, **kwargs): + # this function uses the discriminator to + # pick a new schema/class to instantiate because a discriminator + # propertyName value was passed in + + if len(args) == 1: + arg = args[0] + if arg is None and is_type_nullable(cls): + # The input data is the 'null' value and the type is nullable. + return None + + if issubclass(cls, ModelComposed) and allows_single_value_input(cls): + model_kwargs = {} + oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg) + return oneof_instance + + + visited_composed_classes = kwargs.get('_visited_composed_classes', ()) + if ( + cls.discriminator is None or + cls in visited_composed_classes + ): + # Use case 1: this openapi schema (cls) does not have a discriminator + # Use case 2: we have already visited this class before and are sure that we + # want to instantiate it this time. We have visited this class deserializing + # a payload with a discriminator. During that process we traveled through + # this class but did not make an instance of it. Now we are making an + # instance of a composed class which contains cls in it, so this time make an instance of cls. + # + # Here's an example of use case 2: If Animal has a discriminator + # petType and we pass in "Dog", and the class Dog + # allOf includes Animal, we move through Animal + # once using the discriminator, and pick Dog. + # Then in the composed schema dog Dog, we will make an instance of the + # Animal class (because Dal has allOf: Animal) but this time we won't travel + # through Animal's discriminator because we passed in + # _visited_composed_classes = (Animal,) + + return cls._from_openapi_data(*args, **kwargs) + + # Get the name and value of the discriminator property. + # The discriminator name is obtained from the discriminator meta-data + # and the discriminator value is obtained from the input data. + discr_propertyname_py = list(cls.discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if discr_propertyname_js in kwargs: + discr_value = kwargs[discr_propertyname_js] + elif discr_propertyname_py in kwargs: + discr_value = kwargs[discr_propertyname_py] + else: + # The input data does not contain the discriminator property. + path_to_item = kwargs.get('_path_to_item', ()) + raise ApiValueError( + "Cannot deserialize input data due to missing discriminator. " + "The discriminator property '%s' is missing at path: %s" % + (discr_propertyname_js, path_to_item) + ) + + # Implementation note: the last argument to get_discriminator_class + # is a list of visited classes. get_discriminator_class may recursively + # call itself and update the list of visited classes, and the initial + # value must be an empty list. Hence not using 'visited_composed_classes' + new_cls = get_discriminator_class( + cls, discr_propertyname_py, discr_value, []) + if new_cls is None: + path_to_item = kwargs.get('_path_to_item', ()) + disc_prop_value = kwargs.get( + discr_propertyname_js, kwargs.get(discr_propertyname_py)) + raise ApiValueError( + "Cannot deserialize input data due to invalid discriminator " + "value. The OpenAPI document has no mapping for discriminator " + "property '%s'='%s' at path: %s" % + (discr_propertyname_js, disc_prop_value, path_to_item) + ) + + if new_cls in visited_composed_classes: + # if we are making an instance of a composed schema Descendent + # which allOf includes Ancestor, then Ancestor contains + # a discriminator that includes Descendent. + # So if we make an instance of Descendent, we have to make an + # instance of Ancestor to hold the allOf properties. + # This code detects that use case and makes the instance of Ancestor + # For example: + # When making an instance of Dog, _visited_composed_classes = (Dog,) + # then we make an instance of Animal to include in dog._composed_instances + # so when we are here, cls is Animal + # cls.discriminator != None + # cls not in _visited_composed_classes + # new_cls = Dog + # but we know we know that we already have Dog + # because it is in visited_composed_classes + # so make Animal here + return cls._from_openapi_data(*args, **kwargs) + + # Build a list containing all oneOf and anyOf descendants. + oneof_anyof_classes = None + if cls._composed_schemas is not None: + oneof_anyof_classes = ( + cls._composed_schemas.get('oneOf', ()) + + cls._composed_schemas.get('anyOf', ())) + oneof_anyof_child = new_cls in oneof_anyof_classes + kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,) + + if cls._composed_schemas.get('allOf') and oneof_anyof_child: + # Validate that we can make self because when we make the + # new_cls it will not include the allOf validations in self + self_inst = cls._from_openapi_data(*args, **kwargs) + + + new_inst = new_cls._new_from_openapi_data(*args, **kwargs) + return new_inst + + class ModelSimple(OpenApiModel): """the parent class of models whose type != object in their swagger/openapi""" @@ -434,27 +565,43 @@ def __setitem__(self, name, value): self.__dict__[name] = value return - # set the attribute on the correct instance - model_instances = self._var_name_to_model_instances.get( - name, self._additional_properties_model_instances) - if model_instances: - for model_instance in model_instances: - if model_instance == self: - self.set_attribute(name, value) - else: - setattr(model_instance, name, value) - if name not in self._var_name_to_model_instances: - # we assigned an additional property - self.__dict__['_var_name_to_model_instances'][name] = ( - model_instance - ) - return None - - raise ApiAttributeError( - "{0} has no attribute '{1}'".format( - type(self).__name__, name), - [e for e in [self._path_to_item, name] if e] - ) + """ + Use cases: + 1. additional_properties_type is None (additionalProperties == False in spec) + Check for property presence in self.openapi_types + if not present then throw an error + if present set in self, set attribute + always set on composed schemas + 2. additional_properties_type exists + set attribute on self + always set on composed schemas + """ + if self.additional_properties_type is None: + """ + For an attribute to exist on a composed schema it must: + - fulfill schema_requirements in the self composed schema not considering oneOf/anyOf/allOf schemas AND + - fulfill schema_requirements in each oneOf/anyOf/allOf schemas + + schema_requirements: + For an attribute to exist on a schema it must: + - be present in properties at the schema OR + - have additionalProperties unset (defaults additionalProperties = any type) OR + - have additionalProperties set + """ + if name not in self.openapi_types: + raise ApiAttributeError( + "{0} has no attribute '{1}'".format( + type(self).__name__, name), + [e for e in [self._path_to_item, name] if e] + ) + # attribute must be set on self and composed instances + self.set_attribute(name, value) + for model_instance in self._composed_instances: + setattr(model_instance, name, value) + if name not in self._var_name_to_model_instances: + # we assigned an additional property + self.__dict__['_var_name_to_model_instances'][name] = self._composed_instances + [self] + return None __unset_attribute_value__ = object() @@ -464,13 +611,12 @@ def get(self, name, default=None): return self.__dict__[name] # get the attribute from the correct instance - model_instances = self._var_name_to_model_instances.get( - name, self._additional_properties_model_instances) + model_instances = self._var_name_to_model_instances.get(name) values = [] - # A composed model stores child (oneof/anyOf/allOf) models under - # self._var_name_to_model_instances. A named property can exist in - # multiple child models. If the property is present in more than one - # child model, the value must be the same across all the child models. + # A composed model stores self and child (oneof/anyOf/allOf) models under + # self._var_name_to_model_instances. + # Any property must exist in self and all model instances + # The value stored in all model instances must be the same if model_instances: for model_instance in model_instances: if name in model_instance._data_store: @@ -1193,14 +1339,14 @@ def deserialize_model(model_data, model_class, path_to_item, check_type, _spec_property_naming=spec_property_naming) if issubclass(model_class, ModelSimple): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) elif isinstance(model_data, list): - return model_class(*model_data, **kw_args) + return model_class._new_from_openapi_data(*model_data, **kw_args) if isinstance(model_data, dict): kw_args.update(model_data) - return model_class(**kw_args) + return model_class._new_from_openapi_data(**kw_args) elif isinstance(model_data, PRIMITIVE_TYPES): - return model_class(model_data, **kw_args) + return model_class._new_from_openapi_data(model_data, **kw_args) def deserialize_file(response_data, configuration, content_disposition=None): @@ -1486,12 +1632,20 @@ def model_to_dict(model_instance, serialize=True): model_instances = [model_instance] if model_instance._composed_schemas: model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} for model_instance in model_instances: for attr, value in model_instance._data_store.items(): if serialize: # we use get here because additional property key names do not # exist in attribute_map - attr = model_instance.attribute_map.get(attr, attr) + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) if isinstance(value, list): if not value: # empty list or None @@ -1519,6 +1673,16 @@ def model_to_dict(model_instance, serialize=True): result[attr] = model_to_dict(value, serialize=serialize) else: result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] return result @@ -1562,30 +1726,19 @@ def get_valid_classes_phrase(input_classes): return "is one of [{0}]".format(", ".join(all_class_names)) -def convert_js_args_to_python_args(fn): - from functools import wraps - @wraps(fn) - def wrapped_init(_self, *args, **kwargs): - """ - An attribute named `self` received from the api will conflicts with the reserved `self` - parameter of a class method. During generation, `self` attributes are mapped - to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts. - """ - spec_property_naming = kwargs.get('_spec_property_naming', False) - if spec_property_naming: - kwargs = change_keys_js_to_python(kwargs, _self.__class__) - return fn(_self, *args, **kwargs) - return wrapped_init - - def get_allof_instances(self, model_args, constant_args): """ Args: self: the class we are handling model_args (dict): var_name to var_value used to make instances - constant_args (dict): var_name to var_value - used to make instances + constant_args (dict): + metadata arguments: + _check_type + _path_to_item + _spec_property_naming + _configuration + _visited_composed_classes Returns composed_instances (list) @@ -1593,20 +1746,8 @@ def get_allof_instances(self, model_args, constant_args): composed_instances = [] for allof_class in self._composed_schemas['allOf']: - # no need to handle changing js keys to python because - # for composed schemas, allof parameters are included in the - # composed schema and were changed to python keys in __new__ - # extract a dict of only required keys from fixed_model_args - kwargs = {} - var_names = set(allof_class.openapi_types.keys()) - for var_name in var_names: - if var_name in model_args: - kwargs[var_name] = model_args[var_name] - - # and use it to make the instance - kwargs.update(constant_args) try: - allof_instance = allof_class(**kwargs) + allof_instance = allof_class(**model_args, **constant_args) composed_instances.append(allof_instance) except Exception as ex: raise ApiValueError( @@ -1666,31 +1807,9 @@ def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None): single_value_input = allows_single_value_input(oneof_class) - if not single_value_input: - # transform js keys from input data to python keys in fixed_model_args - fixed_model_args = change_keys_js_to_python( - model_kwargs, oneof_class) - - # Extract a dict with the properties that are declared in the oneOf schema. - # Undeclared properties (e.g. properties that are allowed because of the - # additionalProperties attribute in the OAS document) are not added to - # the dict. - kwargs = {} - var_names = set(oneof_class.openapi_types.keys()) - for var_name in var_names: - if var_name in fixed_model_args: - kwargs[var_name] = fixed_model_args[var_name] - - # do not try to make a model with no input args - if len(kwargs) == 0: - continue - - # and use it to make the instance - kwargs.update(constant_kwargs) - try: if not single_value_input: - oneof_instance = oneof_class(**kwargs) + oneof_instance = oneof_class(**model_kwargs, **constant_kwargs) else: if issubclass(oneof_class, ModelSimple): oneof_instance = oneof_class(model_arg, **constant_kwargs) @@ -1747,24 +1866,8 @@ def get_anyof_instances(self, model_args, constant_args): # none_type deserialization is handled in the __new__ method continue - # transform js keys to python keys in fixed_model_args - fixed_model_args = change_keys_js_to_python(model_args, anyof_class) - - # extract a dict of only required keys from these_model_vars - kwargs = {} - var_names = set(anyof_class.openapi_types.keys()) - for var_name in var_names: - if var_name in fixed_model_args: - kwargs[var_name] = fixed_model_args[var_name] - - # do not try to make a model with no input args - if len(kwargs) == 0: - continue - - # and use it to make the instance - kwargs.update(constant_args) try: - anyof_instance = anyof_class(**kwargs) + anyof_instance = anyof_class(**model_args, **constant_args) anyof_instances.append(anyof_instance) except Exception: pass @@ -1777,47 +1880,34 @@ def get_anyof_instances(self, model_args, constant_args): return anyof_instances -def get_additional_properties_model_instances( - composed_instances, self): - additional_properties_model_instances = [] - all_instances = [self] - all_instances.extend(composed_instances) - for instance in all_instances: - if instance.additional_properties_type is not None: - additional_properties_model_instances.append(instance) - return additional_properties_model_instances - - -def get_var_name_to_model_instances(self, composed_instances): - var_name_to_model_instances = {} - all_instances = [self] - all_instances.extend(composed_instances) - for instance in all_instances: - for var_name in instance.openapi_types: - if var_name not in var_name_to_model_instances: - var_name_to_model_instances[var_name] = [instance] - else: - var_name_to_model_instances[var_name].append(instance) - return var_name_to_model_instances - - -def get_unused_args(self, composed_instances, model_args): - unused_args = dict(model_args) - # arguments apssed to self were already converted to python names +def get_discarded_args(self, composed_instances, model_args): + """ + Gathers the args that were discarded by configuration.discard_unknown_keys + """ + model_arg_keys = model_args.keys() + discarded_args = set() + # arguments passed to self were already converted to python names # before __init__ was called - for var_name_py in self.attribute_map: - if var_name_py in unused_args: - del unused_args[var_name_py] for instance in composed_instances: if instance.__class__ in self._composed_schemas['allOf']: - for var_name_py in instance.attribute_map: - if var_name_py in unused_args: - del unused_args[var_name_py] + try: + keys = instance.to_dict().keys() + discarded_keys = model_args - keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass else: - for var_name_js in instance.attribute_map.values(): - if var_name_js in unused_args: - del unused_args[var_name_js] - return unused_args + try: + all_keys = set(model_to_dict(instance, serialize=False).keys()) + js_keys = model_to_dict(instance, serialize=True).keys() + all_keys.update(js_keys) + discarded_keys = model_arg_keys - all_keys + discarded_args.update(discarded_keys) + except Exception: + # allOf integer schema will throw exception + pass + return discarded_args def validate_get_composed_info(constant_args, model_args, self): @@ -1861,36 +1951,42 @@ def validate_get_composed_info(constant_args, model_args, self): composed_instances.append(oneof_instance) anyof_instances = get_anyof_instances(self, model_args, constant_args) composed_instances.extend(anyof_instances) + """ + set additional_properties_model_instances + additional properties must be evaluated at the schema level + so self's additional properties are most important + If self is a composed schema with: + - no properties defined in self + - additionalProperties: False + Then for object payloads every property is an additional property + and they are not allowed, so only empty dict is allowed + + Properties must be set on all matching schemas + so when a property is assigned toa composed instance, it must be set on all + composed instances regardless of additionalProperties presence + keeping it to prevent breaking changes in v5.0.1 + TODO remove cls._additional_properties_model_instances in 6.0.0 + """ + additional_properties_model_instances = [] + if self.additional_properties_type is not None: + additional_properties_model_instances = [self] - # map variable names to composed_instances - var_name_to_model_instances = get_var_name_to_model_instances( - self, composed_instances) - - # set additional_properties_model_instances - additional_properties_model_instances = ( - get_additional_properties_model_instances(composed_instances, self) - ) - - # set any remaining values - unused_args = get_unused_args(self, composed_instances, model_args) - if len(unused_args) > 0 and \ - len(additional_properties_model_instances) == 0 and \ - (self._configuration is None or - not self._configuration.discard_unknown_keys): - raise ApiValueError( - "Invalid input arguments input when making an instance of " - "class %s. Not all inputs were used. The unused input data " - "is %s" % (self.__class__.__name__, unused_args) - ) + """ + no need to set properties on self in here, they will be set in __init__ + By here all composed schema oneOf/anyOf/allOf instances have their properties set using + model_args + """ + discarded_args = get_discarded_args(self, composed_instances, model_args) - # no need to add additional_properties to var_name_to_model_instances here - # because additional_properties_model_instances will direct us to that - # instance when we use getattr or setattr - # and we update var_name_to_model_instances in setattr + # map variable names to composed_instances + var_name_to_model_instances = {} + for prop_name in model_args: + if prop_name not in discarded_args: + var_name_to_model_instances[prop_name] = [self] + composed_instances return [ composed_instances, var_name_to_model_instances, additional_properties_model_instances, - unused_args + discarded_args ] diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py index 5875dbb55cf2..9485a03d2f88 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py @@ -34,6 +34,7 @@ from petstore_api.model.client import Client from petstore_api.model.complex_quadrilateral import ComplexQuadrilateral from petstore_api.model.composed_one_of_number_with_validations import ComposedOneOfNumberWithValidations +from petstore_api.model.composed_schema_with_props_and_no_add_props import ComposedSchemaWithPropsAndNoAddProps from petstore_api.model.danish_pig import DanishPig from petstore_api.model.dog import Dog from petstore_api.model.dog_all_of import DogAllOf @@ -42,7 +43,7 @@ from petstore_api.model.enum_class import EnumClass from petstore_api.model.enum_test import EnumTest from petstore_api.model.equilateral_triangle import EquilateralTriangle -from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData +from petstore_api.model.fake_post_inline_additional_properties_payload_array_data import FakePostInlineAdditionalPropertiesPayloadArrayData from petstore_api.model.file import File from petstore_api.model.file_schema_test_class import FileSchemaTestClass from petstore_api.model.foo import Foo @@ -66,6 +67,7 @@ from petstore_api.model.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass from petstore_api.model.model200_response import Model200Response from petstore_api.model.model_return import ModelReturn +from petstore_api.model.mole import Mole from petstore_api.model.name import Name from petstore_api.model.nullable_class import NullableClass from petstore_api.model.nullable_shape import NullableShape @@ -81,6 +83,7 @@ from petstore_api.model.quadrilateral import Quadrilateral from petstore_api.model.quadrilateral_interface import QuadrilateralInterface from petstore_api.model.read_only_first import ReadOnlyFirst +from petstore_api.model.readonly import Readonly from petstore_api.model.scalene_triangle import ScaleneTriangle from petstore_api.model.shape import Shape from petstore_api.model.shape_interface import ShapeInterface diff --git a/samples/openapi3/client/petstore/python/pom.xml b/samples/openapi3/client/petstore/python/pom.xml index c2364c744828..e7d7d9caf133 100644 --- a/samples/openapi3/client/petstore/python/pom.xml +++ b/samples/openapi3/client/petstore/python/pom.xml @@ -1,10 +1,10 @@ 4.0.0 org.openapitools - PythonExperimentalOAS3PetstoreTests + PythonOAS3PetstoreTests pom 1.0-SNAPSHOT - Python-Experimental OpenAPI3 Petstore Client + Python OpenAPI3 Petstore Client diff --git a/samples/openapi3/client/petstore/python/test/test_composed_schema_with_props_and_no_add_props.py b/samples/openapi3/client/petstore/python/test/test_composed_schema_with_props_and_no_add_props.py new file mode 100644 index 000000000000..7e7ac901ca6d --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_composed_schema_with_props_and_no_add_props.py @@ -0,0 +1,37 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.tag import Tag +globals()['Tag'] = Tag +from petstore_api.model.composed_schema_with_props_and_no_add_props import ComposedSchemaWithPropsAndNoAddProps + + +class TestComposedSchemaWithPropsAndNoAddProps(unittest.TestCase): + """ComposedSchemaWithPropsAndNoAddProps unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testComposedSchemaWithPropsAndNoAddProps(self): + """Test ComposedSchemaWithPropsAndNoAddProps""" + # FIXME: construct object with mandatory attributes with example values + # model = ComposedSchemaWithPropsAndNoAddProps() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_fake_post_inline_additional_properties_payload_array_data.py b/samples/openapi3/client/petstore/python/test/test_fake_post_inline_additional_properties_payload_array_data.py new file mode 100644 index 000000000000..6b4be44e865d --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_fake_post_inline_additional_properties_payload_array_data.py @@ -0,0 +1,35 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.fake_post_inline_additional_properties_payload_array_data import FakePostInlineAdditionalPropertiesPayloadArrayData + + +class TestFakePostInlineAdditionalPropertiesPayloadArrayData(unittest.TestCase): + """FakePostInlineAdditionalPropertiesPayloadArrayData unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testFakePostInlineAdditionalPropertiesPayloadArrayData(self): + """Test FakePostInlineAdditionalPropertiesPayloadArrayData""" + # FIXME: construct object with mandatory attributes with example values + # model = FakePostInlineAdditionalPropertiesPayloadArrayData() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_inline_additional_properties_ref_payload.py b/samples/openapi3/client/petstore/python/test/test_inline_additional_properties_ref_payload.py index 709ee27adc89..7e8cf543335f 100644 --- a/samples/openapi3/client/petstore/python/test/test_inline_additional_properties_ref_payload.py +++ b/samples/openapi3/client/petstore/python/test/test_inline_additional_properties_ref_payload.py @@ -12,8 +12,8 @@ import unittest import petstore_api -from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData -globals()['FakeGetInlineAdditionalPropertiesPayloadArrayData'] = FakeGetInlineAdditionalPropertiesPayloadArrayData +from petstore_api.model.fake_post_inline_additional_properties_payload_array_data import FakePostInlineAdditionalPropertiesPayloadArrayData +globals()['FakePostInlineAdditionalPropertiesPayloadArrayData'] = FakePostInlineAdditionalPropertiesPayloadArrayData from petstore_api.model.inline_additional_properties_ref_payload import InlineAdditionalPropertiesRefPayload diff --git a/samples/openapi3/client/petstore/python/test/test_inline_object6.py b/samples/openapi3/client/petstore/python/test/test_inline_object6.py index 463123d8e558..887e5689b9ad 100644 --- a/samples/openapi3/client/petstore/python/test/test_inline_object6.py +++ b/samples/openapi3/client/petstore/python/test/test_inline_object6.py @@ -12,8 +12,8 @@ import unittest import petstore_api -from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData -globals()['FakeGetInlineAdditionalPropertiesPayloadArrayData'] = FakeGetInlineAdditionalPropertiesPayloadArrayData +from petstore_api.model.fake_post_inline_additional_properties_payload_array_data import FakePostInlineAdditionalPropertiesPayloadArrayData +globals()['FakePostInlineAdditionalPropertiesPayloadArrayData'] = FakePostInlineAdditionalPropertiesPayloadArrayData from petstore_api.model.inline_object6 import InlineObject6 diff --git a/samples/openapi3/client/petstore/python/test/test_mole.py b/samples/openapi3/client/petstore/python/test/test_mole.py new file mode 100644 index 000000000000..176fdf03a314 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_mole.py @@ -0,0 +1,35 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.mole import Mole + + +class TestMole(unittest.TestCase): + """Mole unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testMole(self): + """Test Mole""" + # FIXME: construct object with mandatory attributes with example values + # mole = Mole() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_readonly.py b/samples/openapi3/client/petstore/python/test/test_readonly.py new file mode 100644 index 000000000000..50be60d4e446 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_readonly.py @@ -0,0 +1,35 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.readonly import Readonly + + +class TestReadonly(unittest.TestCase): + """Readonly unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testReadonly(self): + """Test Readonly""" + # FIXME: construct object with mandatory attributes with example values + # model = Readonly() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_composed_schema_with_props_and_no_add_props.py b/samples/openapi3/client/petstore/python/tests_manual/test_composed_schema_with_props_and_no_add_props.py new file mode 100644 index 000000000000..d219a4e4b8aa --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_composed_schema_with_props_and_no_add_props.py @@ -0,0 +1,45 @@ +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.tag import Tag +globals()['Tag'] = Tag +from petstore_api.model.composed_schema_with_props_and_no_add_props import ComposedSchemaWithPropsAndNoAddProps + + +class TestComposedSchemaWithPropsAndNoAddProps(unittest.TestCase): + """ComposedSchemaWithPropsAndNoAddProps unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testComposedSchemaWithPropsAndNoAddProps(self): + """Test ComposedSchemaWithPropsAndNoAddProps""" + + inst = ComposedSchemaWithPropsAndNoAddProps(color='red') + + # ComposedSchemaWithPropsAndNoAddProps should only allow in the color property + # once https://github.com/OpenAPITools/openapi-generator/pull/8816 lands + # this will no longer work + # TODO update the test then + inst = ComposedSchemaWithPropsAndNoAddProps(color='red', id=1, name='foo') + + with self.assertRaises(petstore_api.ApiAttributeError): + inst = ComposedSchemaWithPropsAndNoAddProps(color='red', id=1, name='foo', additional=5) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_deserialization.py b/samples/openapi3/client/petstore/python/tests_manual/test_deserialization.py index 37e0943273ad..93538160f9a8 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_deserialization.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_deserialization.py @@ -118,12 +118,7 @@ def test_regex_constraint(self): ) assert isinstance(inst, apple.Apple) - inst = apple.Apple( - origin="cHiLe" - ) - assert isinstance(inst, apple.Apple) - - # Test with invalid regex pattern. + # Test with invalid regex pattern in cultivar err_msg = ("Invalid value for `{}`, must match regular expression `{}`$") with self.assertRaisesRegex( petstore_api.ApiValueError, @@ -133,12 +128,14 @@ def test_regex_constraint(self): cultivar="!@#%@$#Akane" ) + # Test with invalid regex pattern in origin err_msg = ("Invalid value for `{}`, must match regular expression `{}` with flags") with self.assertRaisesRegex( petstore_api.ApiValueError, err_msg.format("origin", "[^`]*") ): inst = apple.Apple( + cultivar="Akane", origin="!@#%@$#Chile" ) diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_discard_unknown_properties.py b/samples/openapi3/client/petstore/python/tests_manual/test_discard_unknown_properties.py index d8b71e44353e..ed1ca736d4ba 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_discard_unknown_properties.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_discard_unknown_properties.py @@ -16,7 +16,7 @@ import unittest import petstore_api -from petstore_api.model import cat, dog, isosceles_triangle, banana_req +from petstore_api.model import cat, dog, isosceles_triangle, banana_req, fruit_req from petstore_api import Configuration, signing from petstore_api.model_utils import ( @@ -54,17 +54,17 @@ def test_deserialize_banana_req_do_not_discard_unknown_properties(self): 'Exception message: {0}'.format(str(cm.exception))) - def test_deserialize_isosceles_triangle_do_not_discard_unknown_properties(self): + def test_deserialize_fruit_req_do_not_discard_unknown_properties(self): """ - deserialize IsoscelesTriangle with unknown properties. + deserialize FruitReq with unknown properties. Strict validation is enabled. Composed schema scenario. """ config = Configuration(discard_unknown_keys=False) api_client = petstore_api.ApiClient(config) data = { - 'shape_type': 'Triangle', - 'triangle_type': 'EquilateralTriangle', + 'lengthCm': 21.3, + 'sweet': False, # Below is an unknown property not explicitly declared in the OpenAPI document. # It should not be in the payload because additional properties (undeclared) are # not allowed in the schema (additionalProperties: false). @@ -74,10 +74,29 @@ def test_deserialize_isosceles_triangle_do_not_discard_unknown_properties(self): # Deserializing with strict validation raises an exception because the 'unknown_property' # is undeclared. - with self.assertRaises(petstore_api.ApiValueError) as cm: - deserialized = api_client.deserialize(response, ((isosceles_triangle.IsoscelesTriangle),), True) - self.assertTrue(re.match('.*Not all inputs were used.*unknown_property.*', str(cm.exception)), - 'Exception message: {0}'.format(str(cm.exception))) + with self.assertRaisesRegex(petstore_api.ApiValueError, "Invalid inputs given to generate an instance of FruitReq. None of the oneOf schemas matched the input data."): + deserialized = api_client.deserialize(response, ((fruit_req.FruitReq),), True) + + + def test_deserialize_fruit_req_discard_unknown_properties(self): + """ + deserialize FruitReq with unknown properties. + Strict validation is enabled. + Composed schema scenario. + """ + config = Configuration(discard_unknown_keys=True) + api_client = petstore_api.ApiClient(config) + data = { + 'lengthCm': 21.3, + 'sweet': False, + # Below is an unknown property not explicitly declared in the OpenAPI document. + # It should not be in the payload because additional properties (undeclared) are + # not allowed in BananaReq + 'unknown_property': 'a-value' + } + response = MockResponse(data=json.dumps(data)) + deserialized = api_client.deserialize(response, ((fruit_req.FruitReq),), True) + self.assertNotIn("unknown_property", deserialized.to_dict().keys()) def test_deserialize_banana_req_discard_unknown_properties(self): @@ -145,13 +164,10 @@ def test_deserialize_cat_discard_unknown_properties(self): # Below are additional (undeclared) properties. "my_additional_property": 123, } - # The 'my_additional_property' is undeclared, but 'Cat' has a 'Address' type through - # the allOf: [ $ref: '#/components/schemas/Address' ]. + # The 'my_additional_property' is undeclared response = MockResponse(data=json.dumps(data)) deserialized = api_client.deserialize(response, ((cat.Cat),), True) self.assertTrue(isinstance(deserialized, cat.Cat)) - # Check the 'unknown_property' and 'more-unknown' properties are not present in the - # output. - self.assertIn("declawed", deserialized.to_dict().keys()) + # Check the 'my_additional_property' is present self.assertIn("my_additional_property", deserialized.to_dict().keys()) diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_fake_api.py b/samples/openapi3/client/petstore/python/tests_manual/test_fake_api.py index 8c0886e373b6..954f1ce8e5c2 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_fake_api.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_fake_api.py @@ -19,7 +19,7 @@ import petstore_api from petstore_api.api.fake_api import FakeApi # noqa: E501 from petstore_api.rest import RESTClientObject, RESTResponse -from petstore_api.model_utils import file_type +from petstore_api.model_utils import file_type, model_to_dict HTTPResponse = namedtuple( 'urllib3_response_HTTPResponse', @@ -59,14 +59,15 @@ def assert_request_called_with( url, accept='application/json', http_method='POST', + content_type='application/json', **kwargs ): headers = { 'Accept': accept, 'User-Agent': 'OpenAPI-Generator/1.0.0/python', } - if 'content_type' in kwargs: - headers['Content-Type'] = kwargs['content_type'] + if content_type: + headers['Content-Type'] = content_type used_kwargs = dict( _preload_content=True, _request_timeout=None, @@ -77,12 +78,13 @@ def assert_request_called_with( used_kwargs['post_params'] = kwargs['post_params'] if 'body' in kwargs: used_kwargs['body'] = kwargs['body'] - else: - mock_method.assert_called_with( - http_method, - url, - **used_kwargs - ) + if 'post_params' not in used_kwargs: + used_kwargs['post_params'] = [] + mock_method.assert_called_with( + http_method, + url, + **used_kwargs + ) def test_array_model(self): """Test case for array_model @@ -101,7 +103,11 @@ def test_array_model(self): mock_method.return_value = self.mock_response(json_data) response = endpoint(body=body) - self.assert_request_called_with(mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/arraymodel', body=json_data) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/arraymodel', + body=json_data, + ) assert isinstance(response, animal_farm.AnimalFarm) assert response == body @@ -158,7 +164,10 @@ def test_enum_test(self): response = endpoint(enum_test=body) self.assert_request_called_with( - mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/enum-test', body=json_value) + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/enum-test', + body=json_value, + ) assert isinstance(response, EnumTest) assert response == body @@ -174,7 +183,10 @@ def test_enum_test(self): response = endpoint(enum_test=body) self.assert_request_called_with( - mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/enum-test', body=json_value) + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/enum-test', + body=json_value, + ) assert isinstance(response, EnumTest) assert response == body @@ -198,7 +210,11 @@ def test_array_of_enums(self): mock_method.return_value = self.mock_response(value_simple) response = endpoint(array_of_enums=body) - self.assert_request_called_with(mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/array-of-enums', body=value_simple) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/array-of-enums', + body=value_simple, + ) assert isinstance(response, array_of_enums.ArrayOfEnums) assert response.value == value @@ -219,7 +235,11 @@ def test_number_with_validations(self): mock_method.return_value = self.mock_response(value) response = endpoint(body=body) - self.assert_request_called_with(mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/number', body=value) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/number', + body=value, + ) assert isinstance(response, number_with_validations.NumberWithValidations) assert response.value == value @@ -262,7 +282,7 @@ def test_object_model_with_ref_props(self): self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/object_model_with_ref_props', - body=json_payload + body=json_payload, ) assert isinstance(response, expected_model.__class__) @@ -300,7 +320,7 @@ def test_composed_one_of_number_with_validations(self): self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/composed_one_of_number_with_validations', - body=value_simple + body=value_simple, ) assert isinstance(response, body.__class__) @@ -321,7 +341,11 @@ def test_string(self): mock_method.return_value = self.mock_response(value_simple) response = endpoint(body=body) - self.assert_request_called_with(mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/string', body=value_simple) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/string', + body=value_simple, + ) assert isinstance(response, str) assert response == value_simple @@ -343,7 +367,11 @@ def test_string_enum(self): mock_method.return_value = self.mock_response(value) response = endpoint(body=body) - self.assert_request_called_with(mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/enum', body=value) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/enum', + body=value, + ) assert isinstance(response, string_enum.StringEnum) assert response.value == value @@ -495,6 +523,7 @@ def get_header(name, default=None): 'http://www.jtricks.com/download-text', http_method='GET', accept='text/plain', + content_type=None, ) self.assertTrue(isinstance(file_object, file_type)) self.assertFalse(file_object.closed) @@ -532,8 +561,11 @@ def get_header(name, default=None): self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', - body=expected_file_data, content_type='application/octet-stream' + body=expected_file_data, + content_type='application/octet-stream', + accept='application/octet-stream' ) + self.assertTrue(isinstance(downloaded_file, file_type)) self.assertFalse(downloaded_file.closed) self.assertEqual(downloaded_file.read(), expected_file_data) @@ -604,12 +636,12 @@ def test_test_query_parameter_collection_format(self): """ pass - def test_get_inline_additional_properties_ref_payload(self): - """Test case for getInlineAdditionlPropertiesRefPayload + def test_post_inline_additional_properties_ref_payload(self): + """Test case for postInlineAdditionlPropertiesRefPayload """ from petstore_api.model.inline_additional_properties_ref_payload import InlineAdditionalPropertiesRefPayload - from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData - endpoint = self.api.get_inline_additional_properties_ref_payload + from petstore_api.model.fake_post_inline_additional_properties_payload_array_data import FakePostInlineAdditionalPropertiesPayloadArrayData + endpoint = self.api.post_inline_additional_properties_ref_payload assert endpoint.openapi_types['inline_additional_properties_ref_payload'] == (InlineAdditionalPropertiesRefPayload,) assert endpoint.settings['response_type'] == (InlineAdditionalPropertiesRefPayload,) @@ -617,7 +649,7 @@ def test_get_inline_additional_properties_ref_payload(self): from petstore_api.rest import RESTClientObject, RESTResponse with patch.object(RESTClientObject, 'request') as mock_method: expected_json_body = { - 'array_data': [ + 'arrayData': [ { 'labels': [ None, @@ -628,23 +660,27 @@ def test_get_inline_additional_properties_ref_payload(self): } inline_additional_properties_ref_payload = InlineAdditionalPropertiesRefPayload( array_data=[ - FakeGetInlineAdditionalPropertiesPayloadArrayData(labels=[None, 'foo']) + FakePostInlineAdditionalPropertiesPayloadArrayData(labels=[None, 'foo']) ] ) mock_method.return_value = self.mock_response(expected_json_body) response = endpoint(inline_additional_properties_ref_payload=inline_additional_properties_ref_payload) - self.assert_request_called_with(mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/enum', body=expected_json_body) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/postInlineAdditionalPropertiesRefPayload', + body=expected_json_body + ) assert isinstance(response, InlineAdditionalPropertiesRefPayload) - assert response.to_dict() == expected_json_body + assert model_to_dict(response) == expected_json_body - def test_get_inline_additional_properties_payload(self): - """Test case for getInlineAdditionlPropertiesPayload + def test_post_inline_additional_properties_payload(self): + """Test case for postInlineAdditionlPropertiesPayload """ from petstore_api.model.inline_object6 import InlineObject6 - from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData - endpoint = self.api.get_inline_additional_properties_payload + from petstore_api.model.fake_post_inline_additional_properties_payload_array_data import FakePostInlineAdditionalPropertiesPayloadArrayData + endpoint = self.api.post_inline_additional_properties_payload assert endpoint.openapi_types['inline_object6'] == (InlineObject6,) assert endpoint.settings['response_type'] == (InlineObject6,) @@ -652,7 +688,7 @@ def test_get_inline_additional_properties_payload(self): from petstore_api.rest import RESTClientObject, RESTResponse with patch.object(RESTClientObject, 'request') as mock_method: expected_json_body = { - 'array_data': [ + 'arrayData': [ { 'labels': [ None, @@ -663,16 +699,20 @@ def test_get_inline_additional_properties_payload(self): } inline_object6 = InlineObject6( array_data=[ - FakeGetInlineAdditionalPropertiesPayloadArrayData(labels=[None, 'foo']) + FakePostInlineAdditionalPropertiesPayloadArrayData(labels=[None, 'foo']) ] ) mock_method.return_value = self.mock_response(expected_json_body) response = endpoint(inline_object6=inline_object6) - self.assert_request_called_with(mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/enum', body=expected_json_body) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/postInlineAdditionalPropertiesPayload', + body=expected_json_body + ) assert isinstance(response, InlineObject6) - assert response.to_dict() == expected_json_body + assert model_to_dict(response) == expected_json_body if __name__ == '__main__': unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_fruit.py b/samples/openapi3/client/petstore/python/tests_manual/test_fruit.py index a60fdb9f6be3..f95c07755f85 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_fruit.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_fruit.py @@ -14,56 +14,70 @@ import unittest import petstore_api -try: - from petstore_api.model import apple -except ImportError: - apple = sys.modules[ - 'petstore_api.model.apple'] -try: - from petstore_api.model import banana -except ImportError: - banana = sys.modules[ - 'petstore_api.model.banana'] +from petstore_api.model import apple +from petstore_api.model import banana from petstore_api.model.fruit import Fruit class TestFruit(unittest.TestCase): """Fruit unit test stubs""" + length_cm = 20.3 + color = 'yellow' + + def setUp(self): pass def tearDown(self): pass - def testFruit(self): - """Test Fruit""" + def test_fruit_with_additional_props(self): + # including extra parameters works because the oneOf models include additionalProperties + some_value = 'some_value' + some_fruit = Fruit( + color=self.color, + length_cm=self.length_cm, + unknown_property=some_value + ) + assert some_fruit['unknown_property'] == some_value + + def test_fruit_assigning_additional_props_in_client(self): + # setting a value that doesn't exist works because additional_properties_type allows any type + other_fruit = Fruit(length_cm=self.length_cm, color=self.color) + blah = 'blah' + other_fruit['a'] = blah + assert other_fruit.a == blah + + # with setattr + setattr(other_fruit, 'b', blah) + assert other_fruit.b == blah - # make an instance of Fruit, a composed schema oneOf model - # banana test - length_cm = 20.3 - color = 'yellow' - fruit = Fruit(length_cm=length_cm, color=color) - # check its properties - self.assertEqual(fruit.length_cm, length_cm) - self.assertEqual(fruit['length_cm'], length_cm) - self.assertEqual(fruit.get('length_cm'), length_cm) - self.assertEqual(getattr(fruit, 'length_cm'), length_cm) - self.assertEqual(fruit.color, color) - self.assertEqual(fruit['color'], color) - self.assertEqual(getattr(fruit, 'color'), color) - # check the dict representation self.assertEqual( - fruit.to_dict(), + other_fruit.to_dict(), { - 'length_cm': length_cm, - 'color': color + 'a': 'blah', + 'b': 'blah', + 'length_cm': self.length_cm, + 'color': self.color } ) - # setting a value that doesn't exist raises an exception + + def test_fruit_access_errors(self): + fruit = Fruit(length_cm=self.length_cm, color=self.color) + + # getting a value that doesn't exist raises an exception # with a key with self.assertRaises(AttributeError): - fruit['invalid_variable'] = 'some value' + invalid_variable = fruit['cultivar'] + + # Per Python doc, if the named attribute does not exist, + # default is returned if provided, otherwise AttributeError is raised. + with self.assertRaises(AttributeError): + getattr(fruit, 'cultivar') + + def test_fruit_attribute_access(self): + fruit = Fruit(length_cm=self.length_cm, color=self.color) # Assert that we can call the builtin hasattr() function. # hasattr should return False for non-existent attribute. @@ -74,14 +88,6 @@ def testFruit(self): # hasattr should return True for existent attribute. self.assertTrue(hasattr(fruit, 'color')) - # with setattr - with self.assertRaises(AttributeError): - setattr(fruit, 'invalid_variable', 'some value') - - # getting a value that doesn't exist raises an exception - # with a key - with self.assertRaises(AttributeError): - invalid_variable = fruit['cultivar'] # with getattr # Per Python doc, if the named attribute does not exist, # default is returned if provided. @@ -89,10 +95,28 @@ def testFruit(self): self.assertEqual(fruit.get('cultivar'), None) self.assertEqual(fruit.get('cultivar', 'some value'), 'some value') - # Per Python doc, if the named attribute does not exist, - # default is returned if provided, otherwise AttributeError is raised. - with self.assertRaises(AttributeError): - getattr(fruit, 'cultivar') + def test_banana_fruit(self): + """Test Fruit""" + + # make an instance of Fruit, a composed schema oneOf model + # banana test + fruit = Fruit(length_cm=self.length_cm, color=self.color) + # check its properties + self.assertEqual(fruit.length_cm, self.length_cm) + self.assertEqual(fruit['length_cm'], self.length_cm) + self.assertEqual(fruit.get('length_cm'), self.length_cm) + self.assertEqual(getattr(fruit, 'length_cm'), self.length_cm) + self.assertEqual(fruit.color, self.color) + self.assertEqual(fruit['color'], self.color) + self.assertEqual(getattr(fruit, 'color'), self.color) + # check the dict representation + self.assertEqual( + fruit.to_dict(), + { + 'length_cm': self.length_cm, + 'color': self.color + } + ) # make sure that the ModelComposed class properties are correct # model._composed_schemas stores the anyOf/allOf/oneOf info @@ -109,6 +133,7 @@ def testFruit(self): ) # model._composed_instances is a list of the instances that were # made from the anyOf/allOf/OneOf classes in model._composed_schemas + self.assertEqual(len(fruit._composed_instances), 1) for composed_instance in fruit._composed_instances: if composed_instance.__class__ == banana.Banana: banana_instance = composed_instance @@ -118,19 +143,16 @@ def testFruit(self): ) # model._var_name_to_model_instances maps the variable name to the # model instances which store that variable + print(fruit._var_name_to_model_instances) self.assertEqual( fruit._var_name_to_model_instances, { - 'color': [fruit], + 'color': [fruit, banana_instance], 'length_cm': [fruit, banana_instance], - 'cultivar': [fruit], - 'origin': [fruit], } ) - # model._additional_properties_model_instances stores a list of - # models which have the property additional_properties_type != None self.assertEqual( - fruit._additional_properties_model_instances, [] + fruit._additional_properties_model_instances, [fruit] ) # if we modify one of the properties owned by multiple @@ -140,21 +162,15 @@ def testFruit(self): with self.assertRaises(petstore_api.ApiValueError): some_length_cm = fruit.length_cm - # including extra parameters raises an exception - with self.assertRaises(petstore_api.ApiValueError): - fruit = Fruit( - color=color, - length_cm=length_cm, - unknown_property='some value' - ) - # including input parameters for two oneOf instances raise an exception with self.assertRaises(petstore_api.ApiValueError): fruit = Fruit( - length_cm=length_cm, + length_cm=self.length_cm, cultivar='granny smith' ) + def test_apple_fruit(self): + # make an instance of Fruit, a composed schema oneOf model # apple test color = 'red' @@ -190,19 +206,15 @@ def testFruit(self): self.assertEqual( fruit._var_name_to_model_instances, { - 'color': [fruit], - 'length_cm': [fruit], + 'color': [fruit, apple_instance], 'cultivar': [fruit, apple_instance], - 'origin': [fruit, apple_instance], } ) - # model._additional_properties_model_instances stores a list of - # models which have the property additional_properties_type != None self.assertEqual( - fruit._additional_properties_model_instances, [] + fruit._additional_properties_model_instances, [fruit] ) - def testFruitNullValue(self): + def test_null_fruit(self): # Since 'apple' is nullable, validate we can create an apple with the 'null' value. fruit = apple.Apple(None) self.assertIsNone(fruit) @@ -220,5 +232,16 @@ def testFruitNullValue(self): fruit = Fruit(apple.Apple(None)) self.assertIsNone(fruit) + def test_fruit_with_invalid_input_type(self): + + """ + color must be a str, color's str type is only defined at the Fruit level + Banana + Apple would allow color to be assigned with any type of value + """ + invalid_value = 1 + with self.assertRaises(petstore_api.ApiTypeError): + fruit = Fruit(color=invalid_value, length_cm=self.length_cm) + + if __name__ == '__main__': unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_fruit_req.py b/samples/openapi3/client/petstore/python/tests_manual/test_fruit_req.py index 3e637c3226a0..64b710fdd583 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_fruit_req.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_fruit_req.py @@ -14,21 +14,14 @@ import unittest import petstore_api -try: - from petstore_api.model import apple_req -except ImportError: - apple_req = sys.modules[ - 'petstore_api.model.apple_req'] -try: - from petstore_api.model import banana_req -except ImportError: - banana_req = sys.modules[ - 'petstore_api.model.banana_req'] +from petstore_api.model import apple_req +from petstore_api.model import banana_req from petstore_api.model.fruit_req import FruitReq class TestFruitReq(unittest.TestCase): """FruitReq unit test stubs""" + length_cm = 20.3 def setUp(self): pass @@ -36,24 +29,9 @@ def setUp(self): def tearDown(self): pass - def testFruitReq(self): - """Test FruitReq""" + def test_fruit_access_errors(self): + fruit = FruitReq(length_cm=self.length_cm) - # make an instance of Fruit, a composed schema oneOf model - # banana test - length_cm = 20.3 - fruit = FruitReq(length_cm=length_cm) - # check its properties - self.assertEqual(fruit.length_cm, length_cm) - self.assertEqual(fruit['length_cm'], length_cm) - self.assertEqual(getattr(fruit, 'length_cm'), length_cm) - # check the dict representation - self.assertEqual( - fruit.to_dict(), - { - 'length_cm': length_cm, - } - ) # setting a value that doesn't exist raises an exception # with a key with self.assertRaises(AttributeError): @@ -66,12 +44,31 @@ def testFruitReq(self): # with a key with self.assertRaises(AttributeError): invalid_variable = fruit['cultivar'] - # with getattr - self.assertEqual(getattr(fruit, 'cultivar', 'some value'), 'some value') with self.assertRaises(AttributeError): getattr(fruit, 'cultivar') + def test_FruitReq_banana(self): + """Test FruitReq""" + + # make an instance of Fruit, a composed schema oneOf model + # banana test + fruit = FruitReq(length_cm=self.length_cm) + # check its properties + self.assertEqual(fruit.length_cm, self.length_cm) + self.assertEqual(fruit['length_cm'], self.length_cm) + self.assertEqual(getattr(fruit, 'length_cm'), self.length_cm) + # check the dict representation + self.assertEqual( + fruit.to_dict(), + { + 'length_cm': self.length_cm, + } + ) + + # with getattr + self.assertEqual(getattr(fruit, 'cultivar', 'some value'), 'some value') + # make sure that the ModelComposed class properties are correct # model._composed_schemas stores the anyOf/allOf/oneOf info self.assertEqual( @@ -101,15 +98,10 @@ def testFruitReq(self): fruit._var_name_to_model_instances, { 'length_cm': [fruit, banana_instance], - 'cultivar': [fruit], - 'mealy': [fruit], - 'sweet': [fruit, banana_instance], } ) - # model._additional_properties_model_instances stores a list of - # models which have the property additional_properties_type != None self.assertEqual( - fruit._additional_properties_model_instances, [] + fruit._additional_properties_model_instances, [fruit] ) # if we modify one of the properties owned by multiple @@ -119,21 +111,24 @@ def testFruitReq(self): with self.assertRaises(petstore_api.ApiValueError): some_length_cm = fruit.length_cm + def test_invalid_inputs(self): # including extra parameters raises an exception with self.assertRaises(petstore_api.ApiValueError): fruit = FruitReq( - length_cm=length_cm, + length_cm=self.length_cm, unknown_property='some value' ) # including input parameters for two oneOf instances raise an exception with self.assertRaises(petstore_api.ApiValueError): fruit = FruitReq( - length_cm=length_cm, + length_cm=self.length_cm, cultivar='granny smith' ) - # make an instance of Fruit, a composed schema oneOf model + def test_FruitReq_apple(self): + """Test FruitReq""" + # apple test cultivar = 'golden delicious' fruit = FruitReq(cultivar=cultivar) @@ -163,21 +158,18 @@ def testFruitReq(self): self.assertEqual( fruit._var_name_to_model_instances, { - 'length_cm': [fruit], 'cultivar': [fruit, apple_instance], - 'mealy': [fruit, apple_instance], - 'sweet': [fruit], } ) - # model._additional_properties_model_instances stores a list of - # models which have the property additional_properties_type != None self.assertEqual( - fruit._additional_properties_model_instances, [] + fruit._additional_properties_model_instances, [fruit] ) + def test_null_fruit(self): # we can pass in None fruit = FruitReq(None) assert fruit is None + if __name__ == '__main__': unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_gm_fruit.py b/samples/openapi3/client/petstore/python/tests_manual/test_gm_fruit.py index 85d0fcf9b1c7..ad5907ee4436 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_gm_fruit.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_gm_fruit.py @@ -14,21 +14,15 @@ import unittest import petstore_api -try: - from petstore_api.model import apple -except ImportError: - apple = sys.modules[ - 'petstore_api.model.apple'] -try: - from petstore_api.model import banana -except ImportError: - banana = sys.modules[ - 'petstore_api.model.banana'] +from petstore_api.model import apple +from petstore_api.model import banana from petstore_api.model.gm_fruit import GmFruit class TestGmFruit(unittest.TestCase): """GmFruit unit test stubs""" + length_cm = 20.3 + color = 'yellow' def setUp(self): pass @@ -36,36 +30,48 @@ def setUp(self): def tearDown(self): pass - def testGmFruit(self): + def test_set_addprop_attributes(self): + # setting a value that doesn't exist works because additional_properties_type allows any type + other_fruit = GmFruit(length_cm=self.length_cm, color=self.color) + blah = 'blah' + other_fruit['a'] = blah + assert other_fruit.a == blah + + # with setattr + setattr(other_fruit, 'b', blah) + assert other_fruit.b == blah + + self.assertEqual( + other_fruit.to_dict(), + { + 'a': 'blah', + 'b': 'blah', + 'length_cm': self.length_cm, + 'color': self.color + } + ) + + def test_banana_fruit(self): """Test GmFruit""" # make an instance of GmFruit, a composed schema anyOf model # banana test - length_cm = 20.3 - color = 'yellow' - fruit = GmFruit(length_cm=length_cm, color=color) + fruit = GmFruit(length_cm=self.length_cm, color=self.color) # check its properties - self.assertEqual(fruit.length_cm, length_cm) - self.assertEqual(fruit['length_cm'], length_cm) - self.assertEqual(getattr(fruit, 'length_cm'), length_cm) - self.assertEqual(fruit.color, color) - self.assertEqual(fruit['color'], color) - self.assertEqual(getattr(fruit, 'color'), color) + self.assertEqual(fruit.length_cm, self.length_cm) + self.assertEqual(fruit['length_cm'], self.length_cm) + self.assertEqual(getattr(fruit, 'length_cm'), self.length_cm) + self.assertEqual(fruit.color, self.color) + self.assertEqual(fruit['color'], self.color) + self.assertEqual(getattr(fruit, 'color'), self.color) # check the dict representation self.assertEqual( fruit.to_dict(), { - 'length_cm': length_cm, - 'color': color + 'length_cm': self.length_cm, + 'color': self.color } ) - # setting a value that doesn't exist raises an exception - # with a key - with self.assertRaises(AttributeError): - fruit['invalid_variable'] = 'some value' - # with setattr - with self.assertRaises(AttributeError): - setattr(fruit, 'invalid_variable', 'some value') # getting a value that doesn't exist raises an exception # with a key @@ -104,40 +110,22 @@ def testGmFruit(self): self.assertEqual( fruit._var_name_to_model_instances, { - 'color': [fruit], + 'color': [fruit, banana_instance], 'length_cm': [fruit, banana_instance], - 'cultivar': [fruit], - 'origin': [fruit], } ) - # model._additional_properties_model_instances stores a list of - # models which have the property additional_properties_type != None self.assertEqual( - fruit._additional_properties_model_instances, [] + fruit._additional_properties_model_instances, [fruit] ) - # if we modify one of the properties owned by multiple - # model_instances we get an exception when we try to access that - # property because the retrieved values are not all the same - banana_instance.length_cm = 4.56 - with self.assertRaises(petstore_api.ApiValueError): - some_length_cm = fruit.length_cm - - # including extra parameters raises an exception - with self.assertRaises(petstore_api.ApiValueError): - fruit = GmFruit( - color=color, - length_cm=length_cm, - unknown_property='some value' - ) - + def test_combo_fruit(self): # including input parameters for both anyOf instances works cultivar = 'banaple' color = 'orange' fruit = GmFruit( color=color, cultivar=cultivar, - length_cm=length_cm + length_cm=self.length_cm ) self.assertEqual(fruit.color, color) self.assertEqual(fruit['color'], color) @@ -145,9 +133,9 @@ def testGmFruit(self): self.assertEqual(fruit.cultivar, cultivar) self.assertEqual(fruit['cultivar'], cultivar) self.assertEqual(getattr(fruit, 'cultivar'), cultivar) - self.assertEqual(fruit.length_cm, length_cm) - self.assertEqual(fruit['length_cm'], length_cm) - self.assertEqual(getattr(fruit, 'length_cm'), length_cm) + self.assertEqual(fruit.length_cm, self.length_cm) + self.assertEqual(fruit['length_cm'], self.length_cm) + self.assertEqual(getattr(fruit, 'length_cm'), self.length_cm) # model._composed_instances is a list of the instances that were # made from the anyOf/allOf/OneOf classes in model._composed_schemas @@ -165,14 +153,16 @@ def testGmFruit(self): self.assertEqual( fruit._var_name_to_model_instances, { - 'color': [fruit], - 'length_cm': [fruit, banana_instance], - 'cultivar': [fruit, apple_instance], - 'origin': [fruit, apple_instance], + 'color': [fruit, apple_instance, banana_instance], + 'length_cm': [fruit, apple_instance, banana_instance], + 'cultivar': [fruit, apple_instance, banana_instance], } ) + self.assertEqual( + fruit._additional_properties_model_instances, [fruit] + ) - # make an instance of GmFruit, a composed schema anyOf model + def test_apple_fruit(self): # apple test color = 'red' cultivar = 'golden delicious' @@ -214,16 +204,13 @@ def testGmFruit(self): self.assertEqual( fruit._var_name_to_model_instances, { - 'color': [fruit], - 'length_cm': [fruit], + 'color': [fruit, apple_instance], 'cultivar': [fruit, apple_instance], 'origin': [fruit, apple_instance], } ) - # model._additional_properties_model_instances stores a list of - # models which have the property additional_properties_type != None self.assertEqual( - fruit._additional_properties_model_instances, [] + fruit._additional_properties_model_instances, [fruit] ) if __name__ == '__main__': diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_mole.py b/samples/openapi3/client/petstore/python/tests_manual/test_mole.py new file mode 100644 index 000000000000..fa8bf28c3088 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_mole.py @@ -0,0 +1,78 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest +from petstore_api.exceptions import ApiAttributeError + +import petstore_api + +try: + from petstore_api.model import mole +except ImportError: + mole = sys.modules["petstore_api.model.mole"] + + +class TestMole(unittest.TestCase): + """Triangle unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testMole(self): + # includes required parameters that are `readOnly=False` and not defined `readOnly` + my_mole = mole.Mole(smell="dirt", hearing=False) + assert my_mole.smell == "dirt" + assert my_mole.hearing is False + + # includes required parameters that `readOnly=False`, an optional `readOnly=False` and not defined `readOnly` + my_mole = mole.Mole(smell="dirt", taste="kfc", hearing=True) + assert my_mole.smell == "dirt" + assert my_mole.taste == "kfc" + assert my_mole.hearing is True + + # includes required parameters that `readOnly=False`, and required not defined `readOnly`, and an optional not defined + my_mole = mole.Mole(smell="dirt", seeing_ghosts=True, hearing=False) + assert my_mole.smell == "dirt" + assert my_mole.seeing_ghosts is True + assert my_mole.hearing is False + + # passing in required readOnly parameters raises an exception + with self.assertRaises(ApiAttributeError): + mole.Mole(smell="dirt", hearing=False, blind=True) + + # passing in optional readOnly parameters raises an exception + with self.assertRaises(ApiAttributeError): + mole.Mole(smell="dirt", hearing=False, touch=True) + + # passing in required an optional parameters with readOnly true or false works with from_openapi_data + my_mole = mole.Mole._from_openapi_data( + smell="dirt", + taste="kfc", + blind=True, + touch=False, + hearing=True, + seeing_ghosts=False, + ) + assert my_mole.smell == "dirt" + assert my_mole.taste == "kfc" + assert my_mole.blind is True + assert my_mole.touch is False + assert my_mole.hearing is True + assert my_mole.seeing_ghosts is False + + +if __name__ == "__main__": + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_object_model_with_ref_props.py b/samples/openapi3/client/petstore/python/tests_manual/test_object_model_with_ref_props.py index 9ce55c75bb87..c708237acb42 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_object_model_with_ref_props.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_object_model_with_ref_props.py @@ -20,6 +20,7 @@ number_with_validations = sys.modules[ 'petstore_api.model.number_with_validations'] from petstore_api.model.object_model_with_ref_props import ObjectModelWithRefProps +from petstore_api.model.readonly import Readonly class TestObjectModelWithRefProps(unittest.TestCase): @@ -38,6 +39,7 @@ def testObjectModelWithRefProps(self): ObjectModelWithRefProps.openapi_types, { 'my_number': (NumberWithValidations,), + 'my_readonly': (Readonly,), 'my_string': (str,), 'my_boolean': (bool,), } diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_tag.py b/samples/openapi3/client/petstore/python/tests_manual/test_tag.py new file mode 100644 index 000000000000..ec945f6b30b8 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests_manual/test_tag.py @@ -0,0 +1,35 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.tag import Tag + + +class TestTag(unittest.TestCase): + """Tag unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_can_ingest_additional_properties_in_tag(self): + t = Tag(a='abc') + assert t.a == 'abc' + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/typescript/builds/default/.openapi-generator/VERSION b/samples/openapi3/client/petstore/typescript/builds/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/typescript/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts index 12d711bd5b76..547125db4597 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts @@ -19,8 +19,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public async addPet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async addPet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -32,7 +32,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -57,7 +57,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -70,8 +70,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param petId Pet id to delete * @param apiKey */ - public async deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -85,7 +85,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -100,7 +100,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -113,8 +113,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'status' is not null or undefined if (status === null || status === undefined) { @@ -126,7 +126,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByStatus'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -143,7 +143,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -156,8 +156,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by tags * @param tags Tags to filter by */ - public async findPetsByTags(tags: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByTags(tags: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'tags' is not null or undefined if (tags === null || tags === undefined) { @@ -169,7 +169,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByTags'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -186,7 +186,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -199,8 +199,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Find pet by ID * @param petId ID of pet to return */ - public async getPetById(petId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getPetById(petId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -213,7 +213,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -227,7 +227,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -239,8 +239,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public async updatePet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -252,7 +252,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -277,7 +277,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -291,8 +291,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param name Updated name of the pet * @param status Updated status of the pet */ - public async updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -307,7 +307,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -331,7 +331,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -345,8 +345,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - let config = options || this.configuration; + public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -361,7 +361,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -385,7 +385,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/default/apis/StoreApi.ts b/samples/openapi3/client/petstore/typescript/builds/default/apis/StoreApi.ts index 12be01326978..7780dd52f48c 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/apis/StoreApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/apis/StoreApi.ts @@ -19,8 +19,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public async deleteOrder(orderId: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteOrder(orderId: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -33,7 +33,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -54,14 +54,14 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public async getInventory(options?: Configuration): Promise { - let config = options || this.configuration; + public async getInventory(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/store/inventory'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -75,7 +75,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -88,8 +88,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public async getOrderById(orderId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getOrderById(orderId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -102,7 +102,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -123,8 +123,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Place an order for a pet * @param order order placed for purchasing the pet */ - public async placeOrder(order: Order, options?: Configuration): Promise { - let config = options || this.configuration; + public async placeOrder(order: Order, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'order' is not null or undefined if (order === null || order === undefined) { @@ -136,7 +136,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/store/order'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params diff --git a/samples/openapi3/client/petstore/typescript/builds/default/apis/UserApi.ts b/samples/openapi3/client/petstore/typescript/builds/default/apis/UserApi.ts index 0717cb753040..e12b26fd31d9 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/apis/UserApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/apis/UserApi.ts @@ -19,8 +19,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Create user * @param user Created user object */ - public async createUser(user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUser(user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -32,7 +32,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -55,7 +55,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -67,8 +67,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -80,7 +80,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithArray'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -103,7 +103,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -115,8 +115,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithListInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithListInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -128,7 +128,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithList'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -151,7 +151,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -164,8 +164,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Delete user * @param username The name that needs to be deleted */ - public async deleteUser(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteUser(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -178,7 +178,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -192,7 +192,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -204,8 +204,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public async getUserByName(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async getUserByName(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -218,7 +218,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -240,8 +240,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username The user name for login * @param password The password for login in clear text */ - public async loginUser(username: string, password: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async loginUser(username: string, password: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -259,7 +259,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/login'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -285,14 +285,14 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { /** * Logs out current logged in user session */ - public async logoutUser(options?: Configuration): Promise { - let config = options || this.configuration; + public async logoutUser(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/user/logout'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -306,7 +306,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -320,8 +320,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username name that need to be deleted * @param user Updated user object */ - public async updateUser(username: string, user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async updateUser(username: string, user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -340,7 +340,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -363,7 +363,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/default/auth/auth.ts b/samples/openapi3/client/petstore/typescript/builds/default/auth/auth.ts index 9d59a0a25580..1f1d1ecac678 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/auth/auth.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/auth/auth.ts @@ -48,15 +48,19 @@ export class ApiKeyAuthentication implements SecurityAuthentication { * Applies oauth2 authentication to the request context. */ export class PetstoreAuthAuthentication implements SecurityAuthentication { - // TODO: How to handle oauth2 authentication! - public constructor() {} + /** + * Configures OAuth2 with the necessary properties + * + * @param accessToken: The access token to be used for every request + */ + public constructor(private accessToken: string) {} public getName(): string { return "petstore_auth"; } public applySecurityAuthentication(context: RequestContext) { - // TODO + context.setHeaderParam("Authorization", "Bearer " + this.accessToken); } } @@ -69,7 +73,7 @@ export type AuthMethods = { export type ApiKeyConfiguration = string; export type HttpBasicConfiguration = { "username": string, "password": string }; export type HttpBearerConfiguration = { tokenProvider: TokenProvider }; -export type OAuth2Configuration = string; +export type OAuth2Configuration = { accessToken: string }; export type AuthMethodsConfiguration = { "api_key"?: ApiKeyConfiguration, @@ -95,6 +99,7 @@ export function configureAuthMethods(config: AuthMethodsConfiguration | undefine if (config["petstore_auth"]) { authMethods["petstore_auth"] = new PetstoreAuthAuthentication( + config["petstore_auth"]["accessToken"] ); } diff --git a/samples/openapi3/client/petstore/typescript/builds/default/types/ObservableAPI.ts b/samples/openapi3/client/petstore/typescript/builds/default/types/ObservableAPI.ts index 459fbc8e226e..488915f871ba 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/types/ObservableAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/types/ObservableAPI.ts @@ -30,8 +30,8 @@ export class ObservablePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.addPet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -54,8 +54,8 @@ export class ObservablePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -78,8 +78,8 @@ export class ObservablePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByStatus(status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -102,8 +102,8 @@ export class ObservablePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByTags(tags, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -126,8 +126,8 @@ export class ObservablePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getPetById(petId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -149,8 +149,8 @@ export class ObservablePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -174,8 +174,8 @@ export class ObservablePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -199,8 +199,8 @@ export class ObservablePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -241,8 +241,8 @@ export class ObservableStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteOrder(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -264,8 +264,8 @@ export class ObservableStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Observable<{ [key: string]: number; }> { - const requestContextPromise = this.requestFactory.getInventory(options); + public getInventory(_options?: Configuration): Observable<{ [key: string]: number; }> { + const requestContextPromise = this.requestFactory.getInventory(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -288,8 +288,8 @@ export class ObservableStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getOrderById(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -311,8 +311,8 @@ export class ObservableStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.placeOrder(order, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -353,8 +353,8 @@ export class ObservableUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUser(user, options); + public createUser(user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUser(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -376,8 +376,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -399,8 +399,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithListInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -423,8 +423,8 @@ export class ObservableUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteUser(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -446,8 +446,8 @@ export class ObservableUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getUserByName(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -470,8 +470,8 @@ export class ObservableUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.loginUser(username, password, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -492,8 +492,8 @@ export class ObservableUserApi { /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.logoutUser(options); + public logoutUser(_options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.logoutUser(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -517,8 +517,8 @@ export class ObservableUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updateUser(username, user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); diff --git a/samples/openapi3/client/petstore/typescript/builds/default/types/PromiseAPI.ts b/samples/openapi3/client/petstore/typescript/builds/default/types/PromiseAPI.ts index 2129b103e7e7..ac44ba7a13b2 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/types/PromiseAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/types/PromiseAPI.ts @@ -26,8 +26,8 @@ export class PromisePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Promise { - const result = this.api.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.addPet(pet, _options); return result.toPromise(); } @@ -36,8 +36,8 @@ export class PromisePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - const result = this.api.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + const result = this.api.deletePet(petId, apiKey, _options); return result.toPromise(); } @@ -46,8 +46,8 @@ export class PromisePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise> { - const result = this.api.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise> { + const result = this.api.findPetsByStatus(status, _options); return result.toPromise(); } @@ -56,8 +56,8 @@ export class PromisePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Promise> { - const result = this.api.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Promise> { + const result = this.api.findPetsByTags(tags, _options); return result.toPromise(); } @@ -66,8 +66,8 @@ export class PromisePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Promise { - const result = this.api.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Promise { + const result = this.api.getPetById(petId, _options); return result.toPromise(); } @@ -75,8 +75,8 @@ export class PromisePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Promise { - const result = this.api.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.updatePet(pet, _options); return result.toPromise(); } @@ -86,8 +86,8 @@ export class PromisePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - const result = this.api.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + const result = this.api.updatePetWithForm(petId, name, status, _options); return result.toPromise(); } @@ -97,8 +97,8 @@ export class PromisePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - const result = this.api.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + const result = this.api.uploadFile(petId, additionalMetadata, file, _options); return result.toPromise(); } @@ -126,8 +126,8 @@ export class PromiseStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Promise { - const result = this.api.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Promise { + const result = this.api.deleteOrder(orderId, _options); return result.toPromise(); } @@ -135,8 +135,8 @@ export class PromiseStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Promise<{ [key: string]: number; }> { - const result = this.api.getInventory(options); + public getInventory(_options?: Configuration): Promise<{ [key: string]: number; }> { + const result = this.api.getInventory(_options); return result.toPromise(); } @@ -145,8 +145,8 @@ export class PromiseStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Promise { - const result = this.api.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Promise { + const result = this.api.getOrderById(orderId, _options); return result.toPromise(); } @@ -154,8 +154,8 @@ export class PromiseStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Promise { - const result = this.api.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Promise { + const result = this.api.placeOrder(order, _options); return result.toPromise(); } @@ -183,8 +183,8 @@ export class PromiseUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Promise { - const result = this.api.createUser(user, options); + public createUser(user: User, _options?: Configuration): Promise { + const result = this.api.createUser(user, _options); return result.toPromise(); } @@ -192,8 +192,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithArrayInput(user, _options); return result.toPromise(); } @@ -201,8 +201,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithListInput(user, _options); return result.toPromise(); } @@ -211,8 +211,8 @@ export class PromiseUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Promise { - const result = this.api.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Promise { + const result = this.api.deleteUser(username, _options); return result.toPromise(); } @@ -220,8 +220,8 @@ export class PromiseUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Promise { - const result = this.api.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Promise { + const result = this.api.getUserByName(username, _options); return result.toPromise(); } @@ -230,16 +230,16 @@ export class PromiseUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Promise { - const result = this.api.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Promise { + const result = this.api.loginUser(username, password, _options); return result.toPromise(); } /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Promise { - const result = this.api.logoutUser(options); + public logoutUser(_options?: Configuration): Promise { + const result = this.api.logoutUser(_options); return result.toPromise(); } @@ -249,8 +249,8 @@ export class PromiseUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Promise { - const result = this.api.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Promise { + const result = this.api.updateUser(username, user, _options); return result.toPromise(); } diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/.openapi-generator/VERSION b/samples/openapi3/client/petstore/typescript/builds/deno/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/typescript/builds/deno/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts index 552716b7cb33..cb9a2dfd3e6d 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts @@ -18,8 +18,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public async addPet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async addPet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -31,7 +31,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -56,7 +56,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -69,8 +69,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param petId Pet id to delete * @param apiKey */ - public async deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -84,7 +84,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -99,7 +99,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -112,8 +112,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'status' is not null or undefined if (status === null || status === undefined) { @@ -125,7 +125,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByStatus'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -142,7 +142,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -155,8 +155,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by tags * @param tags Tags to filter by */ - public async findPetsByTags(tags: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByTags(tags: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'tags' is not null or undefined if (tags === null || tags === undefined) { @@ -168,7 +168,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByTags'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -185,7 +185,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -198,8 +198,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Find pet by ID * @param petId ID of pet to return */ - public async getPetById(petId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getPetById(petId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -212,7 +212,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -226,7 +226,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -238,8 +238,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public async updatePet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -251,7 +251,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -276,7 +276,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -290,8 +290,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param name Updated name of the pet * @param status Updated status of the pet */ - public async updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -306,7 +306,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -330,7 +330,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -344,8 +344,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - let config = options || this.configuration; + public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -360,7 +360,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -384,7 +384,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/apis/StoreApi.ts b/samples/openapi3/client/petstore/typescript/builds/deno/apis/StoreApi.ts index f677c988a107..2cedbd705a65 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/apis/StoreApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/apis/StoreApi.ts @@ -18,8 +18,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public async deleteOrder(orderId: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteOrder(orderId: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -32,7 +32,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -53,14 +53,14 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public async getInventory(options?: Configuration): Promise { - let config = options || this.configuration; + public async getInventory(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/store/inventory'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -74,7 +74,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -87,8 +87,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public async getOrderById(orderId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getOrderById(orderId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -101,7 +101,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -122,8 +122,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Place an order for a pet * @param order order placed for purchasing the pet */ - public async placeOrder(order: Order, options?: Configuration): Promise { - let config = options || this.configuration; + public async placeOrder(order: Order, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'order' is not null or undefined if (order === null || order === undefined) { @@ -135,7 +135,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/store/order'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/apis/UserApi.ts b/samples/openapi3/client/petstore/typescript/builds/deno/apis/UserApi.ts index 3757165b71ae..7972e1605834 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/apis/UserApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/apis/UserApi.ts @@ -18,8 +18,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Create user * @param user Created user object */ - public async createUser(user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUser(user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -31,7 +31,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -54,7 +54,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -66,8 +66,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -79,7 +79,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithArray'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -102,7 +102,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -114,8 +114,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithListInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithListInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -127,7 +127,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithList'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -150,7 +150,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -163,8 +163,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Delete user * @param username The name that needs to be deleted */ - public async deleteUser(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteUser(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -177,7 +177,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -191,7 +191,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -203,8 +203,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public async getUserByName(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async getUserByName(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -217,7 +217,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -239,8 +239,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username The user name for login * @param password The password for login in clear text */ - public async loginUser(username: string, password: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async loginUser(username: string, password: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -258,7 +258,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/login'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -284,14 +284,14 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { /** * Logs out current logged in user session */ - public async logoutUser(options?: Configuration): Promise { - let config = options || this.configuration; + public async logoutUser(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/user/logout'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -305,7 +305,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -319,8 +319,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username name that need to be deleted * @param user Updated user object */ - public async updateUser(username: string, user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async updateUser(username: string, user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -339,7 +339,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -362,7 +362,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/auth/auth.ts b/samples/openapi3/client/petstore/typescript/builds/deno/auth/auth.ts index 0a02d2e58d2b..e7609dabbece 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/auth/auth.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/auth/auth.ts @@ -46,15 +46,19 @@ export class ApiKeyAuthentication implements SecurityAuthentication { * Applies oauth2 authentication to the request context. */ export class PetstoreAuthAuthentication implements SecurityAuthentication { - // TODO: How to handle oauth2 authentication! - public constructor() {} + /** + * Configures OAuth2 with the necessary properties + * + * @param accessToken: The access token to be used for every request + */ + public constructor(private accessToken: string) {} public getName(): string { return "petstore_auth"; } public applySecurityAuthentication(context: RequestContext) { - // TODO + context.setHeaderParam("Authorization", "Bearer " + this.accessToken); } } @@ -67,7 +71,7 @@ export type AuthMethods = { export type ApiKeyConfiguration = string; export type HttpBasicConfiguration = { "username": string, "password": string }; export type HttpBearerConfiguration = { tokenProvider: TokenProvider }; -export type OAuth2Configuration = string; +export type OAuth2Configuration = { accessToken: string }; export type AuthMethodsConfiguration = { "api_key"?: ApiKeyConfiguration, @@ -93,6 +97,7 @@ export function configureAuthMethods(config: AuthMethodsConfiguration | undefine if (config["petstore_auth"]) { authMethods["petstore_auth"] = new PetstoreAuthAuthentication( + config["petstore_auth"]["accessToken"] ); } diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/types/ObservableAPI.ts b/samples/openapi3/client/petstore/typescript/builds/deno/types/ObservableAPI.ts index 318c8a3e1bfa..cde73c04cc08 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/types/ObservableAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/types/ObservableAPI.ts @@ -30,8 +30,8 @@ export class ObservablePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.addPet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -54,8 +54,8 @@ export class ObservablePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -78,8 +78,8 @@ export class ObservablePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByStatus(status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -102,8 +102,8 @@ export class ObservablePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByTags(tags, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -126,8 +126,8 @@ export class ObservablePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getPetById(petId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -149,8 +149,8 @@ export class ObservablePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -174,8 +174,8 @@ export class ObservablePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -199,8 +199,8 @@ export class ObservablePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -241,8 +241,8 @@ export class ObservableStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteOrder(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -264,8 +264,8 @@ export class ObservableStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Observable<{ [key: string]: number; }> { - const requestContextPromise = this.requestFactory.getInventory(options); + public getInventory(_options?: Configuration): Observable<{ [key: string]: number; }> { + const requestContextPromise = this.requestFactory.getInventory(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -288,8 +288,8 @@ export class ObservableStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getOrderById(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -311,8 +311,8 @@ export class ObservableStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.placeOrder(order, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -353,8 +353,8 @@ export class ObservableUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUser(user, options); + public createUser(user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUser(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -376,8 +376,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -399,8 +399,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithListInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -423,8 +423,8 @@ export class ObservableUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteUser(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -446,8 +446,8 @@ export class ObservableUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getUserByName(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -470,8 +470,8 @@ export class ObservableUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.loginUser(username, password, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -492,8 +492,8 @@ export class ObservableUserApi { /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.logoutUser(options); + public logoutUser(_options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.logoutUser(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -517,8 +517,8 @@ export class ObservableUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updateUser(username, user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/types/PromiseAPI.ts b/samples/openapi3/client/petstore/typescript/builds/deno/types/PromiseAPI.ts index 5e2f7df97356..76db56cbc8bd 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/types/PromiseAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/types/PromiseAPI.ts @@ -26,8 +26,8 @@ export class PromisePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Promise { - const result = this.api.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.addPet(pet, _options); return result.toPromise(); } @@ -36,8 +36,8 @@ export class PromisePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - const result = this.api.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + const result = this.api.deletePet(petId, apiKey, _options); return result.toPromise(); } @@ -46,8 +46,8 @@ export class PromisePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise> { - const result = this.api.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise> { + const result = this.api.findPetsByStatus(status, _options); return result.toPromise(); } @@ -56,8 +56,8 @@ export class PromisePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Promise> { - const result = this.api.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Promise> { + const result = this.api.findPetsByTags(tags, _options); return result.toPromise(); } @@ -66,8 +66,8 @@ export class PromisePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Promise { - const result = this.api.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Promise { + const result = this.api.getPetById(petId, _options); return result.toPromise(); } @@ -75,8 +75,8 @@ export class PromisePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Promise { - const result = this.api.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.updatePet(pet, _options); return result.toPromise(); } @@ -86,8 +86,8 @@ export class PromisePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - const result = this.api.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + const result = this.api.updatePetWithForm(petId, name, status, _options); return result.toPromise(); } @@ -97,8 +97,8 @@ export class PromisePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - const result = this.api.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + const result = this.api.uploadFile(petId, additionalMetadata, file, _options); return result.toPromise(); } @@ -126,8 +126,8 @@ export class PromiseStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Promise { - const result = this.api.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Promise { + const result = this.api.deleteOrder(orderId, _options); return result.toPromise(); } @@ -135,8 +135,8 @@ export class PromiseStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Promise<{ [key: string]: number; }> { - const result = this.api.getInventory(options); + public getInventory(_options?: Configuration): Promise<{ [key: string]: number; }> { + const result = this.api.getInventory(_options); return result.toPromise(); } @@ -145,8 +145,8 @@ export class PromiseStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Promise { - const result = this.api.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Promise { + const result = this.api.getOrderById(orderId, _options); return result.toPromise(); } @@ -154,8 +154,8 @@ export class PromiseStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Promise { - const result = this.api.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Promise { + const result = this.api.placeOrder(order, _options); return result.toPromise(); } @@ -183,8 +183,8 @@ export class PromiseUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Promise { - const result = this.api.createUser(user, options); + public createUser(user: User, _options?: Configuration): Promise { + const result = this.api.createUser(user, _options); return result.toPromise(); } @@ -192,8 +192,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithArrayInput(user, _options); return result.toPromise(); } @@ -201,8 +201,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithListInput(user, _options); return result.toPromise(); } @@ -211,8 +211,8 @@ export class PromiseUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Promise { - const result = this.api.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Promise { + const result = this.api.deleteUser(username, _options); return result.toPromise(); } @@ -220,8 +220,8 @@ export class PromiseUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Promise { - const result = this.api.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Promise { + const result = this.api.getUserByName(username, _options); return result.toPromise(); } @@ -230,16 +230,16 @@ export class PromiseUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Promise { - const result = this.api.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Promise { + const result = this.api.loginUser(username, password, _options); return result.toPromise(); } /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Promise { - const result = this.api.logoutUser(options); + public logoutUser(_options?: Configuration): Promise { + const result = this.api.logoutUser(_options); return result.toPromise(); } @@ -249,8 +249,8 @@ export class PromiseUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Promise { - const result = this.api.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Promise { + const result = this.api.updateUser(username, user, _options); return result.toPromise(); } diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/.openapi-generator/VERSION b/samples/openapi3/client/petstore/typescript/builds/inversify/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts index 2225d19dbb9d..a127fccfbc21 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts @@ -21,8 +21,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public async addPet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async addPet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -34,7 +34,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -59,7 +59,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -72,8 +72,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param petId Pet id to delete * @param apiKey */ - public async deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -87,7 +87,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -102,7 +102,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -115,8 +115,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'status' is not null or undefined if (status === null || status === undefined) { @@ -128,7 +128,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByStatus'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -145,7 +145,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -158,8 +158,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by tags * @param tags Tags to filter by */ - public async findPetsByTags(tags: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByTags(tags: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'tags' is not null or undefined if (tags === null || tags === undefined) { @@ -171,7 +171,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByTags'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -188,7 +188,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -201,8 +201,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Find pet by ID * @param petId ID of pet to return */ - public async getPetById(petId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getPetById(petId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -215,7 +215,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -229,7 +229,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -241,8 +241,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public async updatePet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -254,7 +254,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -279,7 +279,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -293,8 +293,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param name Updated name of the pet * @param status Updated status of the pet */ - public async updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -309,7 +309,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -333,7 +333,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -347,8 +347,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - let config = options || this.configuration; + public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -363,7 +363,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -387,7 +387,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/StoreApi.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/StoreApi.ts index 836e9ba02618..3607b8dee6ec 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/StoreApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/StoreApi.ts @@ -21,8 +21,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public async deleteOrder(orderId: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteOrder(orderId: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -35,7 +35,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -56,14 +56,14 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public async getInventory(options?: Configuration): Promise { - let config = options || this.configuration; + public async getInventory(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/store/inventory'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -77,7 +77,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -90,8 +90,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public async getOrderById(orderId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getOrderById(orderId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -104,7 +104,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -125,8 +125,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Place an order for a pet * @param order order placed for purchasing the pet */ - public async placeOrder(order: Order, options?: Configuration): Promise { - let config = options || this.configuration; + public async placeOrder(order: Order, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'order' is not null or undefined if (order === null || order === undefined) { @@ -138,7 +138,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/store/order'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/UserApi.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/UserApi.ts index 5c68288c3811..cc4580ef34c9 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/UserApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/UserApi.ts @@ -21,8 +21,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Create user * @param user Created user object */ - public async createUser(user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUser(user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -34,7 +34,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -57,7 +57,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -69,8 +69,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -82,7 +82,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithArray'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -105,7 +105,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -117,8 +117,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithListInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithListInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -130,7 +130,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithList'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -153,7 +153,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -166,8 +166,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Delete user * @param username The name that needs to be deleted */ - public async deleteUser(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteUser(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -180,7 +180,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -194,7 +194,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -206,8 +206,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public async getUserByName(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async getUserByName(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -220,7 +220,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -242,8 +242,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username The user name for login * @param password The password for login in clear text */ - public async loginUser(username: string, password: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async loginUser(username: string, password: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -261,7 +261,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/login'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -287,14 +287,14 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { /** * Logs out current logged in user session */ - public async logoutUser(options?: Configuration): Promise { - let config = options || this.configuration; + public async logoutUser(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/user/logout'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -308,7 +308,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -322,8 +322,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username name that need to be deleted * @param user Updated user object */ - public async updateUser(username: string, user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async updateUser(username: string, user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -342,7 +342,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -365,7 +365,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/auth/auth.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/auth/auth.ts index 13e3b17fa825..f6ffebc4d7ee 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/auth/auth.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/auth/auth.ts @@ -56,15 +56,19 @@ export class ApiKeyAuthentication implements SecurityAuthentication { */ @injectable() export class PetstoreAuthAuthentication implements SecurityAuthentication { - // TODO: How to handle oauth2 authentication! - public constructor() {} + /** + * Configures OAuth2 with the necessary properties + * + * @param accessToken: The access token to be used for every request + */ + public constructor(private accessToken: string) {} public getName(): string { return "petstore_auth"; } public applySecurityAuthentication(context: RequestContext) { - // TODO + context.setHeaderParam("Authorization", "Bearer " + this.accessToken); } } @@ -82,7 +86,7 @@ export const authMethodServices = { export type ApiKeyConfiguration = string; export type HttpBasicConfiguration = { "username": string, "password": string }; export type HttpBearerConfiguration = { tokenProvider: TokenProvider }; -export type OAuth2Configuration = string; +export type OAuth2Configuration = { accessToken: string }; export type AuthMethodsConfiguration = { "api_key"?: ApiKeyConfiguration, @@ -108,6 +112,7 @@ export function configureAuthMethods(config: AuthMethodsConfiguration | undefine if (config["petstore_auth"]) { authMethods["petstore_auth"] = new PetstoreAuthAuthentication( + config["petstore_auth"]["accessToken"] ); } diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/types/ObservableAPI.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/types/ObservableAPI.ts index 555e2ce7273f..6ed7a67b5cbb 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/types/ObservableAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/types/ObservableAPI.ts @@ -35,8 +35,8 @@ export class ObservablePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.addPet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -59,8 +59,8 @@ export class ObservablePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -83,8 +83,8 @@ export class ObservablePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByStatus(status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -107,8 +107,8 @@ export class ObservablePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByTags(tags, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -131,8 +131,8 @@ export class ObservablePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getPetById(petId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -154,8 +154,8 @@ export class ObservablePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -179,8 +179,8 @@ export class ObservablePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -204,8 +204,8 @@ export class ObservablePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -249,8 +249,8 @@ export class ObservableStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteOrder(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -272,8 +272,8 @@ export class ObservableStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Observable<{ [key: string]: number; }> { - const requestContextPromise = this.requestFactory.getInventory(options); + public getInventory(_options?: Configuration): Observable<{ [key: string]: number; }> { + const requestContextPromise = this.requestFactory.getInventory(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -296,8 +296,8 @@ export class ObservableStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getOrderById(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -319,8 +319,8 @@ export class ObservableStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.placeOrder(order, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -364,8 +364,8 @@ export class ObservableUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUser(user, options); + public createUser(user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUser(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -387,8 +387,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -410,8 +410,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithListInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -434,8 +434,8 @@ export class ObservableUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteUser(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -457,8 +457,8 @@ export class ObservableUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getUserByName(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -481,8 +481,8 @@ export class ObservableUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.loginUser(username, password, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -503,8 +503,8 @@ export class ObservableUserApi { /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.logoutUser(options); + public logoutUser(_options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.logoutUser(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -528,8 +528,8 @@ export class ObservableUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updateUser(username, user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/types/PromiseAPI.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/types/PromiseAPI.ts index f58fad865e13..a6135ddbd244 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/types/PromiseAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/types/PromiseAPI.ts @@ -31,8 +31,8 @@ export class PromisePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Promise { - const result = this.api.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.addPet(pet, _options); return result.toPromise(); } @@ -41,8 +41,8 @@ export class PromisePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - const result = this.api.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + const result = this.api.deletePet(petId, apiKey, _options); return result.toPromise(); } @@ -51,8 +51,8 @@ export class PromisePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise> { - const result = this.api.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise> { + const result = this.api.findPetsByStatus(status, _options); return result.toPromise(); } @@ -61,8 +61,8 @@ export class PromisePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Promise> { - const result = this.api.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Promise> { + const result = this.api.findPetsByTags(tags, _options); return result.toPromise(); } @@ -71,8 +71,8 @@ export class PromisePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Promise { - const result = this.api.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Promise { + const result = this.api.getPetById(petId, _options); return result.toPromise(); } @@ -80,8 +80,8 @@ export class PromisePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Promise { - const result = this.api.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.updatePet(pet, _options); return result.toPromise(); } @@ -91,8 +91,8 @@ export class PromisePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - const result = this.api.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + const result = this.api.updatePetWithForm(petId, name, status, _options); return result.toPromise(); } @@ -102,8 +102,8 @@ export class PromisePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - const result = this.api.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + const result = this.api.uploadFile(petId, additionalMetadata, file, _options); return result.toPromise(); } @@ -134,8 +134,8 @@ export class PromiseStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Promise { - const result = this.api.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Promise { + const result = this.api.deleteOrder(orderId, _options); return result.toPromise(); } @@ -143,8 +143,8 @@ export class PromiseStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Promise<{ [key: string]: number; }> { - const result = this.api.getInventory(options); + public getInventory(_options?: Configuration): Promise<{ [key: string]: number; }> { + const result = this.api.getInventory(_options); return result.toPromise(); } @@ -153,8 +153,8 @@ export class PromiseStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Promise { - const result = this.api.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Promise { + const result = this.api.getOrderById(orderId, _options); return result.toPromise(); } @@ -162,8 +162,8 @@ export class PromiseStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Promise { - const result = this.api.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Promise { + const result = this.api.placeOrder(order, _options); return result.toPromise(); } @@ -194,8 +194,8 @@ export class PromiseUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Promise { - const result = this.api.createUser(user, options); + public createUser(user: User, _options?: Configuration): Promise { + const result = this.api.createUser(user, _options); return result.toPromise(); } @@ -203,8 +203,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithArrayInput(user, _options); return result.toPromise(); } @@ -212,8 +212,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithListInput(user, _options); return result.toPromise(); } @@ -222,8 +222,8 @@ export class PromiseUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Promise { - const result = this.api.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Promise { + const result = this.api.deleteUser(username, _options); return result.toPromise(); } @@ -231,8 +231,8 @@ export class PromiseUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Promise { - const result = this.api.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Promise { + const result = this.api.getUserByName(username, _options); return result.toPromise(); } @@ -241,16 +241,16 @@ export class PromiseUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Promise { - const result = this.api.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Promise { + const result = this.api.loginUser(username, password, _options); return result.toPromise(); } /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Promise { - const result = this.api.logoutUser(options); + public logoutUser(_options?: Configuration): Promise { + const result = this.api.logoutUser(_options); return result.toPromise(); } @@ -260,8 +260,8 @@ export class PromiseUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Promise { - const result = this.api.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Promise { + const result = this.api.updateUser(username, user, _options); return result.toPromise(); } diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/.openapi-generator/VERSION b/samples/openapi3/client/petstore/typescript/builds/jquery/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts index 0e0db9ad8eec..8cf33634c312 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts @@ -18,8 +18,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public async addPet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async addPet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -31,7 +31,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -56,7 +56,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -69,8 +69,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param petId Pet id to delete * @param apiKey */ - public async deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -84,7 +84,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -99,7 +99,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -112,8 +112,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'status' is not null or undefined if (status === null || status === undefined) { @@ -125,7 +125,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByStatus'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -142,7 +142,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -155,8 +155,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by tags * @param tags Tags to filter by */ - public async findPetsByTags(tags: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByTags(tags: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'tags' is not null or undefined if (tags === null || tags === undefined) { @@ -168,7 +168,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByTags'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -185,7 +185,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -198,8 +198,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Find pet by ID * @param petId ID of pet to return */ - public async getPetById(petId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getPetById(petId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -212,7 +212,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -226,7 +226,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -238,8 +238,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public async updatePet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -251,7 +251,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -276,7 +276,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -290,8 +290,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param name Updated name of the pet * @param status Updated status of the pet */ - public async updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -306,7 +306,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -330,7 +330,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -344,8 +344,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - let config = options || this.configuration; + public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -360,7 +360,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -384,7 +384,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/StoreApi.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/StoreApi.ts index 9ada7b0fee1f..5ca1dd79b3d2 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/StoreApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/StoreApi.ts @@ -18,8 +18,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public async deleteOrder(orderId: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteOrder(orderId: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -32,7 +32,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -53,14 +53,14 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public async getInventory(options?: Configuration): Promise { - let config = options || this.configuration; + public async getInventory(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/store/inventory'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -74,7 +74,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -87,8 +87,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public async getOrderById(orderId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getOrderById(orderId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -101,7 +101,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -122,8 +122,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Place an order for a pet * @param order order placed for purchasing the pet */ - public async placeOrder(order: Order, options?: Configuration): Promise { - let config = options || this.configuration; + public async placeOrder(order: Order, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'order' is not null or undefined if (order === null || order === undefined) { @@ -135,7 +135,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/store/order'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/UserApi.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/UserApi.ts index f705cc52a124..79bed0455cae 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/UserApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/UserApi.ts @@ -18,8 +18,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Create user * @param user Created user object */ - public async createUser(user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUser(user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -31,7 +31,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -54,7 +54,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -66,8 +66,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -79,7 +79,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithArray'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -102,7 +102,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -114,8 +114,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithListInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithListInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -127,7 +127,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithList'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -150,7 +150,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -163,8 +163,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Delete user * @param username The name that needs to be deleted */ - public async deleteUser(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteUser(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -177,7 +177,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -191,7 +191,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -203,8 +203,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public async getUserByName(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async getUserByName(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -217,7 +217,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -239,8 +239,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username The user name for login * @param password The password for login in clear text */ - public async loginUser(username: string, password: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async loginUser(username: string, password: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -258,7 +258,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/login'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -284,14 +284,14 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { /** * Logs out current logged in user session */ - public async logoutUser(options?: Configuration): Promise { - let config = options || this.configuration; + public async logoutUser(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/user/logout'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -305,7 +305,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -319,8 +319,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username name that need to be deleted * @param user Updated user object */ - public async updateUser(username: string, user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async updateUser(username: string, user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -339,7 +339,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -362,7 +362,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/auth/auth.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/auth/auth.ts index 2cdf0800f32a..d8924a4216c2 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/auth/auth.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/auth/auth.ts @@ -46,15 +46,19 @@ export class ApiKeyAuthentication implements SecurityAuthentication { * Applies oauth2 authentication to the request context. */ export class PetstoreAuthAuthentication implements SecurityAuthentication { - // TODO: How to handle oauth2 authentication! - public constructor() {} + /** + * Configures OAuth2 with the necessary properties + * + * @param accessToken: The access token to be used for every request + */ + public constructor(private accessToken: string) {} public getName(): string { return "petstore_auth"; } public applySecurityAuthentication(context: RequestContext) { - // TODO + context.setHeaderParam("Authorization", "Bearer " + this.accessToken); } } @@ -67,7 +71,7 @@ export type AuthMethods = { export type ApiKeyConfiguration = string; export type HttpBasicConfiguration = { "username": string, "password": string }; export type HttpBearerConfiguration = { tokenProvider: TokenProvider }; -export type OAuth2Configuration = string; +export type OAuth2Configuration = { accessToken: string }; export type AuthMethodsConfiguration = { "api_key"?: ApiKeyConfiguration, @@ -93,6 +97,7 @@ export function configureAuthMethods(config: AuthMethodsConfiguration | undefine if (config["petstore_auth"]) { authMethods["petstore_auth"] = new PetstoreAuthAuthentication( + config["petstore_auth"]["accessToken"] ); } diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/types/ObservableAPI.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/types/ObservableAPI.ts index 459fbc8e226e..488915f871ba 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/types/ObservableAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/types/ObservableAPI.ts @@ -30,8 +30,8 @@ export class ObservablePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.addPet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -54,8 +54,8 @@ export class ObservablePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -78,8 +78,8 @@ export class ObservablePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByStatus(status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -102,8 +102,8 @@ export class ObservablePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByTags(tags, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -126,8 +126,8 @@ export class ObservablePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getPetById(petId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -149,8 +149,8 @@ export class ObservablePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -174,8 +174,8 @@ export class ObservablePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -199,8 +199,8 @@ export class ObservablePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -241,8 +241,8 @@ export class ObservableStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteOrder(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -264,8 +264,8 @@ export class ObservableStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Observable<{ [key: string]: number; }> { - const requestContextPromise = this.requestFactory.getInventory(options); + public getInventory(_options?: Configuration): Observable<{ [key: string]: number; }> { + const requestContextPromise = this.requestFactory.getInventory(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -288,8 +288,8 @@ export class ObservableStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getOrderById(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -311,8 +311,8 @@ export class ObservableStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.placeOrder(order, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -353,8 +353,8 @@ export class ObservableUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUser(user, options); + public createUser(user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUser(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -376,8 +376,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -399,8 +399,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithListInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -423,8 +423,8 @@ export class ObservableUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteUser(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -446,8 +446,8 @@ export class ObservableUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getUserByName(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -470,8 +470,8 @@ export class ObservableUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.loginUser(username, password, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -492,8 +492,8 @@ export class ObservableUserApi { /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.logoutUser(options); + public logoutUser(_options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.logoutUser(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -517,8 +517,8 @@ export class ObservableUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updateUser(username, user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/types/PromiseAPI.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/types/PromiseAPI.ts index 2129b103e7e7..ac44ba7a13b2 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/types/PromiseAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/types/PromiseAPI.ts @@ -26,8 +26,8 @@ export class PromisePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Promise { - const result = this.api.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.addPet(pet, _options); return result.toPromise(); } @@ -36,8 +36,8 @@ export class PromisePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - const result = this.api.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + const result = this.api.deletePet(petId, apiKey, _options); return result.toPromise(); } @@ -46,8 +46,8 @@ export class PromisePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise> { - const result = this.api.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise> { + const result = this.api.findPetsByStatus(status, _options); return result.toPromise(); } @@ -56,8 +56,8 @@ export class PromisePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Promise> { - const result = this.api.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Promise> { + const result = this.api.findPetsByTags(tags, _options); return result.toPromise(); } @@ -66,8 +66,8 @@ export class PromisePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Promise { - const result = this.api.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Promise { + const result = this.api.getPetById(petId, _options); return result.toPromise(); } @@ -75,8 +75,8 @@ export class PromisePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Promise { - const result = this.api.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.updatePet(pet, _options); return result.toPromise(); } @@ -86,8 +86,8 @@ export class PromisePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - const result = this.api.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + const result = this.api.updatePetWithForm(petId, name, status, _options); return result.toPromise(); } @@ -97,8 +97,8 @@ export class PromisePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - const result = this.api.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + const result = this.api.uploadFile(petId, additionalMetadata, file, _options); return result.toPromise(); } @@ -126,8 +126,8 @@ export class PromiseStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Promise { - const result = this.api.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Promise { + const result = this.api.deleteOrder(orderId, _options); return result.toPromise(); } @@ -135,8 +135,8 @@ export class PromiseStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Promise<{ [key: string]: number; }> { - const result = this.api.getInventory(options); + public getInventory(_options?: Configuration): Promise<{ [key: string]: number; }> { + const result = this.api.getInventory(_options); return result.toPromise(); } @@ -145,8 +145,8 @@ export class PromiseStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Promise { - const result = this.api.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Promise { + const result = this.api.getOrderById(orderId, _options); return result.toPromise(); } @@ -154,8 +154,8 @@ export class PromiseStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Promise { - const result = this.api.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Promise { + const result = this.api.placeOrder(order, _options); return result.toPromise(); } @@ -183,8 +183,8 @@ export class PromiseUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Promise { - const result = this.api.createUser(user, options); + public createUser(user: User, _options?: Configuration): Promise { + const result = this.api.createUser(user, _options); return result.toPromise(); } @@ -192,8 +192,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithArrayInput(user, _options); return result.toPromise(); } @@ -201,8 +201,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithListInput(user, _options); return result.toPromise(); } @@ -211,8 +211,8 @@ export class PromiseUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Promise { - const result = this.api.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Promise { + const result = this.api.deleteUser(username, _options); return result.toPromise(); } @@ -220,8 +220,8 @@ export class PromiseUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Promise { - const result = this.api.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Promise { + const result = this.api.getUserByName(username, _options); return result.toPromise(); } @@ -230,16 +230,16 @@ export class PromiseUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Promise { - const result = this.api.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Promise { + const result = this.api.loginUser(username, password, _options); return result.toPromise(); } /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Promise { - const result = this.api.logoutUser(options); + public logoutUser(_options?: Configuration): Promise { + const result = this.api.logoutUser(_options); return result.toPromise(); } @@ -249,8 +249,8 @@ export class PromiseUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Promise { - const result = this.api.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Promise { + const result = this.api.updateUser(username, user, _options); return result.toPromise(); } diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/.openapi-generator/VERSION b/samples/openapi3/client/petstore/typescript/builds/object_params/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/PetApi.ts index 12d711bd5b76..547125db4597 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/PetApi.ts @@ -19,8 +19,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public async addPet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async addPet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -32,7 +32,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -57,7 +57,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -70,8 +70,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param petId Pet id to delete * @param apiKey */ - public async deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -85,7 +85,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -100,7 +100,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -113,8 +113,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'status' is not null or undefined if (status === null || status === undefined) { @@ -126,7 +126,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByStatus'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -143,7 +143,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -156,8 +156,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Finds Pets by tags * @param tags Tags to filter by */ - public async findPetsByTags(tags: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async findPetsByTags(tags: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'tags' is not null or undefined if (tags === null || tags === undefined) { @@ -169,7 +169,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet/findByTags'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -186,7 +186,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -199,8 +199,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Find pet by ID * @param petId ID of pet to return */ - public async getPetById(petId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getPetById(petId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -213,7 +213,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -227,7 +227,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -239,8 +239,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public async updatePet(pet: Pet, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'pet' is not null or undefined if (pet === null || pet === undefined) { @@ -252,7 +252,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/pet'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -277,7 +277,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -291,8 +291,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param name Updated name of the pet * @param status Updated status of the pet */ - public async updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -307,7 +307,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -331,7 +331,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -345,8 +345,8 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - let config = options || this.configuration; + public async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { @@ -361,7 +361,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'petId' + '}', encodeURIComponent(String(petId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -385,7 +385,7 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["petstore_auth"] + authMethod = _config.authMethods["petstore_auth"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/StoreApi.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/StoreApi.ts index 12be01326978..7780dd52f48c 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/StoreApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/StoreApi.ts @@ -19,8 +19,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public async deleteOrder(orderId: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteOrder(orderId: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -33,7 +33,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -54,14 +54,14 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public async getInventory(options?: Configuration): Promise { - let config = options || this.configuration; + public async getInventory(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/store/inventory'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -75,7 +75,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -88,8 +88,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public async getOrderById(orderId: number, options?: Configuration): Promise { - let config = options || this.configuration; + public async getOrderById(orderId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { @@ -102,7 +102,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -123,8 +123,8 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { * Place an order for a pet * @param order order placed for purchasing the pet */ - public async placeOrder(order: Order, options?: Configuration): Promise { - let config = options || this.configuration; + public async placeOrder(order: Order, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'order' is not null or undefined if (order === null || order === undefined) { @@ -136,7 +136,7 @@ export class StoreApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/store/order'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/UserApi.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/UserApi.ts index 0717cb753040..e12b26fd31d9 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/apis/UserApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/apis/UserApi.ts @@ -19,8 +19,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Create user * @param user Created user object */ - public async createUser(user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUser(user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -32,7 +32,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -55,7 +55,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -67,8 +67,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -80,7 +80,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithArray'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -103,7 +103,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -115,8 +115,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Creates list of users with given input array * @param user List of user object */ - public async createUsersWithListInput(user: Array, options?: Configuration): Promise { - let config = options || this.configuration; + public async createUsersWithListInput(user: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { @@ -128,7 +128,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/createWithList'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -151,7 +151,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -164,8 +164,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Delete user * @param username The name that needs to be deleted */ - public async deleteUser(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async deleteUser(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -178,7 +178,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -192,7 +192,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -204,8 +204,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public async getUserByName(username: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async getUserByName(username: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -218,7 +218,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -240,8 +240,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username The user name for login * @param password The password for login in clear text */ - public async loginUser(username: string, password: string, options?: Configuration): Promise { - let config = options || this.configuration; + public async loginUser(username: string, password: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -259,7 +259,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { const localVarPath = '/user/login'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -285,14 +285,14 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { /** * Logs out current logged in user session */ - public async logoutUser(options?: Configuration): Promise { - let config = options || this.configuration; + public async logoutUser(_options?: Configuration): Promise { + let _config = _options || this.configuration; // Path Params const localVarPath = '/user/logout'; // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -306,7 +306,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } @@ -320,8 +320,8 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { * @param username name that need to be deleted * @param user Updated user object */ - public async updateUser(username: string, user: User, options?: Configuration): Promise { - let config = options || this.configuration; + public async updateUser(username: string, user: User, _options?: Configuration): Promise { + let _config = _options || this.configuration; // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { @@ -340,7 +340,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { .replace('{' + 'username' + '}', encodeURIComponent(String(username))); // Make Request Context - const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") // Query Params @@ -363,7 +363,7 @@ export class UserApiRequestFactory extends BaseAPIRequestFactory { let authMethod = null; // Apply auth methods - authMethod = config.authMethods["api_key"] + authMethod = _config.authMethods["api_key"] if (authMethod) { await authMethod.applySecurityAuthentication(requestContext); } diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/auth/auth.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/auth/auth.ts index 9d59a0a25580..1f1d1ecac678 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/auth/auth.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/auth/auth.ts @@ -48,15 +48,19 @@ export class ApiKeyAuthentication implements SecurityAuthentication { * Applies oauth2 authentication to the request context. */ export class PetstoreAuthAuthentication implements SecurityAuthentication { - // TODO: How to handle oauth2 authentication! - public constructor() {} + /** + * Configures OAuth2 with the necessary properties + * + * @param accessToken: The access token to be used for every request + */ + public constructor(private accessToken: string) {} public getName(): string { return "petstore_auth"; } public applySecurityAuthentication(context: RequestContext) { - // TODO + context.setHeaderParam("Authorization", "Bearer " + this.accessToken); } } @@ -69,7 +73,7 @@ export type AuthMethods = { export type ApiKeyConfiguration = string; export type HttpBasicConfiguration = { "username": string, "password": string }; export type HttpBearerConfiguration = { tokenProvider: TokenProvider }; -export type OAuth2Configuration = string; +export type OAuth2Configuration = { accessToken: string }; export type AuthMethodsConfiguration = { "api_key"?: ApiKeyConfiguration, @@ -95,6 +99,7 @@ export function configureAuthMethods(config: AuthMethodsConfiguration | undefine if (config["petstore_auth"]) { authMethods["petstore_auth"] = new PetstoreAuthAuthentication( + config["petstore_auth"]["accessToken"] ); } diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/types/ObservableAPI.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/types/ObservableAPI.ts index 459fbc8e226e..488915f871ba 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/types/ObservableAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/types/ObservableAPI.ts @@ -30,8 +30,8 @@ export class ObservablePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.addPet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -54,8 +54,8 @@ export class ObservablePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deletePet(petId, apiKey, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -78,8 +78,8 @@ export class ObservablePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByStatus(status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -102,8 +102,8 @@ export class ObservablePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Observable> { - const requestContextPromise = this.requestFactory.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Observable> { + const requestContextPromise = this.requestFactory.findPetsByTags(tags, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -126,8 +126,8 @@ export class ObservablePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getPetById(petId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -149,8 +149,8 @@ export class ObservablePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePet(pet, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -174,8 +174,8 @@ export class ObservablePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updatePetWithForm(petId, name, status, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -199,8 +199,8 @@ export class ObservablePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.uploadFile(petId, additionalMetadata, file, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -241,8 +241,8 @@ export class ObservableStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteOrder(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -264,8 +264,8 @@ export class ObservableStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Observable<{ [key: string]: number; }> { - const requestContextPromise = this.requestFactory.getInventory(options); + public getInventory(_options?: Configuration): Observable<{ [key: string]: number; }> { + const requestContextPromise = this.requestFactory.getInventory(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -288,8 +288,8 @@ export class ObservableStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getOrderById(orderId, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -311,8 +311,8 @@ export class ObservableStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.placeOrder(order, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -353,8 +353,8 @@ export class ObservableUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUser(user, options); + public createUser(user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUser(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -376,8 +376,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithArrayInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -399,8 +399,8 @@ export class ObservableUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.createUsersWithListInput(user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -423,8 +423,8 @@ export class ObservableUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.deleteUser(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -446,8 +446,8 @@ export class ObservableUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.getUserByName(username, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -470,8 +470,8 @@ export class ObservableUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.loginUser(username, password, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -492,8 +492,8 @@ export class ObservableUserApi { /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.logoutUser(options); + public logoutUser(_options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.logoutUser(_options); // build promise chain let middlewarePreObservable = from(requestContextPromise); @@ -517,8 +517,8 @@ export class ObservableUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Observable { - const requestContextPromise = this.requestFactory.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Observable { + const requestContextPromise = this.requestFactory.updateUser(username, user, _options); // build promise chain let middlewarePreObservable = from(requestContextPromise); diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/types/PromiseAPI.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/types/PromiseAPI.ts index 2129b103e7e7..ac44ba7a13b2 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/types/PromiseAPI.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/types/PromiseAPI.ts @@ -26,8 +26,8 @@ export class PromisePetApi { * Add a new pet to the store * @param pet Pet object that needs to be added to the store */ - public addPet(pet: Pet, options?: Configuration): Promise { - const result = this.api.addPet(pet, options); + public addPet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.addPet(pet, _options); return result.toPromise(); } @@ -36,8 +36,8 @@ export class PromisePetApi { * @param petId Pet id to delete * @param apiKey */ - public deletePet(petId: number, apiKey?: string, options?: Configuration): Promise { - const result = this.api.deletePet(petId, apiKey, options); + public deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + const result = this.api.deletePet(petId, apiKey, _options); return result.toPromise(); } @@ -46,8 +46,8 @@ export class PromisePetApi { * Finds Pets by status * @param status Status values that need to be considered for filter */ - public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise> { - const result = this.api.findPetsByStatus(status, options); + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise> { + const result = this.api.findPetsByStatus(status, _options); return result.toPromise(); } @@ -56,8 +56,8 @@ export class PromisePetApi { * Finds Pets by tags * @param tags Tags to filter by */ - public findPetsByTags(tags: Array, options?: Configuration): Promise> { - const result = this.api.findPetsByTags(tags, options); + public findPetsByTags(tags: Array, _options?: Configuration): Promise> { + const result = this.api.findPetsByTags(tags, _options); return result.toPromise(); } @@ -66,8 +66,8 @@ export class PromisePetApi { * Find pet by ID * @param petId ID of pet to return */ - public getPetById(petId: number, options?: Configuration): Promise { - const result = this.api.getPetById(petId, options); + public getPetById(petId: number, _options?: Configuration): Promise { + const result = this.api.getPetById(petId, _options); return result.toPromise(); } @@ -75,8 +75,8 @@ export class PromisePetApi { * Update an existing pet * @param pet Pet object that needs to be added to the store */ - public updatePet(pet: Pet, options?: Configuration): Promise { - const result = this.api.updatePet(pet, options); + public updatePet(pet: Pet, _options?: Configuration): Promise { + const result = this.api.updatePet(pet, _options); return result.toPromise(); } @@ -86,8 +86,8 @@ export class PromisePetApi { * @param name Updated name of the pet * @param status Updated status of the pet */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise { - const result = this.api.updatePetWithForm(petId, name, status, options); + public updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + const result = this.api.updatePetWithForm(petId, name, status, _options); return result.toPromise(); } @@ -97,8 +97,8 @@ export class PromisePetApi { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise { - const result = this.api.uploadFile(petId, additionalMetadata, file, options); + public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + const result = this.api.uploadFile(petId, additionalMetadata, file, _options); return result.toPromise(); } @@ -126,8 +126,8 @@ export class PromiseStoreApi { * Delete purchase order by ID * @param orderId ID of the order that needs to be deleted */ - public deleteOrder(orderId: string, options?: Configuration): Promise { - const result = this.api.deleteOrder(orderId, options); + public deleteOrder(orderId: string, _options?: Configuration): Promise { + const result = this.api.deleteOrder(orderId, _options); return result.toPromise(); } @@ -135,8 +135,8 @@ export class PromiseStoreApi { * Returns a map of status codes to quantities * Returns pet inventories by status */ - public getInventory(options?: Configuration): Promise<{ [key: string]: number; }> { - const result = this.api.getInventory(options); + public getInventory(_options?: Configuration): Promise<{ [key: string]: number; }> { + const result = this.api.getInventory(_options); return result.toPromise(); } @@ -145,8 +145,8 @@ export class PromiseStoreApi { * Find purchase order by ID * @param orderId ID of pet that needs to be fetched */ - public getOrderById(orderId: number, options?: Configuration): Promise { - const result = this.api.getOrderById(orderId, options); + public getOrderById(orderId: number, _options?: Configuration): Promise { + const result = this.api.getOrderById(orderId, _options); return result.toPromise(); } @@ -154,8 +154,8 @@ export class PromiseStoreApi { * Place an order for a pet * @param order order placed for purchasing the pet */ - public placeOrder(order: Order, options?: Configuration): Promise { - const result = this.api.placeOrder(order, options); + public placeOrder(order: Order, _options?: Configuration): Promise { + const result = this.api.placeOrder(order, _options); return result.toPromise(); } @@ -183,8 +183,8 @@ export class PromiseUserApi { * Create user * @param user Created user object */ - public createUser(user: User, options?: Configuration): Promise { - const result = this.api.createUser(user, options); + public createUser(user: User, _options?: Configuration): Promise { + const result = this.api.createUser(user, _options); return result.toPromise(); } @@ -192,8 +192,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithArrayInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithArrayInput(user, options); + public createUsersWithArrayInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithArrayInput(user, _options); return result.toPromise(); } @@ -201,8 +201,8 @@ export class PromiseUserApi { * Creates list of users with given input array * @param user List of user object */ - public createUsersWithListInput(user: Array, options?: Configuration): Promise { - const result = this.api.createUsersWithListInput(user, options); + public createUsersWithListInput(user: Array, _options?: Configuration): Promise { + const result = this.api.createUsersWithListInput(user, _options); return result.toPromise(); } @@ -211,8 +211,8 @@ export class PromiseUserApi { * Delete user * @param username The name that needs to be deleted */ - public deleteUser(username: string, options?: Configuration): Promise { - const result = this.api.deleteUser(username, options); + public deleteUser(username: string, _options?: Configuration): Promise { + const result = this.api.deleteUser(username, _options); return result.toPromise(); } @@ -220,8 +220,8 @@ export class PromiseUserApi { * Get user by user name * @param username The name that needs to be fetched. Use user1 for testing. */ - public getUserByName(username: string, options?: Configuration): Promise { - const result = this.api.getUserByName(username, options); + public getUserByName(username: string, _options?: Configuration): Promise { + const result = this.api.getUserByName(username, _options); return result.toPromise(); } @@ -230,16 +230,16 @@ export class PromiseUserApi { * @param username The user name for login * @param password The password for login in clear text */ - public loginUser(username: string, password: string, options?: Configuration): Promise { - const result = this.api.loginUser(username, password, options); + public loginUser(username: string, password: string, _options?: Configuration): Promise { + const result = this.api.loginUser(username, password, _options); return result.toPromise(); } /** * Logs out current logged in user session */ - public logoutUser(options?: Configuration): Promise { - const result = this.api.logoutUser(options); + public logoutUser(_options?: Configuration): Promise { + const result = this.api.logoutUser(_options); return result.toPromise(); } @@ -249,8 +249,8 @@ export class PromiseUserApi { * @param username name that need to be deleted * @param user Updated user object */ - public updateUser(username: string, user: User, options?: Configuration): Promise { - const result = this.api.updateUser(username, user, options); + public updateUser(username: string, user: User, _options?: Configuration): Promise { + const result = this.api.updateUser(username, user, _options); return result.toPromise(); } diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/.openapi-generator/FILES b/samples/openapi3/server/petstore/php-mezzio-ph/.openapi-generator/FILES deleted file mode 100644 index fd268242a0e6..000000000000 --- a/samples/openapi3/server/petstore/php-mezzio-ph/.openapi-generator/FILES +++ /dev/null @@ -1,36 +0,0 @@ -.gitignore -README.md -application/config.yml -application/config/app.yml -application/config/data_transfer.yml -application/config/path_handler.yml -application/container.php -composer.json -public/index.php -src/App/DTO/ApiResponse.php -src/App/DTO/Category.php -src/App/DTO/FindPetsByStatusQueryData.php -src/App/DTO/FindPetsByTagsQueryData.php -src/App/DTO/InlineObject.php -src/App/DTO/InlineObject1.php -src/App/DTO/LoginUserQueryData.php -src/App/DTO/Order.php -src/App/DTO/Pet.php -src/App/DTO/Tag.php -src/App/DTO/User.php -src/App/Factory.php -src/App/Handler/Pet.php -src/App/Handler/PetFindByStatus.php -src/App/Handler/PetFindByTags.php -src/App/Handler/PetPetId.php -src/App/Handler/PetPetIdUploadImage.php -src/App/Handler/StoreInventory.php -src/App/Handler/StoreOrder.php -src/App/Handler/StoreOrderOrderId.php -src/App/Handler/User.php -src/App/Handler/UserCreateWithArray.php -src/App/Handler/UserCreateWithList.php -src/App/Handler/UserLogin.php -src/App/Handler/UserLogout.php -src/App/Handler/UserUsername.php -src/App/Middleware/InternalServerError.php diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/.openapi-generator/VERSION b/samples/openapi3/server/petstore/php-mezzio-ph/.openapi-generator/VERSION deleted file mode 100644 index d99e7162d01f..000000000000 --- a/samples/openapi3/server/petstore/php-mezzio-ph/.openapi-generator/VERSION +++ /dev/null @@ -1 +0,0 @@ -5.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/composer.json b/samples/openapi3/server/petstore/php-mezzio-ph/composer.json deleted file mode 100644 index 54f8e97226c6..000000000000 --- a/samples/openapi3/server/petstore/php-mezzio-ph/composer.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "git_user_id/git_repo_id", - "description": "", - "license": "unlicense", - "version": "1.0.0", - "type": "project", - "require": { - "php": "^7.2", - "ext-yaml": "^2.0", - "mezzio/mezzio": "^3.2", - "laminas/laminas-diactoros": "^2.1", - "articus/path-handler": "^0.6", - "articus/data-transfer": "^0.4", - "articus/openapi-generator-common": "^0.1", - "doctrine/annotations": "^1.10", - "psr/simple-cache": "^1.0", - "laminas/laminas-config": "^3.4", - "laminas/laminas-stdlib": "^3.2", - "laminas/laminas-validator": "^2.13", - "nikic/fast-route": "^1.3" - }, - "autoload": { - "psr-4": { - "": "src/" - } - } -} \ No newline at end of file diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/DTO/ApiResponse.php b/samples/openapi3/server/petstore/php-mezzio-ph/src/App/DTO/ApiResponse.php deleted file mode 100644 index a08cb2c92757..000000000000 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/DTO/ApiResponse.php +++ /dev/null @@ -1,31 +0,0 @@ -getAttribute("bodyData"); - throw new PHException\HttpCode(501, "Not implemented"); - } - /** - * Update an existing pet - * @PHA\Put() - * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="application/json") - * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="application/xml") - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":\App\DTO\Pet::class,"objectAttr":"bodyData"}) - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/xml") - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/json") - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented - * - * @return \App\DTO\Pet - */ - public function updatePet(ServerRequestInterface $request): \App\DTO\Pet - { - //TODO implement method - /** @var \App\DTO\Pet $bodyData */ - $bodyData = $request->getAttribute("bodyData"); - throw new PHException\HttpCode(501, "Not implemented"); - } -} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByStatus.php b/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByStatus.php deleted file mode 100644 index c1c1ce754007..000000000000 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByStatus.php +++ /dev/null @@ -1,44 +0,0 @@ -getAttribute("queryData"); - throw new PHException\HttpCode(501, "Not implemented"); - } -} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByTags.php b/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByTags.php deleted file mode 100644 index b722a310efb0..000000000000 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByTags.php +++ /dev/null @@ -1,44 +0,0 @@ -getAttribute("queryData"); - throw new PHException\HttpCode(501, "Not implemented"); - } -} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreOrder.php b/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreOrder.php deleted file mode 100644 index be6af69243aa..000000000000 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreOrder.php +++ /dev/null @@ -1,41 +0,0 @@ -getAttribute("bodyData"); - throw new PHException\HttpCode(501, "Not implemented"); - } -} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserLogin.php b/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserLogin.php deleted file mode 100644 index 577e7c3f5629..000000000000 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserLogin.php +++ /dev/null @@ -1,43 +0,0 @@ -getAttribute("queryData"); - throw new PHException\HttpCode(501, "Not implemented"); - } -} diff --git a/samples/schema/petstore/ktorm/.openapi-generator/VERSION b/samples/schema/petstore/ktorm/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/schema/petstore/ktorm/.openapi-generator/VERSION +++ b/samples/schema/petstore/ktorm/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/schema/petstore/mysql/.openapi-generator/VERSION b/samples/schema/petstore/mysql/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/schema/petstore/mysql/.openapi-generator/VERSION +++ b/samples/schema/petstore/mysql/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/schema/petstore/wsdl-schema/.openapi-generator-ignore b/samples/schema/petstore/wsdl-schema/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/schema/petstore/wsdl-schema/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/schema/petstore/wsdl-schema/.openapi-generator/FILES b/samples/schema/petstore/wsdl-schema/.openapi-generator/FILES new file mode 100644 index 000000000000..94285c6e2aae --- /dev/null +++ b/samples/schema/petstore/wsdl-schema/.openapi-generator/FILES @@ -0,0 +1,2 @@ +jaxb-customization.xml +service.wsdl diff --git a/samples/schema/petstore/wsdl-schema/.openapi-generator/VERSION b/samples/schema/petstore/wsdl-schema/.openapi-generator/VERSION new file mode 100644 index 000000000000..6555596f9311 --- /dev/null +++ b/samples/schema/petstore/wsdl-schema/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/schema/petstore/wsdl-schema/jaxb-customization.xml b/samples/schema/petstore/wsdl-schema/jaxb-customization.xml new file mode 100644 index 000000000000..0ae533ccb5f4 --- /dev/null +++ b/samples/schema/petstore/wsdl-schema/jaxb-customization.xml @@ -0,0 +1,28 @@ + + + + true + false + + + + + + + + + + + + + + + + + + diff --git a/samples/schema/petstore/wsdl-schema/service.wsdl b/samples/schema/petstore/wsdl-schema/service.wsdl new file mode 100644 index 000000000000..68ce9752d724 --- /dev/null +++ b/samples/schema/petstore/wsdl-schema/service.wsdl @@ -0,0 +1,1158 @@ + + + + + + + + + Invalid input + + + + + + + Invalid ID supplied + + + + + Pet not found + + + + + + + Invalid status value + + + + + + + Invalid tag value + + + + + + + Invalid ID supplied + + + + + Pet not found + + + + + + + Invalid ID supplied + + + + + Pet not found + + + + + Validation exception + + + + + + + Invalid input + + + + + + + + + Invalid ID supplied + + + + + Order not found + + + + + + + + + Invalid ID supplied + + + + + Order not found + + + + + + + Invalid Order + + + + + + + + + + + + + Invalid username supplied + + + + + User not found + + + + + + + Invalid username supplied + + + + + User not found + + + + + + + Invalid username/password supplied + + + + + + + + + Invalid user supplied + + + + + User not found + + + + + + + + + + + + + + + + + + + + + + + + Order Status + + + + + + + + + + + + + + + pet status in the store + + + + + + + + + + + + + + + + + + + + + + User Status + + + + + + + Order Status + + + + + + + + + + pet status in the store + + + + + + + + + + + + + + + + + + + Pet object that needs to be added to the store + + + + + + + + + Pet id to delete + + + + + + + + + + Status values that need to be considered for filter + + + + + + + + + successful operation + + + + + + + + + Tags to filter by + + + + + + + + + successful operation + + + + + + + + + ID of pet to return + + + + + + + + + successful operation + + + + + + + + + Pet object that needs to be added to the store + + + + + + + + + ID of pet that needs to be updated + + + + + Updated name of the pet + + + + + Updated status of the pet + + + + + + + + + ID of pet to update + + + + + Additional data to pass to server + + + + + file to upload + + + + + + + + + successful operation + + + + + + + + + + ID of the order that needs to be deleted + + + + + + + + + + + + + + successful operation + + + + + + + + + + ID of pet that needs to be fetched + + + + + + + + + + + + + + successful operation + + + + + + + + + order placed for purchasing the pet + + + + + + + + + successful operation + + + + + + + + + Created user object + + + + + + + + + successful operation + + + + + + + + + List of user object + + + + + + + + + successful operation + + + + + + + + + List of user object + + + + + + + + + successful operation + + + + + + + + + The name that needs to be deleted + + + + + + + + + The name that needs to be fetched. Use user1 for testing. + + + + + + + + + successful operation + + + + + + + + + The user name for login + + + + + The password for login in clear text + + + + + + + + + successful operation + + + + + + + + + + successful operation + + + + + + + + + name that need to be updated + + + + + Updated user object + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Add a new pet to the store + + + Invalid input + + + + Deletes a pet + + + Invalid ID supplied + + + Pet not found + + + + Multiple status values can be provided with comma separated strings + + + successful operation + + + Invalid status value + + + + Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + + + successful operation + + + Invalid tag value + + + + Returns a single pet + + + successful operation + + + Invalid ID supplied + + + Pet not found + + + + Update an existing pet + + + Invalid ID supplied + + + Pet not found + + + Validation exception + + + + Updates a pet in the store with form data + + + Invalid input + + + + uploads an image + + + successful operation + + + + For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + + + Invalid ID supplied + + + Order not found + + + + Returns a map of status codes to quantities + + + successful operation + + + + For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + + + successful operation + + + Invalid ID supplied + + + Order not found + + + + Place an order for a pet + + + successful operation + + + Invalid Order + + + + This can only be done by the logged in user. + + + successful operation + + + + Creates list of users with given input array + + + successful operation + + + + Creates list of users with given input array + + + successful operation + + + + This can only be done by the logged in user. + + + Invalid username supplied + + + User not found + + + + Get user by user name + + + successful operation + + + Invalid username supplied + + + User not found + + + + Logs user into the system + + + successful operation + + + Invalid username/password supplied + + + + Logs out current logged in user session + + + successful operation + + + + This can only be done by the logged in user. + + + Invalid user supplied + + + User not found + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + + + + + \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-3.0/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-3.0/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/aspnetcore-3.0/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-3.0/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-3.1/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-3.1/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/aspnetcore-3.1/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-3.1/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-5.0/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-5.0/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/aspnetcore-5.0/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-5.0/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/aspnetcore/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/cpp-pistache/.openapi-generator/VERSION b/samples/server/petstore/cpp-pistache/.openapi-generator/VERSION index c30f0ec2be7f..6555596f9311 100644 --- a/samples/server/petstore/cpp-pistache/.openapi-generator/VERSION +++ b/samples/server/petstore/cpp-pistache/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.0-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/cpp-pistache/api/PetApi.cpp b/samples/server/petstore/cpp-pistache/api/PetApi.cpp index 80e15bd68625..7b3641599eef 100644 --- a/samples/server/petstore/cpp-pistache/api/PetApi.cpp +++ b/samples/server/petstore/cpp-pistache/api/PetApi.cpp @@ -13,16 +13,17 @@ #include "PetApi.h" #include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace api { +namespace org::openapitools::server::api +{ using namespace org::openapitools::server::helpers; using namespace org::openapitools::server::model; -PetApi::PetApi(std::shared_ptr rtr) { - router = rtr; +const std::string PetApi::base = "/v2"; + +PetApi::PetApi(const std::shared_ptr& rtr) + : router(rtr) +{ } void PetApi::init() { @@ -45,30 +46,58 @@ void PetApi::setupRoutes() { router->addCustomHandler(Routes::bind(&PetApi::pet_api_default_handler, this)); } +std::pair PetApi::handleParsingException(const std::exception& ex) const noexcept +{ + try { + throw ex; + } catch (nlohmann::detail::exception &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } catch (org::openapitools::server::helpers::ValidationException &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } +} + +std::pair PetApi::handleOperationException(const std::exception& ex) const noexcept +{ + return std::make_pair(Pistache::Http::Code::Internal_Server_Error, ex.what()); +} + void PetApi::add_pet_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the body param Pet body; try { - nlohmann::json::parse(request.body()).get_to(body); - this->add_pet(body, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); + nlohmann::json::parse(request.body()).get_to(body); + body.validate(); + } catch (std::exception &e) { + const std::pair errorInfo = this->handleParsingException(e); + response.send(errorInfo.first, errorInfo.second); return; + } + + try { + this->add_pet(body, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void PetApi::delete_pet_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the path params auto petId = request.param(":petId").as(); @@ -76,22 +105,24 @@ void PetApi::delete_pet_handler(const Pistache::Rest::Request &request, Pistache auto apiKey = request.headers().tryGetRaw("api_key"); try { - this->delete_pet(petId, apiKey, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->delete_pet(petId, apiKey, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void PetApi::find_pets_by_status_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the query params auto statusQuery = request.query().get("status"); @@ -104,22 +135,24 @@ void PetApi::find_pets_by_status_handler(const Pistache::Rest::Request &request, } try { - this->find_pets_by_status(status, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->find_pets_by_status(status, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void PetApi::find_pets_by_tags_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the query params auto tagsQuery = request.query().get("tags"); @@ -132,105 +165,118 @@ void PetApi::find_pets_by_tags_handler(const Pistache::Rest::Request &request, P } try { - this->find_pets_by_tags(tags, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->find_pets_by_tags(tags, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void PetApi::get_pet_by_id_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the path params auto petId = request.param(":petId").as(); try { - this->get_pet_by_id(petId, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->get_pet_by_id(petId, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void PetApi::update_pet_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the body param Pet body; try { - nlohmann::json::parse(request.body()).get_to(body); - this->update_pet(body, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); + nlohmann::json::parse(request.body()).get_to(body); + body.validate(); + } catch (std::exception &e) { + const std::pair errorInfo = this->handleParsingException(e); + response.send(errorInfo.first, errorInfo.second); return; + } + + try { + this->update_pet(body, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void PetApi::update_pet_with_form_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + try { this->update_pet_with_form(request, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void PetApi::upload_file_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + try { this->upload_file(request, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void PetApi::pet_api_default_handler(const Pistache::Rest::Request &, Pistache::Http::ResponseWriter response) { response.send(Pistache::Http::Code::Not_Found, "The requested method does not exist"); } -} -} -} -} +} // namespace org::openapitools::server::api diff --git a/samples/server/petstore/cpp-pistache/api/PetApi.h b/samples/server/petstore/cpp-pistache/api/PetApi.h index d991d13abaed..f689a0675e15 100644 --- a/samples/server/petstore/cpp-pistache/api/PetApi.h +++ b/samples/server/petstore/cpp-pistache/api/PetApi.h @@ -24,25 +24,22 @@ #include #include +#include #include "ApiResponse.h" #include "Pet.h" #include -namespace org { -namespace openapitools { -namespace server { -namespace api { - -using namespace org::openapitools::server::model; +namespace org::openapitools::server::api +{ class PetApi { public: - PetApi(std::shared_ptr); - virtual ~PetApi() {} + explicit PetApi(const std::shared_ptr& rtr); + virtual ~PetApi() = default; void init(); - const std::string base = "/v2"; + static const std::string base; private: void setupRoutes(); @@ -57,7 +54,19 @@ class PetApi { void upload_file_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response); void pet_api_default_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response); - std::shared_ptr router; + const std::shared_ptr router; + + /// + /// Helper function to handle unexpected Exceptions during Parameter parsing and validation. + /// May be overriden to return custom error formats. + /// + virtual std::pair handleParsingException(const std::exception& ex) const noexcept; + + /// + /// Helper function to handle unexpected Exceptions during processing of the request in handler functions. + /// May be overriden to return custom error formats. + /// + virtual std::pair handleOperationException(const std::exception& ex) const noexcept; /// /// Add a new pet to the store @@ -66,8 +75,7 @@ class PetApi { /// /// /// Pet object that needs to be added to the store - virtual void add_pet(const Pet &body, Pistache::Http::ResponseWriter &response) = 0; - + virtual void add_pet(const org::openapitools::server::model::Pet &body, Pistache::Http::ResponseWriter &response) = 0; /// /// Deletes a pet /// @@ -77,7 +85,6 @@ class PetApi { /// Pet id to delete /// (optional, default to "") virtual void delete_pet(const int64_t &petId, const Pistache::Optional &apiKey, Pistache::Http::ResponseWriter &response) = 0; - /// /// Finds Pets by status /// @@ -86,7 +93,6 @@ class PetApi { /// /// Status values that need to be considered for filter virtual void find_pets_by_status(const Pistache::Optional> &status, Pistache::Http::ResponseWriter &response) = 0; - /// /// Finds Pets by tags /// @@ -95,7 +101,6 @@ class PetApi { /// /// Tags to filter by virtual void find_pets_by_tags(const Pistache::Optional> &tags, Pistache::Http::ResponseWriter &response) = 0; - /// /// Find pet by ID /// @@ -104,7 +109,6 @@ class PetApi { /// /// ID of pet to return virtual void get_pet_by_id(const int64_t &petId, Pistache::Http::ResponseWriter &response) = 0; - /// /// Update an existing pet /// @@ -112,8 +116,7 @@ class PetApi { /// /// /// Pet object that needs to be added to the store - virtual void update_pet(const Pet &body, Pistache::Http::ResponseWriter &response) = 0; - + virtual void update_pet(const org::openapitools::server::model::Pet &body, Pistache::Http::ResponseWriter &response) = 0; /// /// Updates a pet in the store with form data /// @@ -121,7 +124,6 @@ class PetApi { /// /// virtual void update_pet_with_form(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter &response) = 0; - /// /// uploads an image /// @@ -132,10 +134,7 @@ class PetApi { }; -} -} -} -} +} // namespace org::openapitools::server::api #endif /* PetApi_H_ */ diff --git a/samples/server/petstore/cpp-pistache/api/StoreApi.cpp b/samples/server/petstore/cpp-pistache/api/StoreApi.cpp index e3f1038f80a4..ea0c0e1793b8 100644 --- a/samples/server/petstore/cpp-pistache/api/StoreApi.cpp +++ b/samples/server/petstore/cpp-pistache/api/StoreApi.cpp @@ -13,16 +13,17 @@ #include "StoreApi.h" #include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace api { +namespace org::openapitools::server::api +{ using namespace org::openapitools::server::helpers; using namespace org::openapitools::server::model; -StoreApi::StoreApi(std::shared_ptr rtr) { - router = rtr; +const std::string StoreApi::base = "/v2"; + +StoreApi::StoreApi(const std::shared_ptr& rtr) + : router(rtr) +{ } void StoreApi::init() { @@ -41,94 +42,123 @@ void StoreApi::setupRoutes() { router->addCustomHandler(Routes::bind(&StoreApi::store_api_default_handler, this)); } +std::pair StoreApi::handleParsingException(const std::exception& ex) const noexcept +{ + try { + throw ex; + } catch (nlohmann::detail::exception &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } catch (org::openapitools::server::helpers::ValidationException &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } +} + +std::pair StoreApi::handleOperationException(const std::exception& ex) const noexcept +{ + return std::make_pair(Pistache::Http::Code::Internal_Server_Error, ex.what()); +} + void StoreApi::delete_order_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the path params auto orderId = request.param(":orderId").as(); try { - this->delete_order(orderId, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->delete_order(orderId, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void StoreApi::get_inventory_handler(const Pistache::Rest::Request &, Pistache::Http::ResponseWriter response) { + try { + try { - this->get_inventory(response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->get_inventory(response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void StoreApi::get_order_by_id_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the path params auto orderId = request.param(":orderId").as(); try { - this->get_order_by_id(orderId, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->get_order_by_id(orderId, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void StoreApi::place_order_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the body param Order body; try { - nlohmann::json::parse(request.body()).get_to(body); - this->place_order(body, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); + nlohmann::json::parse(request.body()).get_to(body); + body.validate(); + } catch (std::exception &e) { + const std::pair errorInfo = this->handleParsingException(e); + response.send(errorInfo.first, errorInfo.second); return; + } + + try { + this->place_order(body, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void StoreApi::store_api_default_handler(const Pistache::Rest::Request &, Pistache::Http::ResponseWriter response) { response.send(Pistache::Http::Code::Not_Found, "The requested method does not exist"); } -} -} -} -} +} // namespace org::openapitools::server::api diff --git a/samples/server/petstore/cpp-pistache/api/StoreApi.h b/samples/server/petstore/cpp-pistache/api/StoreApi.h index f69875c4678d..6eb224387479 100644 --- a/samples/server/petstore/cpp-pistache/api/StoreApi.h +++ b/samples/server/petstore/cpp-pistache/api/StoreApi.h @@ -24,25 +24,22 @@ #include #include +#include #include "Order.h" #include #include -namespace org { -namespace openapitools { -namespace server { -namespace api { - -using namespace org::openapitools::server::model; +namespace org::openapitools::server::api +{ class StoreApi { public: - StoreApi(std::shared_ptr); - virtual ~StoreApi() {} + explicit StoreApi(const std::shared_ptr& rtr); + virtual ~StoreApi() = default; void init(); - const std::string base = "/v2"; + static const std::string base; private: void setupRoutes(); @@ -53,7 +50,19 @@ class StoreApi { void place_order_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response); void store_api_default_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response); - std::shared_ptr router; + const std::shared_ptr router; + + /// + /// Helper function to handle unexpected Exceptions during Parameter parsing and validation. + /// May be overriden to return custom error formats. + /// + virtual std::pair handleParsingException(const std::exception& ex) const noexcept; + + /// + /// Helper function to handle unexpected Exceptions during processing of the request in handler functions. + /// May be overriden to return custom error formats. + /// + virtual std::pair handleOperationException(const std::exception& ex) const noexcept; /// /// Delete purchase order by ID @@ -63,7 +72,6 @@ class StoreApi { /// /// ID of the order that needs to be deleted virtual void delete_order(const std::string &orderId, Pistache::Http::ResponseWriter &response) = 0; - /// /// Returns pet inventories by status /// @@ -71,7 +79,6 @@ class StoreApi { /// Returns a map of status codes to quantities /// virtual void get_inventory(Pistache::Http::ResponseWriter &response) = 0; - /// /// Find purchase order by ID /// @@ -80,7 +87,6 @@ class StoreApi { /// /// ID of pet that needs to be fetched virtual void get_order_by_id(const int64_t &orderId, Pistache::Http::ResponseWriter &response) = 0; - /// /// Place an order for a pet /// @@ -88,14 +94,11 @@ class StoreApi { /// /// /// order placed for purchasing the pet - virtual void place_order(const Order &body, Pistache::Http::ResponseWriter &response) = 0; + virtual void place_order(const org::openapitools::server::model::Order &body, Pistache::Http::ResponseWriter &response) = 0; }; -} -} -} -} +} // namespace org::openapitools::server::api #endif /* StoreApi_H_ */ diff --git a/samples/server/petstore/cpp-pistache/api/UserApi.cpp b/samples/server/petstore/cpp-pistache/api/UserApi.cpp index 93d275611d71..94903581dc4d 100644 --- a/samples/server/petstore/cpp-pistache/api/UserApi.cpp +++ b/samples/server/petstore/cpp-pistache/api/UserApi.cpp @@ -13,16 +13,17 @@ #include "UserApi.h" #include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace api { +namespace org::openapitools::server::api +{ using namespace org::openapitools::server::helpers; using namespace org::openapitools::server::model; -UserApi::UserApi(std::shared_ptr rtr) { - router = rtr; +const std::string UserApi::base = "/v2"; + +UserApi::UserApi(const std::shared_ptr& rtr) + : router(rtr) +{ } void UserApi::init() { @@ -45,114 +46,166 @@ void UserApi::setupRoutes() { router->addCustomHandler(Routes::bind(&UserApi::user_api_default_handler, this)); } +std::pair UserApi::handleParsingException(const std::exception& ex) const noexcept +{ + try { + throw ex; + } catch (nlohmann::detail::exception &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } catch (org::openapitools::server::helpers::ValidationException &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } +} + +std::pair UserApi::handleOperationException(const std::exception& ex) const noexcept +{ + return std::make_pair(Pistache::Http::Code::Internal_Server_Error, ex.what()); +} + void UserApi::create_user_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the body param User body; try { - nlohmann::json::parse(request.body()).get_to(body); - this->create_user(body, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); + nlohmann::json::parse(request.body()).get_to(body); + body.validate(); + } catch (std::exception &e) { + const std::pair errorInfo = this->handleParsingException(e); + response.send(errorInfo.first, errorInfo.second); return; + } + + try { + this->create_user(body, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void UserApi::create_users_with_array_input_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the body param std::vector body; try { - nlohmann::json::parse(request.body()).get_to(body); - this->create_users_with_array_input(body, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); + nlohmann::json::parse(request.body()).get_to(body); + body.validate(); + } catch (std::exception &e) { + const std::pair errorInfo = this->handleParsingException(e); + response.send(errorInfo.first, errorInfo.second); return; + } + + try { + this->create_users_with_array_input(body, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void UserApi::create_users_with_list_input_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the body param std::vector body; try { - nlohmann::json::parse(request.body()).get_to(body); - this->create_users_with_list_input(body, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); + nlohmann::json::parse(request.body()).get_to(body); + body.validate(); + } catch (std::exception &e) { + const std::pair errorInfo = this->handleParsingException(e); + response.send(errorInfo.first, errorInfo.second); return; + } + + try { + this->create_users_with_list_input(body, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void UserApi::delete_user_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the path params auto username = request.param(":username").as(); try { - this->delete_user(username, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->delete_user(username, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void UserApi::get_user_by_name_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the path params auto username = request.param(":username").as(); try { - this->get_user_by_name(username, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->get_user_by_name(username, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void UserApi::login_user_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the query params auto usernameQuery = request.query().get("username"); @@ -173,40 +226,44 @@ void UserApi::login_user_handler(const Pistache::Rest::Request &request, Pistach } try { - this->login_user(username, password, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->login_user(username, password, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void UserApi::logout_user_handler(const Pistache::Rest::Request &, Pistache::Http::ResponseWriter response) { + try { + try { - this->logout_user(response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); - return; + this->logout_user(response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void UserApi::update_user_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response) { + try { + // Getting the path params auto username = request.param(":username").as(); @@ -215,29 +272,34 @@ void UserApi::update_user_handler(const Pistache::Rest::Request &request, Pistac User body; try { - nlohmann::json::parse(request.body()).get_to(body); - this->update_user(username, body, response); - } catch (nlohmann::detail::exception &e) { - //send a 400 error - response.send(Pistache::Http::Code::Bad_Request, e.what()); + nlohmann::json::parse(request.body()).get_to(body); + body.validate(); + } catch (std::exception &e) { + const std::pair errorInfo = this->handleParsingException(e); + response.send(errorInfo.first, errorInfo.second); return; + } + + try { + this->update_user(username, body, response); } catch (Pistache::Http::HttpError &e) { response.send(static_cast(e.code()), e.what()); return; } catch (std::exception &e) { - //send a 500 error - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + const std::pair errorInfo = this->handleOperationException(e); + response.send(errorInfo.first, errorInfo.second); return; } + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + } void UserApi::user_api_default_handler(const Pistache::Rest::Request &, Pistache::Http::ResponseWriter response) { response.send(Pistache::Http::Code::Not_Found, "The requested method does not exist"); } -} -} -} -} +} // namespace org::openapitools::server::api diff --git a/samples/server/petstore/cpp-pistache/api/UserApi.h b/samples/server/petstore/cpp-pistache/api/UserApi.h index 6c589979dbc9..003b6db4df41 100644 --- a/samples/server/petstore/cpp-pistache/api/UserApi.h +++ b/samples/server/petstore/cpp-pistache/api/UserApi.h @@ -24,25 +24,22 @@ #include #include +#include #include "User.h" #include #include -namespace org { -namespace openapitools { -namespace server { -namespace api { - -using namespace org::openapitools::server::model; +namespace org::openapitools::server::api +{ class UserApi { public: - UserApi(std::shared_ptr); - virtual ~UserApi() {} + explicit UserApi(const std::shared_ptr& rtr); + virtual ~UserApi() = default; void init(); - const std::string base = "/v2"; + static const std::string base; private: void setupRoutes(); @@ -57,7 +54,19 @@ class UserApi { void update_user_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response); void user_api_default_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response); - std::shared_ptr router; + const std::shared_ptr router; + + /// + /// Helper function to handle unexpected Exceptions during Parameter parsing and validation. + /// May be overriden to return custom error formats. + /// + virtual std::pair handleParsingException(const std::exception& ex) const noexcept; + + /// + /// Helper function to handle unexpected Exceptions during processing of the request in handler functions. + /// May be overriden to return custom error formats. + /// + virtual std::pair handleOperationException(const std::exception& ex) const noexcept; /// /// Create user @@ -66,8 +75,7 @@ class UserApi { /// This can only be done by the logged in user. /// /// Created user object - virtual void create_user(const User &body, Pistache::Http::ResponseWriter &response) = 0; - + virtual void create_user(const org::openapitools::server::model::User &body, Pistache::Http::ResponseWriter &response) = 0; /// /// Creates list of users with given input array /// @@ -76,7 +84,6 @@ class UserApi { /// /// List of user object virtual void create_users_with_array_input(const std::vector &body, Pistache::Http::ResponseWriter &response) = 0; - /// /// Creates list of users with given input array /// @@ -85,7 +92,6 @@ class UserApi { /// /// List of user object virtual void create_users_with_list_input(const std::vector &body, Pistache::Http::ResponseWriter &response) = 0; - /// /// Delete user /// @@ -94,7 +100,6 @@ class UserApi { /// /// The name that needs to be deleted virtual void delete_user(const std::string &username, Pistache::Http::ResponseWriter &response) = 0; - /// /// Get user by user name /// @@ -103,7 +108,6 @@ class UserApi { /// /// The name that needs to be fetched. Use user1 for testing. virtual void get_user_by_name(const std::string &username, Pistache::Http::ResponseWriter &response) = 0; - /// /// Logs user into the system /// @@ -113,7 +117,6 @@ class UserApi { /// The user name for login /// The password for login in clear text virtual void login_user(const Pistache::Optional &username, const Pistache::Optional &password, Pistache::Http::ResponseWriter &response) = 0; - /// /// Logs out current logged in user session /// @@ -121,7 +124,6 @@ class UserApi { /// /// virtual void logout_user(Pistache::Http::ResponseWriter &response) = 0; - /// /// Updated user /// @@ -130,14 +132,11 @@ class UserApi { /// /// name that need to be deleted /// Updated user object - virtual void update_user(const std::string &username, const User &body, Pistache::Http::ResponseWriter &response) = 0; + virtual void update_user(const std::string &username, const org::openapitools::server::model::User &body, Pistache::Http::ResponseWriter &response) = 0; }; -} -} -} -} +} // namespace org::openapitools::server::api #endif /* UserApi_H_ */ diff --git a/samples/server/petstore/cpp-pistache/impl/PetApiImpl.cpp b/samples/server/petstore/cpp-pistache/impl/PetApiImpl.cpp index 778117a18bbe..94b49b151e4e 100644 --- a/samples/server/petstore/cpp-pistache/impl/PetApiImpl.cpp +++ b/samples/server/petstore/cpp-pistache/impl/PetApiImpl.cpp @@ -19,9 +19,10 @@ namespace api { using namespace org::openapitools::server::model; -PetApiImpl::PetApiImpl(std::shared_ptr rtr) +PetApiImpl::PetApiImpl(const std::shared_ptr& rtr) : PetApi(rtr) - { } +{ +} void PetApiImpl::add_pet(const Pet &body, Pistache::Http::ResponseWriter &response) { response.send(Pistache::Http::Code::Ok, "Do some magic\n"); diff --git a/samples/server/petstore/cpp-pistache/impl/PetApiImpl.h b/samples/server/petstore/cpp-pistache/impl/PetApiImpl.h index 9e9f3d145baf..82c10b0a410c 100644 --- a/samples/server/petstore/cpp-pistache/impl/PetApiImpl.h +++ b/samples/server/petstore/cpp-pistache/impl/PetApiImpl.h @@ -33,17 +33,15 @@ #include "Pet.h" #include -namespace org { -namespace openapitools { -namespace server { -namespace api { +namespace org::openapitools::server::api +{ using namespace org::openapitools::server::model; class PetApiImpl : public org::openapitools::server::api::PetApi { public: - PetApiImpl(std::shared_ptr); - ~PetApiImpl() {} + explicit PetApiImpl(const std::shared_ptr& rtr); + ~PetApiImpl() override = default; void add_pet(const Pet &body, Pistache::Http::ResponseWriter &response); void delete_pet(const int64_t &petId, const Pistache::Optional &apiKey, Pistache::Http::ResponseWriter &response); @@ -56,11 +54,8 @@ class PetApiImpl : public org::openapitools::server::api::PetApi { }; -} -} -} -} +} // namespace org::openapitools::server::api -#endif \ No newline at end of file +#endif diff --git a/samples/server/petstore/cpp-pistache/impl/StoreApiImpl.cpp b/samples/server/petstore/cpp-pistache/impl/StoreApiImpl.cpp index ef164eb0543e..a746316b8039 100644 --- a/samples/server/petstore/cpp-pistache/impl/StoreApiImpl.cpp +++ b/samples/server/petstore/cpp-pistache/impl/StoreApiImpl.cpp @@ -19,9 +19,10 @@ namespace api { using namespace org::openapitools::server::model; -StoreApiImpl::StoreApiImpl(std::shared_ptr rtr) +StoreApiImpl::StoreApiImpl(const std::shared_ptr& rtr) : StoreApi(rtr) - { } +{ +} void StoreApiImpl::delete_order(const std::string &orderId, Pistache::Http::ResponseWriter &response) { response.send(Pistache::Http::Code::Ok, "Do some magic\n"); diff --git a/samples/server/petstore/cpp-pistache/impl/StoreApiImpl.h b/samples/server/petstore/cpp-pistache/impl/StoreApiImpl.h index c99372463184..c5dda64490f7 100644 --- a/samples/server/petstore/cpp-pistache/impl/StoreApiImpl.h +++ b/samples/server/petstore/cpp-pistache/impl/StoreApiImpl.h @@ -33,17 +33,15 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace api { +namespace org::openapitools::server::api +{ using namespace org::openapitools::server::model; class StoreApiImpl : public org::openapitools::server::api::StoreApi { public: - StoreApiImpl(std::shared_ptr); - ~StoreApiImpl() {} + explicit StoreApiImpl(const std::shared_ptr& rtr); + ~StoreApiImpl() override = default; void delete_order(const std::string &orderId, Pistache::Http::ResponseWriter &response); void get_inventory(Pistache::Http::ResponseWriter &response); @@ -52,11 +50,8 @@ class StoreApiImpl : public org::openapitools::server::api::StoreApi { }; -} -} -} -} +} // namespace org::openapitools::server::api -#endif \ No newline at end of file +#endif diff --git a/samples/server/petstore/cpp-pistache/impl/UserApiImpl.cpp b/samples/server/petstore/cpp-pistache/impl/UserApiImpl.cpp index 7163a560bd77..b477f053c5c8 100644 --- a/samples/server/petstore/cpp-pistache/impl/UserApiImpl.cpp +++ b/samples/server/petstore/cpp-pistache/impl/UserApiImpl.cpp @@ -19,9 +19,10 @@ namespace api { using namespace org::openapitools::server::model; -UserApiImpl::UserApiImpl(std::shared_ptr rtr) +UserApiImpl::UserApiImpl(const std::shared_ptr& rtr) : UserApi(rtr) - { } +{ +} void UserApiImpl::create_user(const User &body, Pistache::Http::ResponseWriter &response) { response.send(Pistache::Http::Code::Ok, "Do some magic\n"); diff --git a/samples/server/petstore/cpp-pistache/impl/UserApiImpl.h b/samples/server/petstore/cpp-pistache/impl/UserApiImpl.h index 8f22c4998894..856a30db5bb1 100644 --- a/samples/server/petstore/cpp-pistache/impl/UserApiImpl.h +++ b/samples/server/petstore/cpp-pistache/impl/UserApiImpl.h @@ -33,17 +33,15 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace api { +namespace org::openapitools::server::api +{ using namespace org::openapitools::server::model; class UserApiImpl : public org::openapitools::server::api::UserApi { public: - UserApiImpl(std::shared_ptr); - ~UserApiImpl() {} + explicit UserApiImpl(const std::shared_ptr& rtr); + ~UserApiImpl() override = default; void create_user(const User &body, Pistache::Http::ResponseWriter &response); void create_users_with_array_input(const std::vector &body, Pistache::Http::ResponseWriter &response); @@ -56,11 +54,8 @@ class UserApiImpl : public org::openapitools::server::api::UserApi { }; -} -} -} -} +} // namespace org::openapitools::server::api -#endif \ No newline at end of file +#endif diff --git a/samples/server/petstore/cpp-pistache/model/ApiResponse.cpp b/samples/server/petstore/cpp-pistache/model/ApiResponse.cpp index 4b9ca7419208..049f6c19d6d6 100644 --- a/samples/server/petstore/cpp-pistache/model/ApiResponse.cpp +++ b/samples/server/petstore/cpp-pistache/model/ApiResponse.cpp @@ -12,11 +12,12 @@ #include "ApiResponse.h" +#include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace model { +#include + +namespace org::openapitools::server::model +{ ApiResponse::ApiResponse() { @@ -29,13 +30,52 @@ ApiResponse::ApiResponse() } -ApiResponse::~ApiResponse() +void ApiResponse::validate() const +{ + std::stringstream msg; + if (!validate(msg)) + { + throw org::openapitools::server::helpers::ValidationException(msg.str()); + } +} + +bool ApiResponse::validate(std::stringstream& msg) const +{ + return validate(msg, ""); +} + +bool ApiResponse::validate(std::stringstream& msg, const std::string& pathPrefix) const +{ + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "ApiResponse" : pathPrefix; + + + + + + return success; +} + +bool ApiResponse::operator==(const ApiResponse& rhs) const { + return + + + + ((!codeIsSet() && !rhs.codeIsSet()) || (codeIsSet() && rhs.codeIsSet() && getCode() == rhs.getCode())) && + + + ((!typeIsSet() && !rhs.typeIsSet()) || (typeIsSet() && rhs.typeIsSet() && getType() == rhs.getType())) && + + + ((!messageIsSet() && !rhs.messageIsSet()) || (messageIsSet() && rhs.messageIsSet() && getMessage() == rhs.getMessage())) + + ; } -void ApiResponse::validate() +bool ApiResponse::operator!=(const ApiResponse& rhs) const { - // TODO: implement validation + return !(*this == rhs); } void to_json(nlohmann::json& j, const ApiResponse& o) @@ -123,8 +163,5 @@ void ApiResponse::unsetMessage() } -} -} -} -} +} // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-pistache/model/ApiResponse.h b/samples/server/petstore/cpp-pistache/model/ApiResponse.h index 7ecb6c9a82ec..d963b76650bd 100644 --- a/samples/server/petstore/cpp-pistache/model/ApiResponse.h +++ b/samples/server/petstore/cpp-pistache/model/ApiResponse.h @@ -22,10 +22,8 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace model { +namespace org::openapitools::server::model +{ /// /// Describes the result of uploading an image resource @@ -34,9 +32,22 @@ class ApiResponse { public: ApiResponse(); - virtual ~ApiResponse(); + virtual ~ApiResponse() = default; - void validate(); + + /// + /// Validate the current data in the model. Throws a ValidationException on failure. + /// + void validate() const; + + /// + /// Validate the current data in the model. Returns false on error and writes an error + /// message into the given stringstream. + /// + bool validate(std::stringstream& msg) const; + + bool operator==(const ApiResponse& rhs) const; + bool operator!=(const ApiResponse& rhs) const; ///////////////////////////////////////////// /// ApiResponse members @@ -72,11 +83,11 @@ class ApiResponse bool m_TypeIsSet; std::string m_Message; bool m_MessageIsSet; + + // Helper overload for validate. Used when one model stores another model and calls it's validate. + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; }; -} -} -} -} +} // namespace org::openapitools::server::model #endif /* ApiResponse_H_ */ diff --git a/samples/server/petstore/cpp-pistache/model/Category.cpp b/samples/server/petstore/cpp-pistache/model/Category.cpp index 3b08114f61de..deb18ff9bb7e 100644 --- a/samples/server/petstore/cpp-pistache/model/Category.cpp +++ b/samples/server/petstore/cpp-pistache/model/Category.cpp @@ -12,11 +12,12 @@ #include "Category.h" +#include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace model { +#include + +namespace org::openapitools::server::model +{ Category::Category() { @@ -27,13 +28,48 @@ Category::Category() } -Category::~Category() +void Category::validate() const { + std::stringstream msg; + if (!validate(msg)) + { + throw org::openapitools::server::helpers::ValidationException(msg.str()); + } } -void Category::validate() +bool Category::validate(std::stringstream& msg) const { - // TODO: implement validation + return validate(msg, ""); +} + +bool Category::validate(std::stringstream& msg, const std::string& pathPrefix) const +{ + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "Category" : pathPrefix; + + + + + return success; +} + +bool Category::operator==(const Category& rhs) const +{ + return + + + + ((!idIsSet() && !rhs.idIsSet()) || (idIsSet() && rhs.idIsSet() && getId() == rhs.getId())) && + + + ((!nameIsSet() && !rhs.nameIsSet()) || (nameIsSet() && rhs.nameIsSet() && getName() == rhs.getName())) + + ; +} + +bool Category::operator!=(const Category& rhs) const +{ + return !(*this == rhs); } void to_json(nlohmann::json& j, const Category& o) @@ -97,8 +133,5 @@ void Category::unsetName() } -} -} -} -} +} // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-pistache/model/Category.h b/samples/server/petstore/cpp-pistache/model/Category.h index fa12fdc0de8d..1929ce33e925 100644 --- a/samples/server/petstore/cpp-pistache/model/Category.h +++ b/samples/server/petstore/cpp-pistache/model/Category.h @@ -22,10 +22,8 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace model { +namespace org::openapitools::server::model +{ /// /// A category for a pet @@ -34,9 +32,22 @@ class Category { public: Category(); - virtual ~Category(); + virtual ~Category() = default; - void validate(); + + /// + /// Validate the current data in the model. Throws a ValidationException on failure. + /// + void validate() const; + + /// + /// Validate the current data in the model. Returns false on error and writes an error + /// message into the given stringstream. + /// + bool validate(std::stringstream& msg) const; + + bool operator==(const Category& rhs) const; + bool operator!=(const Category& rhs) const; ///////////////////////////////////////////// /// Category members @@ -63,11 +74,11 @@ class Category bool m_IdIsSet; std::string m_Name; bool m_NameIsSet; + + // Helper overload for validate. Used when one model stores another model and calls it's validate. + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; }; -} -} -} -} +} // namespace org::openapitools::server::model #endif /* Category_H_ */ diff --git a/samples/server/petstore/cpp-pistache/model/Helpers.cpp b/samples/server/petstore/cpp-pistache/model/Helpers.cpp index a7774194c82c..cfac2d78986a 100644 --- a/samples/server/petstore/cpp-pistache/model/Helpers.cpp +++ b/samples/server/petstore/cpp-pistache/model/Helpers.cpp @@ -10,34 +10,75 @@ * Do not edit the class manually. */ #include "Helpers.h" +#include -namespace org { -namespace openapitools { -namespace server { -namespace helpers { +namespace org::openapitools::server::helpers +{ +const std::regex regexRfc3339_date(R"(^(\d{4})\-(\d{2})\-(\d{2})$)"); +const std::regex regexRfc3339_date_time( + R"(^(\d{4})\-(\d{2})\-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(\.\d+)?([Zz]|([\+\-])(\d{2}):(\d{2}))$)" +); + + +namespace +{ + // Determine if given year is a leap year + // See RFC 3339, Appendix C https://tools.ietf.org/html/rfc3339#appendix-C + bool isLeapYear(const uint16_t year) { + return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)); + } + + bool validateDateValues(const uint16_t year, const uint16_t month, const uint16_t day) { + return !( + (month == 0 || month > 12) + || (day == 0) + || (month == 2 && day > (28 + (isLeapYear(year) ? 1 : 0))) + || (month <= 7 && day > (30 + month % 2)) + || (month >= 8 && day > (31 - month % 2)) + ); + } + + bool validateTimeValues(const uint16_t hours, const uint16_t minutes, const uint16_t seconds) { + return (hours <= 23) && (minutes <= 59) && (seconds <= 60); + } +} + +bool validateRfc3339_date(const std::string& str) { + std::smatch match; + const bool found = std::regex_search(str, match, regexRfc3339_date); + return found && validateDateValues(std::stoi(match[1]), std::stoi(match[2]), std::stoi(match[3])); +} + +bool validateRfc3339_date_time(const std::string& str) { + std::smatch match; + const bool found = std::regex_search(str, match, regexRfc3339_date_time); + return found + && validateDateValues(std::stoi(match[1]), std::stoi(match[2]), std::stoi(match[3])) + && validateTimeValues(std::stoi(match[4]), std::stoi(match[5]), std::stoi(match[6])); +} std::string toStringValue(const std::string &value){ return std::string(value); } -std::string toStringValue(const int32_t &value){ +std::string toStringValue(const int32_t value){ return std::to_string(value); } -std::string toStringValue(const int64_t &value){ +std::string toStringValue(const int64_t value){ return std::to_string(value); } -std::string toStringValue(const bool &value){ - return value?std::string("true"):std::string("false"); +std::string toStringValue(const bool value){ + return value ? std::string("true") : std::string("false"); } -std::string toStringValue(const float &value){ +std::string toStringValue(const float value){ return std::to_string(value); } -std::string toStringValue(const double &value){ +std::string toStringValue(const double value){ return std::to_string(value); } @@ -67,9 +108,15 @@ bool fromStringValue(const std::string &inStr, int64_t &value){ } bool fromStringValue(const std::string &inStr, bool &value){ - bool result = true; - inStr == "true"?value = true: inStr == "false"?value = false: result = false; - return result; + if (inStr == "true") { + value = true; + return true; + } + if (inStr == "false") { + value = false; + return true; + } + return false; } bool fromStringValue(const std::string &inStr, float &value){ @@ -92,7 +139,4 @@ bool fromStringValue(const std::string &inStr, double &value){ return true; } -} -} -} -} +} // namespace org::openapitools::server::helpers diff --git a/samples/server/petstore/cpp-pistache/model/Helpers.h b/samples/server/petstore/cpp-pistache/model/Helpers.h index 9c8c02c4ae61..176b817de1eb 100644 --- a/samples/server/petstore/cpp-pistache/model/Helpers.h +++ b/samples/server/petstore/cpp-pistache/model/Helpers.h @@ -24,17 +24,80 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace helpers { +namespace org::openapitools::server::helpers +{ + + class ValidationException : public std::runtime_error + { + public: + explicit ValidationException(const std::string& what) + : std::runtime_error(what) + { } + ~ValidationException() override = default; + }; + + /// + /// Validate a string against the full-date definition of RFC 3339, section 5.6. + /// + bool validateRfc3339_date(const std::string& str); + + /// + /// Validate a string against the date-time definition of RFC 3339, section 5.6. + /// + bool validateRfc3339_date_time(const std::string& str); + + namespace sfinae_helpers + { + struct NoType {}; + template NoType operator==(const T1&, const T2&); + + template class EqualsOperatorAvailable + { + public: + enum + { + value = !std::is_same< decltype(std::declval() == std::declval()), NoType >::value + }; + }; + } // namespace sfinae_helpers + + + /// + /// Determine if the given vector only has unique elements. T must provide the == operator. + /// + template + bool hasOnlyUniqueItems(const std::vector& vec) + { + static_assert(sfinae_helpers::EqualsOperatorAvailable::value, + "hasOnlyUniqueItems cannot be called, passed template type does not provide == operator."); + if (vec.size() <= 1) + { + return true; + } + // Compare every element of vec to every other element of vec. + // This isn't an elegant way to do this, since it's O(n^2), + // but it's the best solution working only with the == operator. + // This could be greatly improved if our models provided a valid hash + // and/or the < operator + for (size_t i = 0; i < vec.size() - 1; i++) + { + for (size_t j = i + 1; j < vec.size(); j++) + { + if (vec[i] == vec[j]) + { + return false; + } + } + } + return true; + } std::string toStringValue(const std::string &value); - std::string toStringValue(const int32_t &value); - std::string toStringValue(const int64_t &value); - std::string toStringValue(const bool &value); - std::string toStringValue(const float &value); - std::string toStringValue(const double &value); + std::string toStringValue(const int32_t value); + std::string toStringValue(const int64_t value); + std::string toStringValue(const bool value); + std::string toStringValue(const float value); + std::string toStringValue(const double value); bool fromStringValue(const std::string &inStr, std::string &value); bool fromStringValue(const std::string &inStr, int32_t &value); @@ -68,9 +131,6 @@ namespace helpers { return fromStringValue(inStrings, value); } -} -} -} -} +} // namespace org::openapitools::server::helpers -#endif // Helpers_H_ \ No newline at end of file +#endif // Helpers_H_ diff --git a/samples/server/petstore/cpp-pistache/model/Order.cpp b/samples/server/petstore/cpp-pistache/model/Order.cpp index 986cf6b24fa9..2d04f0ac637b 100644 --- a/samples/server/petstore/cpp-pistache/model/Order.cpp +++ b/samples/server/petstore/cpp-pistache/model/Order.cpp @@ -12,11 +12,12 @@ #include "Order.h" +#include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace model { +#include + +namespace org::openapitools::server::model +{ Order::Order() { @@ -35,13 +36,64 @@ Order::Order() } -Order::~Order() +void Order::validate() const { + std::stringstream msg; + if (!validate(msg)) + { + throw org::openapitools::server::helpers::ValidationException(msg.str()); + } } -void Order::validate() +bool Order::validate(std::stringstream& msg) const { - // TODO: implement validation + return validate(msg, ""); +} + +bool Order::validate(std::stringstream& msg, const std::string& pathPrefix) const +{ + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "Order" : pathPrefix; + + + + + + + + + return success; +} + +bool Order::operator==(const Order& rhs) const +{ + return + + + + ((!idIsSet() && !rhs.idIsSet()) || (idIsSet() && rhs.idIsSet() && getId() == rhs.getId())) && + + + ((!petIdIsSet() && !rhs.petIdIsSet()) || (petIdIsSet() && rhs.petIdIsSet() && getPetId() == rhs.getPetId())) && + + + ((!quantityIsSet() && !rhs.quantityIsSet()) || (quantityIsSet() && rhs.quantityIsSet() && getQuantity() == rhs.getQuantity())) && + + + ((!shipDateIsSet() && !rhs.shipDateIsSet()) || (shipDateIsSet() && rhs.shipDateIsSet() && getShipDate() == rhs.getShipDate())) && + + + ((!statusIsSet() && !rhs.statusIsSet()) || (statusIsSet() && rhs.statusIsSet() && getStatus() == rhs.getStatus())) && + + + ((!completeIsSet() && !rhs.completeIsSet()) || (completeIsSet() && rhs.completeIsSet() && isComplete() == rhs.isComplete())) + + ; +} + +bool Order::operator!=(const Order& rhs) const +{ + return !(*this == rhs); } void to_json(nlohmann::json& j, const Order& o) @@ -201,8 +253,5 @@ void Order::unsetComplete() } -} -} -} -} +} // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-pistache/model/Order.h b/samples/server/petstore/cpp-pistache/model/Order.h index d900b633f32c..3d28e1eef6ba 100644 --- a/samples/server/petstore/cpp-pistache/model/Order.h +++ b/samples/server/petstore/cpp-pistache/model/Order.h @@ -22,10 +22,8 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace model { +namespace org::openapitools::server::model +{ /// /// An order for a pets from the pet store @@ -34,9 +32,22 @@ class Order { public: Order(); - virtual ~Order(); + virtual ~Order() = default; - void validate(); + + /// + /// Validate the current data in the model. Throws a ValidationException on failure. + /// + void validate() const; + + /// + /// Validate the current data in the model. Returns false on error and writes an error + /// message into the given stringstream. + /// + bool validate(std::stringstream& msg) const; + + bool operator==(const Order& rhs) const; + bool operator!=(const Order& rhs) const; ///////////////////////////////////////////// /// Order members @@ -99,11 +110,11 @@ class Order bool m_StatusIsSet; bool m_Complete; bool m_CompleteIsSet; + + // Helper overload for validate. Used when one model stores another model and calls it's validate. + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; }; -} -} -} -} +} // namespace org::openapitools::server::model #endif /* Order_H_ */ diff --git a/samples/server/petstore/cpp-pistache/model/Pet.cpp b/samples/server/petstore/cpp-pistache/model/Pet.cpp index 434b1339cd06..9c7ba886a44c 100644 --- a/samples/server/petstore/cpp-pistache/model/Pet.cpp +++ b/samples/server/petstore/cpp-pistache/model/Pet.cpp @@ -12,11 +12,12 @@ #include "Pet.h" +#include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace model { +#include + +namespace org::openapitools::server::model +{ Pet::Pet() { @@ -30,13 +31,106 @@ Pet::Pet() } -Pet::~Pet() +void Pet::validate() const +{ + std::stringstream msg; + if (!validate(msg)) + { + throw org::openapitools::server::helpers::ValidationException(msg.str()); + } +} + +bool Pet::validate(std::stringstream& msg) const { + return validate(msg, ""); } -void Pet::validate() +bool Pet::validate(std::stringstream& msg, const std::string& pathPrefix) const { - // TODO: implement validation + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "Pet" : pathPrefix; + + + + + + + /* PhotoUrls */ { + const std::vector& value = m_PhotoUrls; + const std::string currentValuePath = _pathPrefix + ".photoUrls"; + + + { // Recursive validation of array elements + const std::string oldValuePath = currentValuePath; + int i = 0; + for (const std::string& value : value) + { + const std::string currentValuePath = oldValuePath + "[" + std::to_string(i) + "]"; + + + + i++; + } + } + + } + + + if (tagsIsSet()) + { + const std::vector& value = m_Tags; + const std::string currentValuePath = _pathPrefix + ".tags"; + + + { // Recursive validation of array elements + const std::string oldValuePath = currentValuePath; + int i = 0; + for (const Tag& value : value) + { + const std::string currentValuePath = oldValuePath + "[" + std::to_string(i) + "]"; + + success = value.validate(msg, currentValuePath + ".tags") && success; + + i++; + } + } + + } + + + + return success; +} + +bool Pet::operator==(const Pet& rhs) const +{ + return + + + + ((!idIsSet() && !rhs.idIsSet()) || (idIsSet() && rhs.idIsSet() && getId() == rhs.getId())) && + + + ((!categoryIsSet() && !rhs.categoryIsSet()) || (categoryIsSet() && rhs.categoryIsSet() && getCategory() == rhs.getCategory())) && + + (getName() == rhs.getName()) + && + + (getPhotoUrls() == rhs.getPhotoUrls()) + && + + + ((!tagsIsSet() && !rhs.tagsIsSet()) || (tagsIsSet() && rhs.tagsIsSet() && getTags() == rhs.getTags())) && + + + ((!statusIsSet() && !rhs.statusIsSet()) || (statusIsSet() && rhs.statusIsSet() && getStatus() == rhs.getStatus())) + + ; +} + +bool Pet::operator!=(const Pet& rhs) const +{ + return !(*this == rhs); } void to_json(nlohmann::json& j, const Pet& o) @@ -124,7 +218,7 @@ void Pet::setName(std::string const& value) { m_Name = value; } -std::vector& Pet::getPhotoUrls() +std::vector Pet::getPhotoUrls() const { return m_PhotoUrls; } @@ -132,7 +226,7 @@ void Pet::setPhotoUrls(std::vector const& value) { m_PhotoUrls = value; } -std::vector& Pet::getTags() +std::vector Pet::getTags() const { return m_Tags; } @@ -168,8 +262,5 @@ void Pet::unsetStatus() } -} -} -} -} +} // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-pistache/model/Pet.h b/samples/server/petstore/cpp-pistache/model/Pet.h index eddf475f6ee3..1cd841a08fa7 100644 --- a/samples/server/petstore/cpp-pistache/model/Pet.h +++ b/samples/server/petstore/cpp-pistache/model/Pet.h @@ -25,10 +25,8 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace model { +namespace org::openapitools::server::model +{ /// /// A pet for sale in the pet store @@ -37,9 +35,22 @@ class Pet { public: Pet(); - virtual ~Pet(); + virtual ~Pet() = default; - void validate(); + + /// + /// Validate the current data in the model. Throws a ValidationException on failure. + /// + void validate() const; + + /// + /// Validate the current data in the model. Returns false on error and writes an error + /// message into the given stringstream. + /// + bool validate(std::stringstream& msg) const; + + bool operator==(const Pet& rhs) const; + bool operator!=(const Pet& rhs) const; ///////////////////////////////////////////// /// Pet members @@ -66,12 +77,12 @@ class Pet /// /// /// - std::vector& getPhotoUrls(); + std::vector getPhotoUrls() const; void setPhotoUrls(std::vector const& value); /// /// /// - std::vector& getTags(); + std::vector getTags() const; void setTags(std::vector const& value); bool tagsIsSet() const; void unsetTags(); @@ -98,11 +109,11 @@ class Pet bool m_TagsIsSet; std::string m_Status; bool m_StatusIsSet; + + // Helper overload for validate. Used when one model stores another model and calls it's validate. + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; }; -} -} -} -} +} // namespace org::openapitools::server::model #endif /* Pet_H_ */ diff --git a/samples/server/petstore/cpp-pistache/model/Tag.cpp b/samples/server/petstore/cpp-pistache/model/Tag.cpp index cba759bad1d0..659565e4034d 100644 --- a/samples/server/petstore/cpp-pistache/model/Tag.cpp +++ b/samples/server/petstore/cpp-pistache/model/Tag.cpp @@ -12,11 +12,12 @@ #include "Tag.h" +#include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace model { +#include + +namespace org::openapitools::server::model +{ Tag::Tag() { @@ -27,13 +28,48 @@ Tag::Tag() } -Tag::~Tag() +void Tag::validate() const { + std::stringstream msg; + if (!validate(msg)) + { + throw org::openapitools::server::helpers::ValidationException(msg.str()); + } } -void Tag::validate() +bool Tag::validate(std::stringstream& msg) const { - // TODO: implement validation + return validate(msg, ""); +} + +bool Tag::validate(std::stringstream& msg, const std::string& pathPrefix) const +{ + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "Tag" : pathPrefix; + + + + + return success; +} + +bool Tag::operator==(const Tag& rhs) const +{ + return + + + + ((!idIsSet() && !rhs.idIsSet()) || (idIsSet() && rhs.idIsSet() && getId() == rhs.getId())) && + + + ((!nameIsSet() && !rhs.nameIsSet()) || (nameIsSet() && rhs.nameIsSet() && getName() == rhs.getName())) + + ; +} + +bool Tag::operator!=(const Tag& rhs) const +{ + return !(*this == rhs); } void to_json(nlohmann::json& j, const Tag& o) @@ -97,8 +133,5 @@ void Tag::unsetName() } -} -} -} -} +} // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-pistache/model/Tag.h b/samples/server/petstore/cpp-pistache/model/Tag.h index 4b422931d771..ddebeadae431 100644 --- a/samples/server/petstore/cpp-pistache/model/Tag.h +++ b/samples/server/petstore/cpp-pistache/model/Tag.h @@ -22,10 +22,8 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace model { +namespace org::openapitools::server::model +{ /// /// A tag for a pet @@ -34,9 +32,22 @@ class Tag { public: Tag(); - virtual ~Tag(); + virtual ~Tag() = default; - void validate(); + + /// + /// Validate the current data in the model. Throws a ValidationException on failure. + /// + void validate() const; + + /// + /// Validate the current data in the model. Returns false on error and writes an error + /// message into the given stringstream. + /// + bool validate(std::stringstream& msg) const; + + bool operator==(const Tag& rhs) const; + bool operator!=(const Tag& rhs) const; ///////////////////////////////////////////// /// Tag members @@ -63,11 +74,11 @@ class Tag bool m_IdIsSet; std::string m_Name; bool m_NameIsSet; + + // Helper overload for validate. Used when one model stores another model and calls it's validate. + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; }; -} -} -} -} +} // namespace org::openapitools::server::model #endif /* Tag_H_ */ diff --git a/samples/server/petstore/cpp-pistache/model/User.cpp b/samples/server/petstore/cpp-pistache/model/User.cpp index 2db9316b75d9..c997bf9734db 100644 --- a/samples/server/petstore/cpp-pistache/model/User.cpp +++ b/samples/server/petstore/cpp-pistache/model/User.cpp @@ -12,11 +12,12 @@ #include "User.h" +#include "Helpers.h" -namespace org { -namespace openapitools { -namespace server { -namespace model { +#include + +namespace org::openapitools::server::model +{ User::User() { @@ -39,13 +40,72 @@ User::User() } -User::~User() +void User::validate() const +{ + std::stringstream msg; + if (!validate(msg)) + { + throw org::openapitools::server::helpers::ValidationException(msg.str()); + } +} + +bool User::validate(std::stringstream& msg) const { + return validate(msg, ""); } -void User::validate() +bool User::validate(std::stringstream& msg, const std::string& pathPrefix) const { - // TODO: implement validation + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "User" : pathPrefix; + + + + + + + + + + + return success; +} + +bool User::operator==(const User& rhs) const +{ + return + + + + ((!idIsSet() && !rhs.idIsSet()) || (idIsSet() && rhs.idIsSet() && getId() == rhs.getId())) && + + + ((!usernameIsSet() && !rhs.usernameIsSet()) || (usernameIsSet() && rhs.usernameIsSet() && getUsername() == rhs.getUsername())) && + + + ((!firstNameIsSet() && !rhs.firstNameIsSet()) || (firstNameIsSet() && rhs.firstNameIsSet() && getFirstName() == rhs.getFirstName())) && + + + ((!lastNameIsSet() && !rhs.lastNameIsSet()) || (lastNameIsSet() && rhs.lastNameIsSet() && getLastName() == rhs.getLastName())) && + + + ((!emailIsSet() && !rhs.emailIsSet()) || (emailIsSet() && rhs.emailIsSet() && getEmail() == rhs.getEmail())) && + + + ((!passwordIsSet() && !rhs.passwordIsSet()) || (passwordIsSet() && rhs.passwordIsSet() && getPassword() == rhs.getPassword())) && + + + ((!phoneIsSet() && !rhs.phoneIsSet()) || (phoneIsSet() && rhs.phoneIsSet() && getPhone() == rhs.getPhone())) && + + + ((!userStatusIsSet() && !rhs.userStatusIsSet()) || (userStatusIsSet() && rhs.userStatusIsSet() && getUserStatus() == rhs.getUserStatus())) + + ; +} + +bool User::operator!=(const User& rhs) const +{ + return !(*this == rhs); } void to_json(nlohmann::json& j, const User& o) @@ -253,8 +313,5 @@ void User::unsetUserStatus() } -} -} -} -} +} // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-pistache/model/User.h b/samples/server/petstore/cpp-pistache/model/User.h index 1f4c17ce6a81..02bd5f4230a8 100644 --- a/samples/server/petstore/cpp-pistache/model/User.h +++ b/samples/server/petstore/cpp-pistache/model/User.h @@ -22,10 +22,8 @@ #include #include -namespace org { -namespace openapitools { -namespace server { -namespace model { +namespace org::openapitools::server::model +{ /// /// A User who is purchasing from the pet store @@ -34,9 +32,22 @@ class User { public: User(); - virtual ~User(); + virtual ~User() = default; - void validate(); + + /// + /// Validate the current data in the model. Throws a ValidationException on failure. + /// + void validate() const; + + /// + /// Validate the current data in the model. Returns false on error and writes an error + /// message into the given stringstream. + /// + bool validate(std::stringstream& msg) const; + + bool operator==(const User& rhs) const; + bool operator!=(const User& rhs) const; ///////////////////////////////////////////// /// User members @@ -117,11 +128,11 @@ class User bool m_PhoneIsSet; int32_t m_UserStatus; bool m_UserStatusIsSet; + + // Helper overload for validate. Used when one model stores another model and calls it's validate. + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; }; -} -} -} -} +} // namespace org::openapitools::server::model #endif /* User_H_ */ diff --git a/samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator-ignore b/samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/.openapi-generator/FILES b/samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator/FILES similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/.openapi-generator/FILES rename to samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator/FILES diff --git a/samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator/VERSION b/samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator/VERSION new file mode 100644 index 000000000000..6555596f9311 --- /dev/null +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/CMakeLists.txt b/samples/server/petstore/cpp-qt-qhttpengine-server/server/CMakeLists.txt similarity index 93% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/CMakeLists.txt rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/CMakeLists.txt index 54e6d36d73fe..71b8bdb45f41 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/CMakeLists.txt +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/server/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.2 FATAL_ERROR) -project(cpp-qt5-qhttpengine-server) +project(cpp-qt-qhttpengine-server) include(ExternalProject) diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/Dockerfile b/samples/server/petstore/cpp-qt-qhttpengine-server/server/Dockerfile similarity index 78% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/Dockerfile rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/Dockerfile index b0c591d10f65..9dfdd9ab4785 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/Dockerfile +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/server/Dockerfile @@ -23,7 +23,7 @@ RUN apk add --update \ openssl WORKDIR /usr/server -COPY --from=build /usr/server/build/src/cpp-qt5-qhttpengine-server ./build/src/ +COPY --from=build /usr/server/build/src/cpp-qt-qhttpengine-server ./build/src/ COPY --from=build /usr/server/external/ ./external EXPOSE 8080/tcp -ENTRYPOINT ["/usr/server/build/src/cpp-qt5-qhttpengine-server"] \ No newline at end of file +ENTRYPOINT ["/usr/server/build/src/cpp-qt-qhttpengine-server"] diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/LICENSE.txt b/samples/server/petstore/cpp-qt-qhttpengine-server/server/LICENSE.txt similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/LICENSE.txt rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/LICENSE.txt diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/Makefile b/samples/server/petstore/cpp-qt-qhttpengine-server/server/Makefile similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/Makefile rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/Makefile diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/README.MD b/samples/server/petstore/cpp-qt-qhttpengine-server/server/README.MD similarity index 88% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/README.MD rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/README.MD index 5225ebb24fd9..8158062ef703 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/README.MD +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/server/README.MD @@ -1,6 +1,6 @@ -# C++ Qt5 Server +# C++ Qt Server -## Qt5 HTTP Server based on the Qhttpengine +## Qt HTTP Server based on the Qhttpengine This server was generated by the [openapi-generator](https://openapi-generator.tech) project. By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. @@ -46,18 +46,18 @@ make To run the server ```shell -./build/src/cpp-qt5-qhttpengine-server & +./build/src/cpp-qt-qhttpengine-server & ``` To override the default port via the command line, provide the parameters `port` and `address` like below ```shell -cpp-qt5-qhttpengine-server --port 9080 --address 127.17.0.1 +cpp-qt-qhttpengine-server --port 9080 --address 127.17.0.1 ``` or ```shell -cpp-qt5-qhttpengine-server -p 9080 -a 127.17.0.1 +cpp-qt-qhttpengine-server -p 9080 -a 127.17.0.1 ``` #### Invoke an API @@ -76,13 +76,13 @@ If you dont have docker install [here](https://docs.docker.com/install) Add yourself to the docker group ```shell -docker build --network=host -t cpp-qt5-qhttpengine-server . +docker build --network=host -t cpp-qt-qhttpengine-server . ``` Running with docker ```shell -docker run --rm -it --name=server-container cpp-qt5-qhttpengine-server +docker run --rm -it --name=server-container cpp-qt-qhttpengine-server ``` #### Invoking an API diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/CMakeLists.txt b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/CMakeLists.txt similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/CMakeLists.txt rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/CMakeLists.txt diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIApiRouter.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIApiRouter.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIApiRouter.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIApiRouter.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIApiRouter.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIApiRouter.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIApiRouter.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIApiRouter.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIPetApiHandler.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIPetApiHandler.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIPetApiHandler.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIPetApiHandler.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIPetApiHandler.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIPetApiHandler.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIPetApiHandler.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIPetApiHandler.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIUserApiHandler.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIUserApiHandler.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIUserApiHandler.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIUserApiHandler.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIUserApiHandler.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIUserApiHandler.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIUserApiHandler.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIUserApiHandler.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/main.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/main.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/main.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/main.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIApiResponse.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIApiResponse.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIApiResponse.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIApiResponse.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIApiResponse.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIApiResponse.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIApiResponse.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIApiResponse.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAICategory.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAICategory.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAICategory.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAICategory.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAICategory.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAICategory.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAICategory.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAICategory.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIEnum.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIEnum.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIEnum.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIEnum.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHelpers.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIHelpers.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHelpers.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIHelpers.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHelpers.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIHelpers.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHelpers.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIHelpers.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHttpFileElement.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIHttpFileElement.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHttpFileElement.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIHttpFileElement.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHttpFileElement.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIHttpFileElement.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHttpFileElement.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIHttpFileElement.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIObject.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIObject.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIObject.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIObject.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIOrder.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIOrder.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIOrder.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIOrder.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIOrder.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIOrder.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIOrder.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIOrder.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIPet.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIPet.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIPet.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIPet.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIPet.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIPet.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIPet.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIPet.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAITag.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAITag.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAITag.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAITag.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAITag.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAITag.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAITag.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAITag.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIUser.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIUser.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIUser.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIUser.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIUser.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIUser.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIUser.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIUser.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIPetApiRequest.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIPetApiRequest.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIPetApiRequest.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIPetApiRequest.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIPetApiRequest.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIPetApiRequest.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIPetApiRequest.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIPetApiRequest.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIStoreApiRequest.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIStoreApiRequest.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIStoreApiRequest.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIStoreApiRequest.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIStoreApiRequest.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIStoreApiRequest.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIStoreApiRequest.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIStoreApiRequest.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIUserApiRequest.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIUserApiRequest.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIUserApiRequest.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIUserApiRequest.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIUserApiRequest.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIUserApiRequest.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIUserApiRequest.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIUserApiRequest.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/.openapi-generator/VERSION b/samples/server/petstore/cpp-qt5-qhttpengine-server/.openapi-generator/VERSION deleted file mode 100644 index d509cc92aa80..000000000000 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/.openapi-generator/VERSION +++ /dev/null @@ -1 +0,0 @@ -5.1.1-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/erlang-server/.openapi-generator/FILES b/samples/server/petstore/erlang-server/.openapi-generator/FILES new file mode 100644 index 000000000000..9c50202b9359 --- /dev/null +++ b/samples/server/petstore/erlang-server/.openapi-generator/FILES @@ -0,0 +1,14 @@ +README.md +priv/openapi.json +rebar.config +src/openapi.app.src +src/openapi_api.erl +src/openapi_auth.erl +src/openapi_default_logic_handler.erl +src/openapi_logic_handler.erl +src/openapi_pet_handler.erl +src/openapi_router.erl +src/openapi_server.erl +src/openapi_store_handler.erl +src/openapi_user_handler.erl +src/openapi_utils.erl diff --git a/samples/server/petstore/erlang-server/.openapi-generator/VERSION b/samples/server/petstore/erlang-server/.openapi-generator/VERSION index d99e7162d01f..d509cc92aa80 100644 --- a/samples/server/petstore/erlang-server/.openapi-generator/VERSION +++ b/samples/server/petstore/erlang-server/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.1.1-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/erlang-server/rebar.config b/samples/server/petstore/erlang-server/rebar.config index 7ddca0f30279..743b108f384a 100644 --- a/samples/server/petstore/erlang-server/rebar.config +++ b/samples/server/petstore/erlang-server/rebar.config @@ -1,6 +1,6 @@ {deps, [ - {cowboy, {git, "https://github.com/ninenines/cowboy.git", {tag, "2.5.0"}}}, + {cowboy, {git, "https://github.com/ninenines/cowboy.git", {tag, "2.8.0"}}}, {rfc3339, {git, "https://github.com/talentdeficit/rfc3339.git", {tag, "master"}}}, - {jsx, {git, "https://github.com/talentdeficit/jsx.git", {tag, "2.9.0"}}}, - {jesse, {git, "https://github.com/for-GET/jesse.git", {tag, "1.5.2"}}} + {jsx, {git, "https://github.com/talentdeficit/jsx.git", {tag, "v3.1.0"}}}, + {jesse, {git, "https://github.com/for-GET/jesse.git", {tag, "1.5.6"}}} ]}. diff --git a/samples/server/petstore/fsharp-giraffe/.openapi-generator/VERSION b/samples/server/petstore/fsharp-giraffe/.openapi-generator/VERSION index 0e97bd19efbf..d509cc92aa80 100644 --- a/samples/server/petstore/fsharp-giraffe/.openapi-generator/VERSION +++ b/samples/server/petstore/fsharp-giraffe/.openapi-generator/VERSION @@ -1 +1 @@ -4.1.3-SNAPSHOT \ No newline at end of file +5.1.1-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/fsharp-giraffe/OpenAPI/README.md b/samples/server/petstore/fsharp-giraffe/OpenAPI/README.md index c529ef85cdd8..efa4280fbffa 100644 --- a/samples/server/petstore/fsharp-giraffe/OpenAPI/README.md +++ b/samples/server/petstore/fsharp-giraffe/OpenAPI/README.md @@ -10,8 +10,6 @@ The following models have been auto-generated from the provided OpenAPI schema: - model/TagModel.fs - model/CategoryModel.fs - model/OrderModel.fs -- model/InlineObject1Model.fs -- model/InlineObjectModel.fs - model/PetModel.fs - model/ApiResponseModel.fs diff --git a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/OpenAPI.fsproj b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/OpenAPI.fsproj index 4b31d698ba33..be2ed1c3c1fd 100644 --- a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/OpenAPI.fsproj +++ b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/OpenAPI.fsproj @@ -25,8 +25,6 @@ - - diff --git a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/PetApiHandler.fs b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/PetApiHandler.fs index 634acdf18752..0e1bd62938ad 100644 --- a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/PetApiHandler.fs +++ b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/PetApiHandler.fs @@ -29,8 +29,10 @@ module PetApiHandler = let serviceArgs = { bodyParams=bodyParams } : AddPetArgs let result = PetApiService.AddPet ctx serviceArgs return! (match result with + | AddPetStatusCode200 resolved -> + setStatusCode 200 >=> json resolved.content | AddPetStatusCode405 resolved -> - setStatusCode 405 >=> text resolved.content + setStatusCode 405 >=> text resolved.content ) next ctx } //#endregion @@ -50,7 +52,7 @@ module PetApiHandler = let result = PetApiService.DeletePet ctx serviceArgs return! (match result with | DeletePetStatusCode400 resolved -> - setStatusCode 400 >=> text resolved.content + setStatusCode 400 >=> text resolved.content ) next ctx } //#endregion @@ -67,10 +69,10 @@ module PetApiHandler = let serviceArgs = { queryParams=queryParams; } : FindPetsByStatusArgs let result = PetApiService.FindPetsByStatus ctx serviceArgs return! (match result with - | FindPetsByStatusDefaultStatusCode resolved -> - setStatusCode 200 >=> json resolved.content + | FindPetsByStatusStatusCode200 resolved -> + setStatusCode 200 >=> json resolved.content | FindPetsByStatusStatusCode400 resolved -> - setStatusCode 400 >=> text resolved.content + setStatusCode 400 >=> text resolved.content ) next ctx } //#endregion @@ -87,10 +89,10 @@ module PetApiHandler = let serviceArgs = { queryParams=queryParams; } : FindPetsByTagsArgs let result = PetApiService.FindPetsByTags ctx serviceArgs return! (match result with - | FindPetsByTagsDefaultStatusCode resolved -> - setStatusCode 200 >=> json resolved.content + | FindPetsByTagsStatusCode200 resolved -> + setStatusCode 200 >=> json resolved.content | FindPetsByTagsStatusCode400 resolved -> - setStatusCode 400 >=> text resolved.content + setStatusCode 400 >=> text resolved.content ) next ctx } //#endregion @@ -106,12 +108,12 @@ module PetApiHandler = let serviceArgs = { pathParams=pathParams; } : GetPetByIdArgs let result = PetApiService.GetPetById ctx serviceArgs return! (match result with - | GetPetByIdDefaultStatusCode resolved -> - setStatusCode 200 >=> json resolved.content + | GetPetByIdStatusCode200 resolved -> + setStatusCode 200 >=> json resolved.content | GetPetByIdStatusCode400 resolved -> - setStatusCode 400 >=> text resolved.content + setStatusCode 400 >=> text resolved.content | GetPetByIdStatusCode404 resolved -> - setStatusCode 404 >=> text resolved.content + setStatusCode 404 >=> text resolved.content ) next ctx } //#endregion @@ -129,12 +131,14 @@ module PetApiHandler = let serviceArgs = { bodyParams=bodyParams } : UpdatePetArgs let result = PetApiService.UpdatePet ctx serviceArgs return! (match result with + | UpdatePetStatusCode200 resolved -> + setStatusCode 200 >=> json resolved.content | UpdatePetStatusCode400 resolved -> - setStatusCode 400 >=> text resolved.content + setStatusCode 400 >=> text resolved.content | UpdatePetStatusCode404 resolved -> - setStatusCode 404 >=> text resolved.content + setStatusCode 404 >=> text resolved.content | UpdatePetStatusCode405 resolved -> - setStatusCode 405 >=> text resolved.content + setStatusCode 405 >=> text resolved.content ) next ctx } //#endregion @@ -152,7 +156,7 @@ module PetApiHandler = let result = PetApiService.UpdatePetWithForm ctx serviceArgs return! (match result with | UpdatePetWithFormStatusCode405 resolved -> - setStatusCode 405 >=> text resolved.content + setStatusCode 405 >=> text resolved.content ) next ctx } //#endregion @@ -169,8 +173,8 @@ module PetApiHandler = let serviceArgs = { formParams=formParams; pathParams=pathParams; } : UploadFileArgs let result = PetApiService.UploadFile ctx serviceArgs return! (match result with - | UploadFileDefaultStatusCode resolved -> - setStatusCode 200 >=> json resolved.content + | UploadFileStatusCode200 resolved -> + setStatusCode 200 >=> json resolved.content ) next ctx } //#endregion diff --git a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/PetApiHandlerParams.fs b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/PetApiHandlerParams.fs index f84ffb76b22c..c2332ce40bfd 100644 --- a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/PetApiHandlerParams.fs +++ b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/PetApiHandlerParams.fs @@ -14,11 +14,16 @@ module PetApiHandlerParams = //#endregion + type AddPetStatusCode200Response = { + content:Pet; + + } + type AddPetStatusCode405Response = { content:string; } - type AddPetResult = AddPetStatusCode405 of AddPetStatusCode405Response + type AddPetResult = AddPetStatusCode200 of AddPetStatusCode200Response|AddPetStatusCode405 of AddPetStatusCode405Response type AddPetArgs = { bodyParams:AddPetBodyParams @@ -58,7 +63,7 @@ module PetApiHandlerParams = //#endregion - type FindPetsByStatusDefaultStatusCodeResponse = { + type FindPetsByStatusStatusCode200Response = { content:Pet[]; } @@ -67,7 +72,7 @@ module PetApiHandlerParams = content:string; } - type FindPetsByStatusResult = FindPetsByStatusDefaultStatusCode of FindPetsByStatusDefaultStatusCodeResponse|FindPetsByStatusStatusCode400 of FindPetsByStatusStatusCode400Response + type FindPetsByStatusResult = FindPetsByStatusStatusCode200 of FindPetsByStatusStatusCode200Response|FindPetsByStatusStatusCode400 of FindPetsByStatusStatusCode400Response type FindPetsByStatusArgs = { queryParams:Result; @@ -82,7 +87,7 @@ module PetApiHandlerParams = //#endregion - type FindPetsByTagsDefaultStatusCodeResponse = { + type FindPetsByTagsStatusCode200Response = { content:Pet[]; } @@ -91,7 +96,7 @@ module PetApiHandlerParams = content:string; } - type FindPetsByTagsResult = FindPetsByTagsDefaultStatusCode of FindPetsByTagsDefaultStatusCodeResponse|FindPetsByTagsStatusCode400 of FindPetsByTagsStatusCode400Response + type FindPetsByTagsResult = FindPetsByTagsStatusCode200 of FindPetsByTagsStatusCode200Response|FindPetsByTagsStatusCode400 of FindPetsByTagsStatusCode400Response type FindPetsByTagsArgs = { queryParams:Result; @@ -104,7 +109,7 @@ module PetApiHandlerParams = //#endregion - type GetPetByIdDefaultStatusCodeResponse = { + type GetPetByIdStatusCode200Response = { content:Pet; } @@ -118,7 +123,7 @@ module PetApiHandlerParams = content:string; } - type GetPetByIdResult = GetPetByIdDefaultStatusCode of GetPetByIdDefaultStatusCodeResponse|GetPetByIdStatusCode400 of GetPetByIdStatusCode400Response|GetPetByIdStatusCode404 of GetPetByIdStatusCode404Response + type GetPetByIdResult = GetPetByIdStatusCode200 of GetPetByIdStatusCode200Response|GetPetByIdStatusCode400 of GetPetByIdStatusCode400Response|GetPetByIdStatusCode404 of GetPetByIdStatusCode404Response type GetPetByIdArgs = { pathParams:GetPetByIdPathParams; @@ -130,6 +135,11 @@ module PetApiHandlerParams = //#endregion + type UpdatePetStatusCode200Response = { + content:Pet; + + } + type UpdatePetStatusCode400Response = { content:string; @@ -144,7 +154,7 @@ module PetApiHandlerParams = content:string; } - type UpdatePetResult = UpdatePetStatusCode400 of UpdatePetStatusCode400Response|UpdatePetStatusCode404 of UpdatePetStatusCode404Response|UpdatePetStatusCode405 of UpdatePetStatusCode405Response + type UpdatePetResult = UpdatePetStatusCode200 of UpdatePetStatusCode200Response|UpdatePetStatusCode400 of UpdatePetStatusCode400Response|UpdatePetStatusCode404 of UpdatePetStatusCode404Response|UpdatePetStatusCode405 of UpdatePetStatusCode405Response type UpdatePetArgs = { bodyParams:UpdatePetBodyParams @@ -197,11 +207,11 @@ module PetApiHandlerParams = //#endregion - type UploadFileDefaultStatusCodeResponse = { + type UploadFileStatusCode200Response = { content:ApiResponse; } - type UploadFileResult = UploadFileDefaultStatusCode of UploadFileDefaultStatusCodeResponse + type UploadFileResult = UploadFileStatusCode200 of UploadFileStatusCode200Response type UploadFileArgs = { pathParams:UploadFilePathParams; diff --git a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/StoreApiHandler.fs b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/StoreApiHandler.fs index 91592d5af51f..cabdab6cbdb5 100644 --- a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/StoreApiHandler.fs +++ b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/StoreApiHandler.fs @@ -28,9 +28,9 @@ module StoreApiHandler = let result = StoreApiService.DeleteOrder ctx serviceArgs return! (match result with | DeleteOrderStatusCode400 resolved -> - setStatusCode 400 >=> text resolved.content + setStatusCode 400 >=> text resolved.content | DeleteOrderStatusCode404 resolved -> - setStatusCode 404 >=> text resolved.content + setStatusCode 404 >=> text resolved.content ) next ctx } //#endregion @@ -45,8 +45,8 @@ module StoreApiHandler = task { let result = StoreApiService.GetInventory ctx return! (match result with - | GetInventoryDefaultStatusCode resolved -> - setStatusCode 200 >=> json resolved.content + | GetInventoryStatusCode200 resolved -> + setStatusCode 200 >=> json resolved.content ) next ctx } //#endregion @@ -62,12 +62,12 @@ module StoreApiHandler = let serviceArgs = { pathParams=pathParams; } : GetOrderByIdArgs let result = StoreApiService.GetOrderById ctx serviceArgs return! (match result with - | GetOrderByIdDefaultStatusCode resolved -> - setStatusCode 200 >=> json resolved.content + | GetOrderByIdStatusCode200 resolved -> + setStatusCode 200 >=> json resolved.content | GetOrderByIdStatusCode400 resolved -> - setStatusCode 400 >=> text resolved.content + setStatusCode 400 >=> text resolved.content | GetOrderByIdStatusCode404 resolved -> - setStatusCode 404 >=> text resolved.content + setStatusCode 404 >=> text resolved.content ) next ctx } //#endregion @@ -85,10 +85,10 @@ module StoreApiHandler = let serviceArgs = { bodyParams=bodyParams } : PlaceOrderArgs let result = StoreApiService.PlaceOrder ctx serviceArgs return! (match result with - | PlaceOrderDefaultStatusCode resolved -> - setStatusCode 200 >=> json resolved.content + | PlaceOrderStatusCode200 resolved -> + setStatusCode 200 >=> json resolved.content | PlaceOrderStatusCode400 resolved -> - setStatusCode 400 >=> text resolved.content + setStatusCode 400 >=> text resolved.content ) next ctx } //#endregion diff --git a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/StoreApiHandlerParams.fs b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/StoreApiHandlerParams.fs index 2c9226f8abfe..dbb836432bd3 100644 --- a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/StoreApiHandlerParams.fs +++ b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/StoreApiHandlerParams.fs @@ -31,11 +31,11 @@ module StoreApiHandlerParams = } - type GetInventoryDefaultStatusCodeResponse = { + type GetInventoryStatusCode200Response = { content:IDictionary; } - type GetInventoryResult = GetInventoryDefaultStatusCode of GetInventoryDefaultStatusCodeResponse + type GetInventoryResult = GetInventoryStatusCode200 of GetInventoryStatusCode200Response //#region Path parameters [] @@ -45,7 +45,7 @@ module StoreApiHandlerParams = //#endregion - type GetOrderByIdDefaultStatusCodeResponse = { + type GetOrderByIdStatusCode200Response = { content:Order; } @@ -59,7 +59,7 @@ module StoreApiHandlerParams = content:string; } - type GetOrderByIdResult = GetOrderByIdDefaultStatusCode of GetOrderByIdDefaultStatusCodeResponse|GetOrderByIdStatusCode400 of GetOrderByIdStatusCode400Response|GetOrderByIdStatusCode404 of GetOrderByIdStatusCode404Response + type GetOrderByIdResult = GetOrderByIdStatusCode200 of GetOrderByIdStatusCode200Response|GetOrderByIdStatusCode400 of GetOrderByIdStatusCode400Response|GetOrderByIdStatusCode404 of GetOrderByIdStatusCode404Response type GetOrderByIdArgs = { pathParams:GetOrderByIdPathParams; @@ -71,7 +71,7 @@ module StoreApiHandlerParams = //#endregion - type PlaceOrderDefaultStatusCodeResponse = { + type PlaceOrderStatusCode200Response = { content:Order; } @@ -80,7 +80,7 @@ module StoreApiHandlerParams = content:string; } - type PlaceOrderResult = PlaceOrderDefaultStatusCode of PlaceOrderDefaultStatusCodeResponse|PlaceOrderStatusCode400 of PlaceOrderStatusCode400Response + type PlaceOrderResult = PlaceOrderStatusCode200 of PlaceOrderStatusCode200Response|PlaceOrderStatusCode400 of PlaceOrderStatusCode400Response type PlaceOrderArgs = { bodyParams:PlaceOrderBodyParams diff --git a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/UserApiHandler.fs b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/UserApiHandler.fs index 6994e2397416..42352b3f9118 100644 --- a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/UserApiHandler.fs +++ b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/UserApiHandler.fs @@ -29,7 +29,7 @@ module UserApiHandler = let result = UserApiService.CreateUser ctx serviceArgs return! (match result with | CreateUserDefaultStatusCode resolved -> - setStatusCode 0 >=> text resolved.content + setStatusCode 0 >=> text resolved.content ) next ctx } //#endregion @@ -48,7 +48,7 @@ module UserApiHandler = let result = UserApiService.CreateUsersWithArrayInput ctx serviceArgs return! (match result with | CreateUsersWithArrayInputDefaultStatusCode resolved -> - setStatusCode 0 >=> text resolved.content + setStatusCode 0 >=> text resolved.content ) next ctx } //#endregion @@ -67,7 +67,7 @@ module UserApiHandler = let result = UserApiService.CreateUsersWithListInput ctx serviceArgs return! (match result with | CreateUsersWithListInputDefaultStatusCode resolved -> - setStatusCode 0 >=> text resolved.content + setStatusCode 0 >=> text resolved.content ) next ctx } //#endregion @@ -84,9 +84,9 @@ module UserApiHandler = let result = UserApiService.DeleteUser ctx serviceArgs return! (match result with | DeleteUserStatusCode400 resolved -> - setStatusCode 400 >=> text resolved.content + setStatusCode 400 >=> text resolved.content | DeleteUserStatusCode404 resolved -> - setStatusCode 404 >=> text resolved.content + setStatusCode 404 >=> text resolved.content ) next ctx } //#endregion @@ -102,12 +102,12 @@ module UserApiHandler = let serviceArgs = { pathParams=pathParams; } : GetUserByNameArgs let result = UserApiService.GetUserByName ctx serviceArgs return! (match result with - | GetUserByNameDefaultStatusCode resolved -> - setStatusCode 200 >=> json resolved.content + | GetUserByNameStatusCode200 resolved -> + setStatusCode 200 >=> json resolved.content | GetUserByNameStatusCode400 resolved -> - setStatusCode 400 >=> text resolved.content + setStatusCode 400 >=> text resolved.content | GetUserByNameStatusCode404 resolved -> - setStatusCode 404 >=> text resolved.content + setStatusCode 404 >=> text resolved.content ) next ctx } //#endregion @@ -124,10 +124,10 @@ module UserApiHandler = let serviceArgs = { queryParams=queryParams; } : LoginUserArgs let result = UserApiService.LoginUser ctx serviceArgs return! (match result with - | LoginUserDefaultStatusCode resolved -> - setStatusCode 200 >=> text resolved.content + | LoginUserStatusCode200 resolved -> + setStatusCode 200 >=> text resolved.content | LoginUserStatusCode400 resolved -> - setStatusCode 400 >=> text resolved.content + setStatusCode 400 >=> text resolved.content ) next ctx } //#endregion @@ -143,7 +143,7 @@ module UserApiHandler = let result = UserApiService.LogoutUser ctx return! (match result with | LogoutUserDefaultStatusCode resolved -> - setStatusCode 0 >=> text resolved.content + setStatusCode 0 >=> text resolved.content ) next ctx } //#endregion @@ -162,9 +162,9 @@ module UserApiHandler = let result = UserApiService.UpdateUser ctx serviceArgs return! (match result with | UpdateUserStatusCode400 resolved -> - setStatusCode 400 >=> text resolved.content + setStatusCode 400 >=> text resolved.content | UpdateUserStatusCode404 resolved -> - setStatusCode 404 >=> text resolved.content + setStatusCode 404 >=> text resolved.content ) next ctx } //#endregion diff --git a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/UserApiHandlerParams.fs b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/UserApiHandlerParams.fs index 42c51c93a664..b32b849c8633 100644 --- a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/UserApiHandlerParams.fs +++ b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/api/UserApiHandlerParams.fs @@ -84,7 +84,7 @@ module UserApiHandlerParams = //#endregion - type GetUserByNameDefaultStatusCodeResponse = { + type GetUserByNameStatusCode200Response = { content:User; } @@ -98,7 +98,7 @@ module UserApiHandlerParams = content:string; } - type GetUserByNameResult = GetUserByNameDefaultStatusCode of GetUserByNameDefaultStatusCodeResponse|GetUserByNameStatusCode400 of GetUserByNameStatusCode400Response|GetUserByNameStatusCode404 of GetUserByNameStatusCode404Response + type GetUserByNameResult = GetUserByNameStatusCode200 of GetUserByNameStatusCode200Response|GetUserByNameStatusCode400 of GetUserByNameStatusCode400Response|GetUserByNameStatusCode404 of GetUserByNameStatusCode404Response type GetUserByNameArgs = { pathParams:GetUserByNamePathParams; @@ -116,7 +116,7 @@ module UserApiHandlerParams = //#endregion - type LoginUserDefaultStatusCodeResponse = { + type LoginUserStatusCode200Response = { content:string; } @@ -125,7 +125,7 @@ module UserApiHandlerParams = content:string; } - type LoginUserResult = LoginUserDefaultStatusCode of LoginUserDefaultStatusCodeResponse|LoginUserStatusCode400 of LoginUserStatusCode400Response + type LoginUserResult = LoginUserStatusCode200 of LoginUserStatusCode200Response|LoginUserStatusCode400 of LoginUserStatusCode400Response type LoginUserArgs = { queryParams:Result; diff --git a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/auth/AuthSchemes.fs b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/auth/AuthSchemes.fs index 5e1bc765d48f..d7c5dc2cb355 100644 --- a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/auth/AuthSchemes.fs +++ b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/auth/AuthSchemes.fs @@ -60,7 +60,6 @@ module AuthSchemes = let configureApiKeyAuth (settings:IConfiguration) services = buildApiKeyAuth "api_key" services - raise (NotImplementedException("API key security scheme outside of header has not yet been implemented")) let configureCookie (builder:AuthenticationBuilder) = diff --git a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/impl/CustomHandlers.fs b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/impl/CustomHandlers.fs index ef85330bb0e8..6f8dea83e0fb 100644 --- a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/impl/CustomHandlers.fs +++ b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/impl/CustomHandlers.fs @@ -79,7 +79,6 @@ module CustomHandlers = body [] [ h1 [] [ str "Welcome" ] a [_href "/login-with-api_key"] [ str "Login with api_key" ] - a [_href "/login-with-auth_cookie"] [ str "Login with auth_cookie" ] a [_href "/login-with-petstore_auth"] [ str "Login with petstore_auth" ] ] ] @@ -93,7 +92,6 @@ module CustomHandlers = choose [ route "/login" >=> redirectToLogin route "/login-with-api_key" >=> challenge "api_key" - route "/login-with-auth_cookie" >=> challenge "auth_cookie" route "/login-with-petstore_auth" >=> challenge "petstore_auth" route "/logout" >=> logout ] diff --git a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/impl/PetApiService.fs b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/impl/PetApiService.fs index 948ee5ce71a2..db576a47d853 100644 --- a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/impl/PetApiService.fs +++ b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/impl/PetApiService.fs @@ -14,6 +14,10 @@ module PetApiServiceImplementation = interface IPetApiService with member this.AddPet ctx args = + if true then + let content = "successful operation" :> obj :?> Pet // this cast is obviously wrong, and is only intended to allow generated project to compile + AddPetStatusCode200 { content = content } + else let content = "Invalid input" AddPetStatusCode405 { content = content } @@ -24,7 +28,7 @@ module PetApiServiceImplementation = member this.FindPetsByStatus ctx args = if true then let content = "successful operation" :> obj :?> Pet[] // this cast is obviously wrong, and is only intended to allow generated project to compile - FindPetsByStatusDefaultStatusCode { content = content } + FindPetsByStatusStatusCode200 { content = content } else let content = "Invalid status value" FindPetsByStatusStatusCode400 { content = content } @@ -32,7 +36,7 @@ module PetApiServiceImplementation = member this.FindPetsByTags ctx args = if true then let content = "successful operation" :> obj :?> Pet[] // this cast is obviously wrong, and is only intended to allow generated project to compile - FindPetsByTagsDefaultStatusCode { content = content } + FindPetsByTagsStatusCode200 { content = content } else let content = "Invalid tag value" FindPetsByTagsStatusCode400 { content = content } @@ -40,7 +44,7 @@ module PetApiServiceImplementation = member this.GetPetById ctx args = if true then let content = "successful operation" :> obj :?> Pet // this cast is obviously wrong, and is only intended to allow generated project to compile - GetPetByIdDefaultStatusCode { content = content } + GetPetByIdStatusCode200 { content = content } else if true then let content = "Invalid ID supplied" GetPetByIdStatusCode400 { content = content } @@ -50,6 +54,9 @@ module PetApiServiceImplementation = member this.UpdatePet ctx args = if true then + let content = "successful operation" :> obj :?> Pet // this cast is obviously wrong, and is only intended to allow generated project to compile + UpdatePetStatusCode200 { content = content } + else if true then let content = "Invalid ID supplied" UpdatePetStatusCode400 { content = content } else if true then @@ -65,7 +72,7 @@ module PetApiServiceImplementation = member this.UploadFile ctx args = let content = "successful operation" :> obj :?> ApiResponse // this cast is obviously wrong, and is only intended to allow generated project to compile - UploadFileDefaultStatusCode { content = content } + UploadFileStatusCode200 { content = content } //#endregion diff --git a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/impl/StoreApiService.fs b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/impl/StoreApiService.fs index ccb52b6e6e2a..d24dbe644c12 100644 --- a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/impl/StoreApiService.fs +++ b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/impl/StoreApiService.fs @@ -23,12 +23,12 @@ module StoreApiServiceImplementation = member this.GetInventory ctx = let content = "successful operation" :> obj :?> IDictionary // this cast is obviously wrong, and is only intended to allow generated project to compile - GetInventoryDefaultStatusCode { content = content } + GetInventoryStatusCode200 { content = content } member this.GetOrderById ctx args = if true then let content = "successful operation" :> obj :?> Order // this cast is obviously wrong, and is only intended to allow generated project to compile - GetOrderByIdDefaultStatusCode { content = content } + GetOrderByIdStatusCode200 { content = content } else if true then let content = "Invalid ID supplied" GetOrderByIdStatusCode400 { content = content } @@ -39,7 +39,7 @@ module StoreApiServiceImplementation = member this.PlaceOrder ctx args = if true then let content = "successful operation" :> obj :?> Order // this cast is obviously wrong, and is only intended to allow generated project to compile - PlaceOrderDefaultStatusCode { content = content } + PlaceOrderStatusCode200 { content = content } else let content = "Invalid Order" PlaceOrderStatusCode400 { content = content } diff --git a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/impl/UserApiService.fs b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/impl/UserApiService.fs index 853d8a3d3aef..b6e0d73cd920 100644 --- a/samples/server/petstore/fsharp-giraffe/OpenAPI/src/impl/UserApiService.fs +++ b/samples/server/petstore/fsharp-giraffe/OpenAPI/src/impl/UserApiService.fs @@ -35,7 +35,7 @@ module UserApiServiceImplementation = member this.GetUserByName ctx args = if true then let content = "successful operation" :> obj :?> User // this cast is obviously wrong, and is only intended to allow generated project to compile - GetUserByNameDefaultStatusCode { content = content } + GetUserByNameStatusCode200 { content = content } else if true then let content = "Invalid username supplied" GetUserByNameStatusCode400 { content = content } @@ -46,7 +46,7 @@ module UserApiServiceImplementation = member this.LoginUser ctx args = if true then let content = "successful operation" :> obj :?> string // this cast is obviously wrong, and is only intended to allow generated project to compile - LoginUserDefaultStatusCode { content = content } + LoginUserStatusCode200 { content = content } else let content = "Invalid username/password supplied" LoginUserStatusCode400 { content = content } diff --git a/samples/server/petstore/go-api-server/.openapi-generator/VERSION b/samples/server/petstore/go-api-server/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/go-api-server/.openapi-generator/VERSION +++ b/samples/server/petstore/go-api-server/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/go-echo-server/.docs/api/openapi.yaml b/samples/server/petstore/go-echo-server/.docs/api/openapi.yaml new file mode 100644 index 000000000000..26aaeac34b7d --- /dev/null +++ b/samples/server/petstore/go-echo-server/.docs/api/openapi.yaml @@ -0,0 +1,822 @@ +openapi: 3.0.0 +info: + description: This is a sample server Petstore server. For this sample, you can use + the api key `special-key` to test the authorization filters. + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Petstore + version: 1.0.0 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: +- url: http://petstore.swagger.io/v2 +tags: +- description: Everything about your Pets + name: pet +- description: Access to Petstore orders + name: store +- description: Operations about user + name: user +paths: + /pet: + post: + operationId: addPet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Add a new pet to the store + tags: + - pet + put: + operationId: updatePet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + "405": + description: Validation exception + security: + - petstore_auth: + - write:pets + - read:pets + summary: Update an existing pet + tags: + - pet + /pet/findByStatus: + get: + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - description: Status values that need to be considered for filter + explode: false + in: query + name: status + required: true + schema: + items: + default: available + enum: + - available + - pending + - sold + type: string + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + description: successful operation + "400": + description: Invalid status value + security: + - petstore_auth: + - read:pets + summary: Finds Pets by status + tags: + - pet + /pet/findByTags: + get: + deprecated: true + description: Multiple tags can be provided with comma separated strings. Use + tag1, tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - description: Tags to filter by + explode: false + in: query + name: tags + required: true + schema: + items: + type: string + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + description: successful operation + "400": + description: Invalid tag value + security: + - petstore_auth: + - read:pets + summary: Finds Pets by tags + tags: + - pet + /pet/{petId}: + delete: + operationId: deletePet + parameters: + - explode: false + in: header + name: api_key + required: false + schema: + type: string + style: simple + - description: Pet id to delete + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "400": + description: Invalid pet value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Deletes a pet + tags: + - pet + get: + description: Returns a single pet + operationId: getPetById + parameters: + - description: ID of pet to return + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + security: + - api_key: [] + summary: Find pet by ID + tags: + - pet + post: + operationId: updatePetWithForm + parameters: + - description: ID of pet that needs to be updated + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + $ref: '#/components/requestBodies/inline_object' + content: + application/x-www-form-urlencoded: + schema: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + type: object + responses: + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Updates a pet in the store with form data + tags: + - pet + /pet/{petId}/uploadImage: + post: + operationId: uploadFile + parameters: + - description: ID of pet to update + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + $ref: '#/components/requestBodies/inline_object_1' + content: + multipart/form-data: + schema: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + type: object + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads an image + tags: + - pet + /store/inventory: + get: + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + "200": + content: + application/json: + schema: + additionalProperties: + format: int32 + type: integer + type: object + description: successful operation + security: + - api_key: [] + summary: Returns pet inventories by status + tags: + - store + /store/order: + post: + operationId: placeOrder + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + description: successful operation + "400": + description: Invalid Order + summary: Place an order for a pet + tags: + - store + /store/order/{orderId}: + delete: + description: For valid response try integer IDs with value < 1000. Anything + above 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - description: ID of the order that needs to be deleted + explode: false + in: path + name: orderId + required: true + schema: + type: string + style: simple + responses: + "400": + description: Invalid ID supplied + "404": + description: Order not found + summary: Delete purchase order by ID + tags: + - store + get: + description: For valid response try integer IDs with value <= 5 or > 10. Other + values will generated exceptions + operationId: getOrderById + parameters: + - description: ID of pet that needs to be fetched + explode: false + in: path + name: orderId + required: true + schema: + format: int64 + maximum: 5 + minimum: 1 + type: integer + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Order not found + summary: Find purchase order by ID + tags: + - store + /user: + post: + description: This can only be done by the logged in user. + operationId: createUser + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Create user + tags: + - user + /user/createWithArray: + post: + operationId: createUsersWithArrayInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Creates list of users with given input array + tags: + - user + /user/createWithList: + post: + operationId: createUsersWithListInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Creates list of users with given input array + tags: + - user + /user/login: + get: + operationId: loginUser + parameters: + - description: The user name for login + explode: true + in: query + name: username + required: true + schema: + pattern: ^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$ + type: string + style: form + - description: The password for login in clear text + explode: true + in: query + name: password + required: true + schema: + type: string + style: form + responses: + "200": + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + description: successful operation + headers: + Set-Cookie: + description: Cookie authentication key for use with the `api_key` apiKey + authentication. + explode: false + schema: + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + type: string + style: simple + X-Rate-Limit: + description: calls per hour allowed by the user + explode: false + schema: + format: int32 + type: integer + style: simple + X-Expires-After: + description: date in UTC when toekn expires + explode: false + schema: + format: date-time + type: string + style: simple + "400": + description: Invalid username/password supplied + summary: Logs user into the system + tags: + - user + /user/logout: + get: + operationId: logoutUser + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Logs out current logged in user session + tags: + - user + /user/{username}: + delete: + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - description: The name that needs to be deleted + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + responses: + "400": + description: Invalid username supplied + "404": + description: User not found + security: + - api_key: [] + summary: Delete user + tags: + - user + get: + operationId: getUserByName + parameters: + - description: The name that needs to be fetched. Use user1 for testing. + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + description: successful operation + "400": + description: Invalid username supplied + "404": + description: User not found + summary: Get user by user name + tags: + - user + put: + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - description: name that need to be deleted + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + responses: + "400": + description: Invalid user supplied + "404": + description: User not found + security: + - api_key: [] + summary: Updated user + tags: + - user +components: + requestBodies: + UserArray: + content: + application/json: + schema: + items: + $ref: '#/components/schemas/User' + type: array + description: List of user object + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + inline_object: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/inline_object' + inline_object_1: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/inline_object_1' + schemas: + Order: + description: An order for a pets from the pet store + example: + petId: 6 + quantity: 1 + id: 0 + shipDate: 2000-01-23T04:56:07.000+00:00 + complete: false + status: placed + properties: + id: + format: int64 + type: integer + petId: + format: int64 + type: integer + quantity: + format: int32 + type: integer + shipDate: + format: date-time + type: string + status: + description: Order Status + enum: + - placed + - approved + - delivered + type: string + complete: + default: false + type: boolean + title: Pet Order + type: object + xml: + name: Order + Category: + description: A category for a pet + example: + name: name + id: 6 + properties: + id: + format: int64 + type: integer + name: + pattern: ^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$ + type: string + title: Pet category + type: object + xml: + name: Category + User: + description: A User who is purchasing from the pet store + example: + firstName: firstName + lastName: lastName + password: password + userStatus: 6 + phone: phone + id: 0 + email: email + username: username + properties: + id: + format: int64 + type: integer + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + description: User Status + format: int32 + type: integer + title: a User + type: object + xml: + name: User + Tag: + description: A tag for a pet + example: + name: name + id: 1 + properties: + id: + format: int64 + type: integer + name: + type: string + title: Pet Tag + type: object + xml: + name: Tag + Pet: + description: A pet for sale in the pet store + example: + photoUrls: + - photoUrls + - photoUrls + name: doggie + id: 0 + category: + name: name + id: 6 + tags: + - name: name + id: 1 + - name: name + id: 1 + status: available + properties: + id: + format: int64 + type: integer + category: + $ref: '#/components/schemas/Category' + name: + example: doggie + type: string + photoUrls: + items: + type: string + type: array + xml: + name: photoUrl + wrapped: true + tags: + items: + $ref: '#/components/schemas/Tag' + type: array + xml: + name: tag + wrapped: true + status: + description: pet status in the store + enum: + - available + - pending + - sold + type: string + required: + - name + - photoUrls + title: a Pet + type: object + xml: + name: Pet + ApiResponse: + description: Describes the result of uploading an image resource + example: + code: 0 + type: type + message: message + properties: + code: + format: int32 + type: integer + type: + type: string + message: + type: string + title: An uploaded response + type: object + inline_object: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + type: object + inline_object_1: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + type: object + securitySchemes: + petstore_auth: + flows: + implicit: + authorizationUrl: http://petstore.swagger.io/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + type: oauth2 + api_key: + in: header + name: api_key + type: apiKey diff --git a/samples/server/petstore/go-echo-server/.openapi-generator-ignore b/samples/server/petstore/go-echo-server/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/petstore/go-echo-server/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/go-echo-server/.openapi-generator/FILES b/samples/server/petstore/go-echo-server/.openapi-generator/FILES new file mode 100644 index 000000000000..1197d5a46ff0 --- /dev/null +++ b/samples/server/petstore/go-echo-server/.openapi-generator/FILES @@ -0,0 +1,16 @@ +.docs/api/openapi.yaml +Dockerfile +README.md +go.mod +handlers/api_pet.go +handlers/api_store.go +handlers/api_user.go +handlers/container.go +main.go +models/hello-world.go +models/model_api_response.go +models/model_category.go +models/model_order.go +models/model_pet.go +models/model_tag.go +models/model_user.go diff --git a/samples/server/petstore/go-echo-server/.openapi-generator/VERSION b/samples/server/petstore/go-echo-server/.openapi-generator/VERSION new file mode 100644 index 000000000000..6555596f9311 --- /dev/null +++ b/samples/server/petstore/go-echo-server/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/go-echo-server/Dockerfile b/samples/server/petstore/go-echo-server/Dockerfile new file mode 100644 index 000000000000..da7cf24944f9 --- /dev/null +++ b/samples/server/petstore/go-echo-server/Dockerfile @@ -0,0 +1,11 @@ +FROM golang:1.16-alpine3.13 as build-env +RUN apk add --no-cache git gcc +RUN mkdir /app +WORKDIR /app +COPY . . +RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o openapi +FROM alpine:3.13 +COPY --from=build-env /app/openapi . +EXPOSE 8080/tcp +USER 1001 +ENTRYPOINT ["./openapi"] \ No newline at end of file diff --git a/samples/server/petstore/go-echo-server/README.md b/samples/server/petstore/go-echo-server/README.md new file mode 100644 index 000000000000..d0c7ad18acee --- /dev/null +++ b/samples/server/petstore/go-echo-server/README.md @@ -0,0 +1,38 @@ +# Go Echo API Server for openapi + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +## Overview +This server was generated by the [openapi-generator] +(https://openapi-generator.tech) project. +By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. +- + +To see how to make this your own, look here: + +[README](https://openapi-generator.tech) + +- API version: 1.0.0 + +### Running the server + +To run the server, follow these simple steps: + +``` +go mod download +go build -o app +``` + +To run the server in a docker container +``` +docker build --network=host -t openapi . +``` + +Once the image is built, just run +``` +docker run --rm -it openapi +``` + +### Known Issue + +TBA \ No newline at end of file diff --git a/samples/server/petstore/go-echo-server/go.mod b/samples/server/petstore/go-echo-server/go.mod new file mode 100644 index 000000000000..a7d3a57f6197 --- /dev/null +++ b/samples/server/petstore/go-echo-server/go.mod @@ -0,0 +1,5 @@ +module github.com/GIT_USER_ID/GIT_REPO_ID + +go 1.16 + +require github.com/labstack/echo/v4 v4.2.0 diff --git a/samples/server/petstore/go-echo-server/handlers/api_pet.go b/samples/server/petstore/go-echo-server/handlers/api_pet.go new file mode 100644 index 000000000000..0fd09f1ff5c2 --- /dev/null +++ b/samples/server/petstore/go-echo-server/handlers/api_pet.go @@ -0,0 +1,69 @@ +package handlers +import ( + "github.com/GIT_USER_ID/GIT_REPO_ID/models" + "github.com/labstack/echo/v4" + "net/http" +) + +// AddPet - Add a new pet to the store +func (c *Container) AddPet(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} + + +// DeletePet - Deletes a pet +func (c *Container) DeletePet(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} + + +// FindPetsByStatus - Finds Pets by status +func (c *Container) FindPetsByStatus(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} + + +// FindPetsByTags - Finds Pets by tags +func (c *Container) FindPetsByTags(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} + + +// GetPetById - Find pet by ID +func (c *Container) GetPetById(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} + + +// UpdatePet - Update an existing pet +func (c *Container) UpdatePet(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} + + +// UpdatePetWithForm - Updates a pet in the store with form data +func (c *Container) UpdatePetWithForm(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} + + +// UploadFile - uploads an image +func (c *Container) UploadFile(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} diff --git a/samples/server/petstore/go-echo-server/handlers/api_store.go b/samples/server/petstore/go-echo-server/handlers/api_store.go new file mode 100644 index 000000000000..90cf94597ead --- /dev/null +++ b/samples/server/petstore/go-echo-server/handlers/api_store.go @@ -0,0 +1,37 @@ +package handlers +import ( + "github.com/GIT_USER_ID/GIT_REPO_ID/models" + "github.com/labstack/echo/v4" + "net/http" +) + +// DeleteOrder - Delete purchase order by ID +func (c *Container) DeleteOrder(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} + + +// GetInventory - Returns pet inventories by status +func (c *Container) GetInventory(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} + + +// GetOrderById - Find purchase order by ID +func (c *Container) GetOrderById(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} + + +// PlaceOrder - Place an order for a pet +func (c *Container) PlaceOrder(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} diff --git a/samples/server/petstore/go-echo-server/handlers/api_user.go b/samples/server/petstore/go-echo-server/handlers/api_user.go new file mode 100644 index 000000000000..c7893a407efb --- /dev/null +++ b/samples/server/petstore/go-echo-server/handlers/api_user.go @@ -0,0 +1,69 @@ +package handlers +import ( + "github.com/GIT_USER_ID/GIT_REPO_ID/models" + "github.com/labstack/echo/v4" + "net/http" +) + +// CreateUser - Create user +func (c *Container) CreateUser(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} + + +// CreateUsersWithArrayInput - Creates list of users with given input array +func (c *Container) CreateUsersWithArrayInput(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} + + +// CreateUsersWithListInput - Creates list of users with given input array +func (c *Container) CreateUsersWithListInput(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} + + +// DeleteUser - Delete user +func (c *Container) DeleteUser(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} + + +// GetUserByName - Get user by user name +func (c *Container) GetUserByName(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} + + +// LoginUser - Logs user into the system +func (c *Container) LoginUser(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} + + +// LogoutUser - Logs out current logged in user session +func (c *Container) LogoutUser(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} + + +// UpdateUser - Updated user +func (c *Container) UpdateUser(ctx echo.Context) error { + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) +} diff --git a/samples/server/petstore/go-echo-server/handlers/container.go b/samples/server/petstore/go-echo-server/handlers/container.go new file mode 100644 index 000000000000..330a32f51534 --- /dev/null +++ b/samples/server/petstore/go-echo-server/handlers/container.go @@ -0,0 +1,11 @@ +package handlers + +// Container will hold all dependencies for your application. +type Container struct { +} + +// NewContainer returns an empty or an initialized container for your handlers. +func NewContainer() (Container, error) { + c := Container{} + return c, nil +} \ No newline at end of file diff --git a/samples/server/petstore/go-echo-server/main.go b/samples/server/petstore/go-echo-server/main.go new file mode 100644 index 000000000000..2d4c212e23c3 --- /dev/null +++ b/samples/server/petstore/go-echo-server/main.go @@ -0,0 +1,83 @@ +package main + +import ( + "github.com/GIT_USER_ID/GIT_REPO_ID/handlers" + "github.com/labstack/echo/v4" + "github.com/labstack/echo/v4/middleware" +) + +func main() { + e := echo.New() + + //todo: handle the error! + c, _ := handlers.NewContainer() + + // Middleware + e.Use(middleware.Logger()) + e.Use(middleware.Recover()) + + + // AddPet - Add a new pet to the store + e.POST("/v2/pet", c.AddPet) + + // DeletePet - Deletes a pet + e.DELETE("/v2/pet/:petId", c.DeletePet) + + // FindPetsByStatus - Finds Pets by status + e.GET("/v2/pet/findByStatus", c.FindPetsByStatus) + + // FindPetsByTags - Finds Pets by tags + e.GET("/v2/pet/findByTags", c.FindPetsByTags) + + // GetPetById - Find pet by ID + e.GET("/v2/pet/:petId", c.GetPetById) + + // UpdatePet - Update an existing pet + e.PUT("/v2/pet", c.UpdatePet) + + // UpdatePetWithForm - Updates a pet in the store with form data + e.POST("/v2/pet/:petId", c.UpdatePetWithForm) + + // UploadFile - uploads an image + e.POST("/v2/pet/:petId/uploadImage", c.UploadFile) + + // DeleteOrder - Delete purchase order by ID + e.DELETE("/v2/store/order/:orderId", c.DeleteOrder) + + // GetInventory - Returns pet inventories by status + e.GET("/v2/store/inventory", c.GetInventory) + + // GetOrderById - Find purchase order by ID + e.GET("/v2/store/order/:orderId", c.GetOrderById) + + // PlaceOrder - Place an order for a pet + e.POST("/v2/store/order", c.PlaceOrder) + + // CreateUser - Create user + e.POST("/v2/user", c.CreateUser) + + // CreateUsersWithArrayInput - Creates list of users with given input array + e.POST("/v2/user/createWithArray", c.CreateUsersWithArrayInput) + + // CreateUsersWithListInput - Creates list of users with given input array + e.POST("/v2/user/createWithList", c.CreateUsersWithListInput) + + // DeleteUser - Delete user + e.DELETE("/v2/user/:username", c.DeleteUser) + + // GetUserByName - Get user by user name + e.GET("/v2/user/:username", c.GetUserByName) + + // LoginUser - Logs user into the system + e.GET("/v2/user/login", c.LoginUser) + + // LogoutUser - Logs out current logged in user session + e.GET("/v2/user/logout", c.LogoutUser) + + // UpdateUser - Updated user + e.PUT("/v2/user/:username", c.UpdateUser) + + + // Start server + e.Logger.Fatal(e.Start(":8080")) +} \ No newline at end of file diff --git a/samples/server/petstore/go-echo-server/models/hello-world.go b/samples/server/petstore/go-echo-server/models/hello-world.go new file mode 100644 index 000000000000..98b4d20cb613 --- /dev/null +++ b/samples/server/petstore/go-echo-server/models/hello-world.go @@ -0,0 +1,6 @@ +package models + +// HelloWorld is a sample data structure to make sure each endpoint return something. +type HelloWorld struct { + Message string `json:"message"` +} \ No newline at end of file diff --git a/samples/server/petstore/go-echo-server/models/model_api_response.go b/samples/server/petstore/go-echo-server/models/model_api_response.go new file mode 100644 index 000000000000..1d897b50181d --- /dev/null +++ b/samples/server/petstore/go-echo-server/models/model_api_response.go @@ -0,0 +1,11 @@ +package models + +// ApiResponse - Describes the result of uploading an image resource +type ApiResponse struct { + + Code int32 `json:"code,omitempty"` + + Type string `json:"type,omitempty"` + + Message string `json:"message,omitempty"` +} diff --git a/samples/server/petstore/go-echo-server/models/model_category.go b/samples/server/petstore/go-echo-server/models/model_category.go new file mode 100644 index 000000000000..e165eb44563c --- /dev/null +++ b/samples/server/petstore/go-echo-server/models/model_category.go @@ -0,0 +1,9 @@ +package models + +// Category - A category for a pet +type Category struct { + + Id int64 `json:"id,omitempty"` + + Name string `json:"name,omitempty"` +} diff --git a/samples/server/petstore/go-echo-server/models/model_order.go b/samples/server/petstore/go-echo-server/models/model_order.go new file mode 100644 index 000000000000..c58f51887118 --- /dev/null +++ b/samples/server/petstore/go-echo-server/models/model_order.go @@ -0,0 +1,22 @@ +package models + +import ( + "time" +) + +// Order - An order for a pets from the pet store +type Order struct { + + Id int64 `json:"id,omitempty"` + + PetId int64 `json:"petId,omitempty"` + + Quantity int32 `json:"quantity,omitempty"` + + ShipDate time.Time `json:"shipDate,omitempty"` + + // Order Status + Status string `json:"status,omitempty"` + + Complete bool `json:"complete,omitempty"` +} diff --git a/samples/server/petstore/go-echo-server/models/model_pet.go b/samples/server/petstore/go-echo-server/models/model_pet.go new file mode 100644 index 000000000000..a315672b3bd0 --- /dev/null +++ b/samples/server/petstore/go-echo-server/models/model_pet.go @@ -0,0 +1,18 @@ +package models + +// Pet - A pet for sale in the pet store +type Pet struct { + + Id int64 `json:"id,omitempty"` + + Category Category `json:"category,omitempty"` + + Name string `json:"name"` + + PhotoUrls []string `json:"photoUrls"` + + Tags []Tag `json:"tags,omitempty"` + + // pet status in the store + Status string `json:"status,omitempty"` +} diff --git a/samples/server/petstore/go-echo-server/models/model_tag.go b/samples/server/petstore/go-echo-server/models/model_tag.go new file mode 100644 index 000000000000..9be526bd051e --- /dev/null +++ b/samples/server/petstore/go-echo-server/models/model_tag.go @@ -0,0 +1,9 @@ +package models + +// Tag - A tag for a pet +type Tag struct { + + Id int64 `json:"id,omitempty"` + + Name string `json:"name,omitempty"` +} diff --git a/samples/server/petstore/go-echo-server/models/model_user.go b/samples/server/petstore/go-echo-server/models/model_user.go new file mode 100644 index 000000000000..608e7518b451 --- /dev/null +++ b/samples/server/petstore/go-echo-server/models/model_user.go @@ -0,0 +1,22 @@ +package models + +// User - A User who is purchasing from the pet store +type User struct { + + Id int64 `json:"id,omitempty"` + + Username string `json:"username,omitempty"` + + FirstName string `json:"firstName,omitempty"` + + LastName string `json:"lastName,omitempty"` + + Email string `json:"email,omitempty"` + + Password string `json:"password,omitempty"` + + Phone string `json:"phone,omitempty"` + + // User Status + UserStatus int32 `json:"userStatus,omitempty"` +} diff --git a/samples/server/petstore/go-echo-server/pom.xml b/samples/server/petstore/go-echo-server/pom.xml new file mode 100644 index 000000000000..5e7f03d3842b --- /dev/null +++ b/samples/server/petstore/go-echo-server/pom.xml @@ -0,0 +1,62 @@ + + 4.0.0 + org.openapitools + GoEchoServer + pom + 1.0-SNAPSHOT + Go Gin Server + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + go-get + integration-test + + exec + + + go + + mod + download + + + + + go-test + integration-test + + exec + + + go + + build + -o + app + + + + + + + + diff --git a/samples/server/petstore/go-gin-api-server/.openapi-generator/VERSION b/samples/server/petstore/go-gin-api-server/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/go-gin-api-server/.openapi-generator/VERSION +++ b/samples/server/petstore/go-gin-api-server/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-msf4j/.openapi-generator/VERSION b/samples/server/petstore/java-msf4j/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/java-msf4j/.openapi-generator/VERSION +++ b/samples/server/petstore/java-msf4j/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-api-package-override/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-api-package-override/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/java-play-framework-api-package-override/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-api-package-override/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-async/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-async/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/java-play-framework-async/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-async/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-controller-only/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-controller-only/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/java-play-framework-controller-only/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-controller-only/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-fake-endpoints/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-fake-endpoints/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-no-bean-validation/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-no-bean-validation/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/java-play-framework-no-bean-validation/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-no-bean-validation/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-no-exception-handling/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-no-exception-handling/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-no-interface/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-no-interface/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/java-play-framework-no-interface/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-no-interface/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-no-nullable/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-no-nullable/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/java-play-framework-no-nullable/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-no-nullable/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-no-swagger-ui/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-no-wrap-calls/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/java-play-framework/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-undertow/.openapi-generator/VERSION b/samples/server/petstore/java-undertow/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/java-undertow/.openapi-generator/VERSION +++ b/samples/server/petstore/java-undertow/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-undertow/src/main/java/org/openapitools/handler/PathHandlerInterface.java b/samples/server/petstore/java-undertow/src/main/java/org/openapitools/handler/PathHandlerInterface.java index 41b91a89132f..362ae2441189 100644 --- a/samples/server/petstore/java-undertow/src/main/java/org/openapitools/handler/PathHandlerInterface.java +++ b/samples/server/petstore/java-undertow/src/main/java/org/openapitools/handler/PathHandlerInterface.java @@ -539,10 +539,10 @@ public interface PathHandlerInterface { *

Response headers: [CodegenProperty{openApiType='integer', baseName='X-Rate-Limit', complexType='null', getter='getxRateLimit', setter='setxRateLimit', description='calls per hour allowed by the user', dataType='Integer', datatypeWithEnum='Integer', dataFormat='int32', name='xRateLimit', min='null', max='null', defaultValue='null', defaultValueWithParam=' = data.X-Rate-Limit;', baseType='Integer', containerType='null', title='null', unescapedDescription='calls per hour allowed by the user', maxLength=null, minLength=null, pattern='null', example='null', jsonSchema='{ "type" : "integer", "format" : "int32" -}', minimum='null', maximum='null', exclusiveMinimum=false, exclusiveMaximum=false, required=false, deprecated=false, hasMoreNonReadOnly=false, isPrimitiveType=true, isModel=false, isContainer=false, isString=false, isNumeric=true, isInteger=true, isLong=false, isNumber=false, isFloat=false, isDouble=false, isDecimal=false, isByteArray=false, isBinary=false, isFile=false, isBoolean=false, isDate=false, isDateTime=false, isUuid=false, isUri=false, isEmail=false, isFreeFormObject=false, isArray=false, isMap=false, isEnum=false, isReadOnly=false, isWriteOnly=false, isNullable=false, isSelfReference=false, isCircularReference=false, isDiscriminator=false, _enum=null, allowableValues=null, items=null, additionalProperties=null, vars=[], requiredVars=[], mostInnerItems=null, vendorExtensions={}, hasValidation=false, isInherited=false, discriminatorValue='null', nameInCamelCase='XRateLimit', nameInSnakeCase='X_RATE_LIMIT', enumName='null', maxItems=null, minItems=null, maxProperties=null, minProperties=null, uniqueItems=false, multipleOf=null, isXmlAttribute=false, xmlPrefix='null', xmlName='null', xmlNamespace='null', isXmlWrapped=false, isNull=false, getAdditionalPropertiesIsAnyType=false, getHasVars=false, getHasRequired=false}, CodegenProperty{openApiType='string', baseName='X-Expires-After', complexType='Date', getter='getxExpiresAfter', setter='setxExpiresAfter', description='date in UTC when toekn expires', dataType='Date', datatypeWithEnum='Date', dataFormat='date-time', name='xExpiresAfter', min='null', max='null', defaultValue='null', defaultValueWithParam=' = data.X-Expires-After;', baseType='Date', containerType='null', title='null', unescapedDescription='date in UTC when toekn expires', maxLength=null, minLength=null, pattern='null', example='null', jsonSchema='{ +}', minimum='null', maximum='null', exclusiveMinimum=false, exclusiveMaximum=false, required=false, deprecated=false, hasMoreNonReadOnly=false, isPrimitiveType=true, isModel=false, isContainer=false, isString=false, isNumeric=true, isInteger=true, isShort=true, isLong=false, isUnboundedInteger=false, isNumber=false, isFloat=false, isDouble=false, isDecimal=false, isByteArray=false, isBinary=false, isFile=false, isBoolean=false, isDate=false, isDateTime=false, isUuid=false, isUri=false, isEmail=false, isFreeFormObject=false, isArray=false, isMap=false, isEnum=false, isReadOnly=false, isWriteOnly=false, isNullable=false, isSelfReference=false, isCircularReference=false, isDiscriminator=false, _enum=null, allowableValues=null, items=null, additionalProperties=null, vars=[], requiredVars=[], mostInnerItems=null, vendorExtensions={}, hasValidation=false, isInherited=false, discriminatorValue='null', nameInCamelCase='XRateLimit', nameInSnakeCase='X_RATE_LIMIT', enumName='null', maxItems=null, minItems=null, maxProperties=null, minProperties=null, uniqueItems=false, multipleOf=null, isXmlAttribute=false, xmlPrefix='null', xmlName='null', xmlNamespace='null', isXmlWrapped=false, isNull=false, getAdditionalPropertiesIsAnyType=false, getHasVars=false, getHasRequired=false}, CodegenProperty{openApiType='string', baseName='X-Expires-After', complexType='Date', getter='getxExpiresAfter', setter='setxExpiresAfter', description='date in UTC when toekn expires', dataType='Date', datatypeWithEnum='Date', dataFormat='date-time', name='xExpiresAfter', min='null', max='null', defaultValue='null', defaultValueWithParam=' = data.X-Expires-After;', baseType='Date', containerType='null', title='null', unescapedDescription='date in UTC when toekn expires', maxLength=null, minLength=null, pattern='null', example='null', jsonSchema='{ "type" : "string", "format" : "date-time" -}', minimum='null', maximum='null', exclusiveMinimum=false, exclusiveMaximum=false, required=false, deprecated=false, hasMoreNonReadOnly=false, isPrimitiveType=false, isModel=false, isContainer=false, isString=false, isNumeric=false, isInteger=false, isLong=false, isNumber=false, isFloat=false, isDouble=false, isDecimal=false, isByteArray=false, isBinary=false, isFile=false, isBoolean=false, isDate=false, isDateTime=true, isUuid=false, isUri=false, isEmail=false, isFreeFormObject=false, isArray=false, isMap=false, isEnum=false, isReadOnly=false, isWriteOnly=false, isNullable=false, isSelfReference=false, isCircularReference=false, isDiscriminator=false, _enum=null, allowableValues=null, items=null, additionalProperties=null, vars=[], requiredVars=[], mostInnerItems=null, vendorExtensions={}, hasValidation=false, isInherited=false, discriminatorValue='null', nameInCamelCase='XExpiresAfter', nameInSnakeCase='X_EXPIRES_AFTER', enumName='null', maxItems=null, minItems=null, maxProperties=null, minProperties=null, uniqueItems=false, multipleOf=null, isXmlAttribute=false, xmlPrefix='null', xmlName='null', xmlNamespace='null', isXmlWrapped=false, isNull=false, getAdditionalPropertiesIsAnyType=false, getHasVars=false, getHasRequired=false}]

+}', minimum='null', maximum='null', exclusiveMinimum=false, exclusiveMaximum=false, required=false, deprecated=false, hasMoreNonReadOnly=false, isPrimitiveType=false, isModel=false, isContainer=false, isString=false, isNumeric=false, isInteger=false, isShort=false, isLong=false, isUnboundedInteger=false, isNumber=false, isFloat=false, isDouble=false, isDecimal=false, isByteArray=false, isBinary=false, isFile=false, isBoolean=false, isDate=false, isDateTime=true, isUuid=false, isUri=false, isEmail=false, isFreeFormObject=false, isArray=false, isMap=false, isEnum=false, isReadOnly=false, isWriteOnly=false, isNullable=false, isSelfReference=false, isCircularReference=false, isDiscriminator=false, _enum=null, allowableValues=null, items=null, additionalProperties=null, vars=[], requiredVars=[], mostInnerItems=null, vendorExtensions={}, hasValidation=false, isInherited=false, discriminatorValue='null', nameInCamelCase='XExpiresAfter', nameInSnakeCase='X_EXPIRES_AFTER', enumName='null', maxItems=null, minItems=null, maxProperties=null, minProperties=null, uniqueItems=false, multipleOf=null, isXmlAttribute=false, xmlPrefix='null', xmlName='null', xmlNamespace='null', isXmlWrapped=false, isNull=false, getAdditionalPropertiesIsAnyType=false, getHasVars=false, getHasRequired=false}]

* *

Produces: [{mediaType=application/xml}, {mediaType=application/json}]

*

Returns: {@link String}

diff --git a/samples/server/petstore/java-vertx-web/.openapi-generator/VERSION b/samples/server/petstore/java-vertx-web/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/java-vertx-web/.openapi-generator/VERSION +++ b/samples/server/petstore/java-vertx-web/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-cxf-annotated-base-path/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-cdi-default-value/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-cxf-cdi-default-value/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi-default-value/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-cxf-cdi-default-value/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-cdi/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-cxf-cdi/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-cxf-cdi/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-cxf-non-spring-app/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-cxf/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs-cxf/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-cxf/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-datelib-j8/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-datelib-j8/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-datelib-j8/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java index 2177f6a70a32..c9f806f7d523 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java @@ -46,7 +46,7 @@ public AdditionalPropertiesAnyType name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java index c15893f94a9d..61a99c3d4b87 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java @@ -47,7 +47,7 @@ public AdditionalPropertiesArray name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java index 7858bc6c063f..0370765dcc20 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java @@ -46,7 +46,7 @@ public AdditionalPropertiesBoolean name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index 6cb8e220db95..7174c0f0eb67 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -106,7 +106,7 @@ public AdditionalPropertiesClass putMapStringItem(String key, String mapStringIt * Get mapString * @return mapString **/ - @JsonProperty("map_string") + @JsonProperty(value = "map_string") @ApiModelProperty(value = "") public Map getMapString() { @@ -134,7 +134,7 @@ public AdditionalPropertiesClass putMapNumberItem(String key, BigDecimal mapNumb * Get mapNumber * @return mapNumber **/ - @JsonProperty("map_number") + @JsonProperty(value = "map_number") @ApiModelProperty(value = "") @Valid public Map getMapNumber() { @@ -162,7 +162,7 @@ public AdditionalPropertiesClass putMapIntegerItem(String key, Integer mapIntege * Get mapInteger * @return mapInteger **/ - @JsonProperty("map_integer") + @JsonProperty(value = "map_integer") @ApiModelProperty(value = "") public Map getMapInteger() { @@ -190,7 +190,7 @@ public AdditionalPropertiesClass putMapBooleanItem(String key, Boolean mapBoolea * Get mapBoolean * @return mapBoolean **/ - @JsonProperty("map_boolean") + @JsonProperty(value = "map_boolean") @ApiModelProperty(value = "") public Map getMapBoolean() { @@ -218,7 +218,7 @@ public AdditionalPropertiesClass putMapArrayIntegerItem(String key, List> getMapArrayInteger() { @@ -246,7 +246,7 @@ public AdditionalPropertiesClass putMapArrayAnytypeItem(String key, List * Get mapArrayAnytype * @return mapArrayAnytype **/ - @JsonProperty("map_array_anytype") + @JsonProperty(value = "map_array_anytype") @ApiModelProperty(value = "") @Valid public Map> getMapArrayAnytype() { @@ -274,7 +274,7 @@ public AdditionalPropertiesClass putMapMapStringItem(String key, Map> getMapMapString() { @@ -302,7 +302,7 @@ public AdditionalPropertiesClass putMapMapAnytypeItem(String key, Map> getMapMapAnytype() { @@ -322,7 +322,7 @@ public AdditionalPropertiesClass anytype1(Object anytype1) { * Get anytype1 * @return anytype1 **/ - @JsonProperty("anytype_1") + @JsonProperty(value = "anytype_1") @ApiModelProperty(value = "") public Object getAnytype1() { @@ -342,7 +342,7 @@ public AdditionalPropertiesClass anytype2(Object anytype2) { * Get anytype2 * @return anytype2 **/ - @JsonProperty("anytype_2") + @JsonProperty(value = "anytype_2") @ApiModelProperty(value = "") public Object getAnytype2() { @@ -362,7 +362,7 @@ public AdditionalPropertiesClass anytype3(Object anytype3) { * Get anytype3 * @return anytype3 **/ - @JsonProperty("anytype_3") + @JsonProperty(value = "anytype_3") @ApiModelProperty(value = "") public Object getAnytype3() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java index a51877c6e514..f7ecf1a1106e 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java @@ -46,7 +46,7 @@ public AdditionalPropertiesInteger name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java index 808ed25b4ad4..8608ce3f5918 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java @@ -47,7 +47,7 @@ public AdditionalPropertiesNumber name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java index 0d224bd8ccb5..4dadea8d0f96 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java @@ -46,7 +46,7 @@ public AdditionalPropertiesObject name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java index 21294ea53de2..8fc7ab782b6f 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java @@ -46,7 +46,7 @@ public AdditionalPropertiesString name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Animal.java index f504ba2e89bd..bd20629cac45 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Animal.java @@ -57,7 +57,7 @@ public Animal className(String className) { * Get className * @return className **/ - @JsonProperty("className") + @JsonProperty(value = "className") @ApiModelProperty(required = true, value = "") @NotNull public String getClassName() { @@ -77,7 +77,7 @@ public Animal color(String color) { * Get color * @return color **/ - @JsonProperty("color") + @JsonProperty(value = "color") @ApiModelProperty(value = "") public String getColor() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index c4a31496237b..33121369fee4 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -55,7 +55,7 @@ public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayAr * Get arrayArrayNumber * @return arrayArrayNumber **/ - @JsonProperty("ArrayArrayNumber") + @JsonProperty(value = "ArrayArrayNumber") @ApiModelProperty(value = "") @Valid public List> getArrayArrayNumber() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index b164acb08585..efb1371353d9 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -55,7 +55,7 @@ public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { * Get arrayNumber * @return arrayNumber **/ - @JsonProperty("ArrayNumber") + @JsonProperty(value = "ArrayNumber") @ApiModelProperty(value = "") @Valid public List getArrayNumber() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayTest.java index 16bd74092a96..3bd201dd0617 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayTest.java @@ -65,7 +65,7 @@ public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { * Get arrayOfString * @return arrayOfString **/ - @JsonProperty("array_of_string") + @JsonProperty(value = "array_of_string") @ApiModelProperty(value = "") public List getArrayOfString() { @@ -93,7 +93,7 @@ public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) * Get arrayArrayOfInteger * @return arrayArrayOfInteger **/ - @JsonProperty("array_array_of_integer") + @JsonProperty(value = "array_array_of_integer") @ApiModelProperty(value = "") @Valid public List> getArrayArrayOfInteger() { @@ -121,7 +121,7 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI * Get arrayArrayOfModel * @return arrayArrayOfModel **/ - @JsonProperty("array_array_of_model") + @JsonProperty(value = "array_array_of_model") @ApiModelProperty(value = "") @Valid public List> getArrayArrayOfModel() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/BigCat.java index 1c94c77319b2..5e0d5ae925d7 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/BigCat.java @@ -82,7 +82,7 @@ public BigCat kind(KindEnum kind) { * Get kind * @return kind **/ - @JsonProperty("kind") + @JsonProperty(value = "kind") @ApiModelProperty(value = "") public KindEnum getKind() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/BigCatAllOf.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/BigCatAllOf.java index 9860e5423056..e2c9cc69de8b 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/BigCatAllOf.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/BigCatAllOf.java @@ -80,7 +80,7 @@ public BigCatAllOf kind(KindEnum kind) { * Get kind * @return kind **/ - @JsonProperty("kind") + @JsonProperty(value = "kind") @ApiModelProperty(value = "") public KindEnum getKind() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Capitalization.java index 21173ba5fd1b..6d180ab1ed1e 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Capitalization.java @@ -69,7 +69,7 @@ public Capitalization smallCamel(String smallCamel) { * Get smallCamel * @return smallCamel **/ - @JsonProperty("smallCamel") + @JsonProperty(value = "smallCamel") @ApiModelProperty(value = "") public String getSmallCamel() { @@ -89,7 +89,7 @@ public Capitalization capitalCamel(String capitalCamel) { * Get capitalCamel * @return capitalCamel **/ - @JsonProperty("CapitalCamel") + @JsonProperty(value = "CapitalCamel") @ApiModelProperty(value = "") public String getCapitalCamel() { @@ -109,7 +109,7 @@ public Capitalization smallSnake(String smallSnake) { * Get smallSnake * @return smallSnake **/ - @JsonProperty("small_Snake") + @JsonProperty(value = "small_Snake") @ApiModelProperty(value = "") public String getSmallSnake() { @@ -129,7 +129,7 @@ public Capitalization capitalSnake(String capitalSnake) { * Get capitalSnake * @return capitalSnake **/ - @JsonProperty("Capital_Snake") + @JsonProperty(value = "Capital_Snake") @ApiModelProperty(value = "") public String getCapitalSnake() { @@ -149,7 +149,7 @@ public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { * Get scAETHFlowPoints * @return scAETHFlowPoints **/ - @JsonProperty("SCA_ETH_Flow_Points") + @JsonProperty(value = "SCA_ETH_Flow_Points") @ApiModelProperty(value = "") public String getScAETHFlowPoints() { @@ -169,7 +169,7 @@ public Capitalization ATT_NAME(String ATT_NAME) { * Name of the pet * @return ATT_NAME **/ - @JsonProperty("ATT_NAME") + @JsonProperty(value = "ATT_NAME") @ApiModelProperty(value = "Name of the pet ") public String getATTNAME() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Cat.java index f371a81df8f3..dd713740017f 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Cat.java @@ -46,7 +46,7 @@ public Cat declawed(Boolean declawed) { * Get declawed * @return declawed **/ - @JsonProperty("declawed") + @JsonProperty(value = "declawed") @ApiModelProperty(value = "") public Boolean getDeclawed() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/CatAllOf.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/CatAllOf.java index 86715b878ddb..0fafea591aeb 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/CatAllOf.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/CatAllOf.java @@ -44,7 +44,7 @@ public CatAllOf declawed(Boolean declawed) { * Get declawed * @return declawed **/ - @JsonProperty("declawed") + @JsonProperty(value = "declawed") @ApiModelProperty(value = "") public Boolean getDeclawed() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Category.java index cc10e0fe4de6..ab8b79f3af5c 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Category.java @@ -49,7 +49,7 @@ public Category id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -69,7 +69,7 @@ public Category name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(required = true, value = "") @NotNull public String getName() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ClassModel.java index eb09d470010b..eb0be37f6d2b 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ClassModel.java @@ -45,7 +45,7 @@ public ClassModel propertyClass(String propertyClass) { * Get propertyClass * @return propertyClass **/ - @JsonProperty("_class") + @JsonProperty(value = "_class") @ApiModelProperty(value = "") public String getPropertyClass() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Client.java index d7b603e85bed..aa5d892fdf7a 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Client.java @@ -44,7 +44,7 @@ public Client client(String client) { * Get client * @return client **/ - @JsonProperty("client") + @JsonProperty(value = "client") @ApiModelProperty(value = "") public String getClient() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Dog.java index 86304bcbf2b9..3e551b65d65b 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Dog.java @@ -46,7 +46,7 @@ public Dog breed(String breed) { * Get breed * @return breed **/ - @JsonProperty("breed") + @JsonProperty(value = "breed") @ApiModelProperty(value = "") public String getBreed() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/DogAllOf.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/DogAllOf.java index 25ee4a8ed382..032ee0e253f4 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/DogAllOf.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/DogAllOf.java @@ -44,7 +44,7 @@ public DogAllOf breed(String breed) { * Get breed * @return breed **/ - @JsonProperty("breed") + @JsonProperty(value = "breed") @ApiModelProperty(value = "") public String getBreed() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/EnumArrays.java index 0bd13b121484..99eccbc1e0c6 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/EnumArrays.java @@ -114,7 +114,7 @@ public EnumArrays justSymbol(JustSymbolEnum justSymbol) { * Get justSymbol * @return justSymbol **/ - @JsonProperty("just_symbol") + @JsonProperty(value = "just_symbol") @ApiModelProperty(value = "") public JustSymbolEnum getJustSymbol() { @@ -142,7 +142,7 @@ public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { * Get arrayEnum * @return arrayEnum **/ - @JsonProperty("array_enum") + @JsonProperty(value = "array_enum") @ApiModelProperty(value = "") public List getArrayEnum() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/EnumTest.java index 06c0cd2730b3..5f19eca41622 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/EnumTest.java @@ -194,7 +194,7 @@ public EnumTest enumString(EnumStringEnum enumString) { * Get enumString * @return enumString **/ - @JsonProperty("enum_string") + @JsonProperty(value = "enum_string") @ApiModelProperty(value = "") public EnumStringEnum getEnumString() { @@ -214,7 +214,7 @@ public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { * Get enumStringRequired * @return enumStringRequired **/ - @JsonProperty("enum_string_required") + @JsonProperty(value = "enum_string_required") @ApiModelProperty(required = true, value = "") @NotNull public EnumStringRequiredEnum getEnumStringRequired() { @@ -234,7 +234,7 @@ public EnumTest enumInteger(EnumIntegerEnum enumInteger) { * Get enumInteger * @return enumInteger **/ - @JsonProperty("enum_integer") + @JsonProperty(value = "enum_integer") @ApiModelProperty(value = "") public EnumIntegerEnum getEnumInteger() { @@ -254,7 +254,7 @@ public EnumTest enumNumber(EnumNumberEnum enumNumber) { * Get enumNumber * @return enumNumber **/ - @JsonProperty("enum_number") + @JsonProperty(value = "enum_number") @ApiModelProperty(value = "") public EnumNumberEnum getEnumNumber() { @@ -274,7 +274,7 @@ public EnumTest outerEnum(OuterEnum outerEnum) { * Get outerEnum * @return outerEnum **/ - @JsonProperty("outerEnum") + @JsonProperty(value = "outerEnum") @ApiModelProperty(value = "") @Valid public OuterEnum getOuterEnum() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 13078766c9ba..7debd01e8dd0 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -51,7 +51,7 @@ public FileSchemaTestClass file(java.io.File file) { * Get file * @return file **/ - @JsonProperty("file") + @JsonProperty(value = "file") @ApiModelProperty(value = "") @Valid public java.io.File getFile() { @@ -79,7 +79,7 @@ public FileSchemaTestClass addFilesItem(java.io.File filesItem) { * Get files * @return files **/ - @JsonProperty("files") + @JsonProperty(value = "files") @ApiModelProperty(value = "") @Valid public List getFiles() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/FormatTest.java index c3022356f9f2..e6b1aea1570f 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/FormatTest.java @@ -116,7 +116,7 @@ public FormatTest integer(Integer integer) { * maximum: 100 * @return integer **/ - @JsonProperty("integer") + @JsonProperty(value = "integer") @ApiModelProperty(value = "") @Min(10) @Max(100) public Integer getInteger() { @@ -138,7 +138,7 @@ public FormatTest int32(Integer int32) { * maximum: 200 * @return int32 **/ - @JsonProperty("int32") + @JsonProperty(value = "int32") @ApiModelProperty(value = "") @Min(20) @Max(200) public Integer getInt32() { @@ -158,7 +158,7 @@ public FormatTest int64(Long int64) { * Get int64 * @return int64 **/ - @JsonProperty("int64") + @JsonProperty(value = "int64") @ApiModelProperty(value = "") public Long getInt64() { @@ -180,7 +180,7 @@ public FormatTest number(BigDecimal number) { * maximum: 543.2 * @return number **/ - @JsonProperty("number") + @JsonProperty(value = "number") @ApiModelProperty(required = true, value = "") @NotNull @Valid @DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { @@ -202,7 +202,7 @@ public FormatTest _float(Float _float) { * maximum: 987.6 * @return _float **/ - @JsonProperty("float") + @JsonProperty(value = "float") @ApiModelProperty(value = "") @DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { @@ -224,7 +224,7 @@ public FormatTest _double(Double _double) { * maximum: 123.4 * @return _double **/ - @JsonProperty("double") + @JsonProperty(value = "double") @ApiModelProperty(value = "") @DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { @@ -244,7 +244,7 @@ public FormatTest string(String string) { * Get string * @return string **/ - @JsonProperty("string") + @JsonProperty(value = "string") @ApiModelProperty(value = "") @Pattern(regexp="/[a-z]/i") public String getString() { @@ -264,7 +264,7 @@ public FormatTest _byte(byte[] _byte) { * Get _byte * @return _byte **/ - @JsonProperty("byte") + @JsonProperty(value = "byte") @ApiModelProperty(required = true, value = "") @NotNull public byte[] getByte() { @@ -284,7 +284,7 @@ public FormatTest binary(File binary) { * Get binary * @return binary **/ - @JsonProperty("binary") + @JsonProperty(value = "binary") @ApiModelProperty(value = "") public File getBinary() { @@ -304,7 +304,7 @@ public FormatTest date(LocalDate date) { * Get date * @return date **/ - @JsonProperty("date") + @JsonProperty(value = "date") @ApiModelProperty(required = true, value = "") @NotNull public LocalDate getDate() { @@ -324,7 +324,7 @@ public FormatTest dateTime(OffsetDateTime dateTime) { * Get dateTime * @return dateTime **/ - @JsonProperty("dateTime") + @JsonProperty(value = "dateTime") @ApiModelProperty(value = "") public OffsetDateTime getDateTime() { @@ -344,7 +344,7 @@ public FormatTest uuid(UUID uuid) { * Get uuid * @return uuid **/ - @JsonProperty("uuid") + @JsonProperty(value = "uuid") @ApiModelProperty(example = "72f98069-206d-4f12-9f12-3d1e525a8e84", value = "") public UUID getUuid() { @@ -364,7 +364,7 @@ public FormatTest password(String password) { * Get password * @return password **/ - @JsonProperty("password") + @JsonProperty(value = "password") @ApiModelProperty(required = true, value = "") @NotNull @Size(min=10,max=64) public String getPassword() { @@ -384,7 +384,7 @@ public FormatTest bigDecimal(BigDecimal bigDecimal) { * Get bigDecimal * @return bigDecimal **/ - @JsonProperty("BigDecimal") + @JsonProperty(value = "BigDecimal") @ApiModelProperty(value = "") @Valid public BigDecimal getBigDecimal() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index 4a85a3526299..49e5c178cc2f 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -49,7 +49,7 @@ public HasOnlyReadOnly bar(String bar) { * Get bar * @return bar **/ - @JsonProperty("bar") + @JsonProperty(value = "bar", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getBar() { @@ -69,7 +69,7 @@ public HasOnlyReadOnly foo(String foo) { * Get foo * @return foo **/ - @JsonProperty("foo") + @JsonProperty(value = "foo", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getFoo() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/MapTest.java index ea710248eb3a..0f920d2a3ea6 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/MapTest.java @@ -102,7 +102,7 @@ public MapTest putMapMapOfStringItem(String key, Map mapMapOfStr * Get mapMapOfString * @return mapMapOfString **/ - @JsonProperty("map_map_of_string") + @JsonProperty(value = "map_map_of_string") @ApiModelProperty(value = "") @Valid public Map> getMapMapOfString() { @@ -130,7 +130,7 @@ public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) * Get mapOfEnumString * @return mapOfEnumString **/ - @JsonProperty("map_of_enum_string") + @JsonProperty(value = "map_of_enum_string") @ApiModelProperty(value = "") public Map getMapOfEnumString() { @@ -158,7 +158,7 @@ public MapTest putDirectMapItem(String key, Boolean directMapItem) { * Get directMap * @return directMap **/ - @JsonProperty("direct_map") + @JsonProperty(value = "direct_map") @ApiModelProperty(value = "") public Map getDirectMap() { @@ -186,7 +186,7 @@ public MapTest putIndirectMapItem(String key, Boolean indirectMapItem) { * Get indirectMap * @return indirectMap **/ - @JsonProperty("indirect_map") + @JsonProperty(value = "indirect_map") @ApiModelProperty(value = "") public Map getIndirectMap() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index a404fc161d0b..56f41997d170 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -60,7 +60,7 @@ public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { * Get uuid * @return uuid **/ - @JsonProperty("uuid") + @JsonProperty(value = "uuid") @ApiModelProperty(value = "") public UUID getUuid() { @@ -80,7 +80,7 @@ public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateT * Get dateTime * @return dateTime **/ - @JsonProperty("dateTime") + @JsonProperty(value = "dateTime") @ApiModelProperty(value = "") public OffsetDateTime getDateTime() { @@ -108,7 +108,7 @@ public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal * Get map * @return map **/ - @JsonProperty("map") + @JsonProperty(value = "map") @ApiModelProperty(value = "") @Valid public Map getMap() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Model200Response.java index de4421e21e13..3d502128b84d 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Model200Response.java @@ -50,7 +50,7 @@ public Model200Response name(Integer name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public Integer getName() { @@ -70,7 +70,7 @@ public Model200Response propertyClass(String propertyClass) { * Get propertyClass * @return propertyClass **/ - @JsonProperty("class") + @JsonProperty(value = "class") @ApiModelProperty(value = "") public String getPropertyClass() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelApiResponse.java index 3fe631f5c022..d2b4bcc66cd9 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -54,7 +54,7 @@ public ModelApiResponse code(Integer code) { * Get code * @return code **/ - @JsonProperty("code") + @JsonProperty(value = "code") @ApiModelProperty(value = "") public Integer getCode() { @@ -74,7 +74,7 @@ public ModelApiResponse type(String type) { * Get type * @return type **/ - @JsonProperty("type") + @JsonProperty(value = "type") @ApiModelProperty(value = "") public String getType() { @@ -94,7 +94,7 @@ public ModelApiResponse message(String message) { * Get message * @return message **/ - @JsonProperty("message") + @JsonProperty(value = "message") @ApiModelProperty(value = "") public String getMessage() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelReturn.java index a33c8543b53c..628e4e58975b 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelReturn.java @@ -45,7 +45,7 @@ public ModelReturn _return(Integer _return) { * Get _return * @return _return **/ - @JsonProperty("return") + @JsonProperty(value = "return") @ApiModelProperty(value = "") public Integer getReturn() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Name.java index e0e88d4acd1e..deeead372d63 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Name.java @@ -60,7 +60,7 @@ public Name name(Integer name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(required = true, value = "") @NotNull public Integer getName() { @@ -80,7 +80,7 @@ public Name snakeCase(Integer snakeCase) { * Get snakeCase * @return snakeCase **/ - @JsonProperty("snake_case") + @JsonProperty(value = "snake_case", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public Integer getSnakeCase() { @@ -100,7 +100,7 @@ public Name property(String property) { * Get property * @return property **/ - @JsonProperty("property") + @JsonProperty(value = "property") @ApiModelProperty(value = "") public String getProperty() { @@ -120,7 +120,7 @@ public Name _123number(Integer _123number) { * Get _123number * @return _123number **/ - @JsonProperty("123Number") + @JsonProperty(value = "123Number", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public Integer get123number() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/NumberOnly.java index 6dfda96ddced..63a02a6fceda 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/NumberOnly.java @@ -45,7 +45,7 @@ public NumberOnly justNumber(BigDecimal justNumber) { * Get justNumber * @return justNumber **/ - @JsonProperty("JustNumber") + @JsonProperty(value = "JustNumber") @ApiModelProperty(value = "") @Valid public BigDecimal getJustNumber() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Order.java index c953dbccbb9a..87a841661665 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Order.java @@ -104,7 +104,7 @@ public Order id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -124,7 +124,7 @@ public Order petId(Long petId) { * Get petId * @return petId **/ - @JsonProperty("petId") + @JsonProperty(value = "petId") @ApiModelProperty(value = "") public Long getPetId() { @@ -144,7 +144,7 @@ public Order quantity(Integer quantity) { * Get quantity * @return quantity **/ - @JsonProperty("quantity") + @JsonProperty(value = "quantity") @ApiModelProperty(value = "") public Integer getQuantity() { @@ -164,7 +164,7 @@ public Order shipDate(OffsetDateTime shipDate) { * Get shipDate * @return shipDate **/ - @JsonProperty("shipDate") + @JsonProperty(value = "shipDate") @ApiModelProperty(value = "") public OffsetDateTime getShipDate() { @@ -184,7 +184,7 @@ public Order status(StatusEnum status) { * Order Status * @return status **/ - @JsonProperty("status") + @JsonProperty(value = "status") @ApiModelProperty(value = "Order Status") public StatusEnum getStatus() { @@ -204,7 +204,7 @@ public Order complete(Boolean complete) { * Get complete * @return complete **/ - @JsonProperty("complete") + @JsonProperty(value = "complete") @ApiModelProperty(value = "") public Boolean getComplete() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/OuterComposite.java index 943768a62507..0c90b69d363d 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/OuterComposite.java @@ -55,7 +55,7 @@ public OuterComposite myNumber(BigDecimal myNumber) { * Get myNumber * @return myNumber **/ - @JsonProperty("my_number") + @JsonProperty(value = "my_number") @ApiModelProperty(value = "") @Valid public BigDecimal getMyNumber() { @@ -75,7 +75,7 @@ public OuterComposite myString(String myString) { * Get myString * @return myString **/ - @JsonProperty("my_string") + @JsonProperty(value = "my_string") @ApiModelProperty(value = "") public String getMyString() { @@ -95,7 +95,7 @@ public OuterComposite myBoolean(Boolean myBoolean) { * Get myBoolean * @return myBoolean **/ - @JsonProperty("my_boolean") + @JsonProperty(value = "my_boolean") @ApiModelProperty(value = "") public Boolean getMyBoolean() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Pet.java index 2537652ce8ba..6d027716816b 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Pet.java @@ -109,7 +109,7 @@ public Pet id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -129,7 +129,7 @@ public Pet category(Category category) { * Get category * @return category **/ - @JsonProperty("category") + @JsonProperty(value = "category") @ApiModelProperty(value = "") @Valid public Category getCategory() { @@ -149,7 +149,7 @@ public Pet name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(example = "doggie", required = true, value = "") @NotNull public String getName() { @@ -174,7 +174,7 @@ public Pet addPhotoUrlsItem(String photoUrlsItem) { * Get photoUrls * @return photoUrls **/ - @JsonProperty("photoUrls") + @JsonProperty(value = "photoUrls") @ApiModelProperty(required = true, value = "") @NotNull public Set getPhotoUrls() { @@ -202,7 +202,7 @@ public Pet addTagsItem(Tag tagsItem) { * Get tags * @return tags **/ - @JsonProperty("tags") + @JsonProperty(value = "tags") @ApiModelProperty(value = "") @Valid public List getTags() { @@ -222,7 +222,7 @@ public Pet status(StatusEnum status) { * pet status in the store * @return status **/ - @JsonProperty("status") + @JsonProperty(value = "status") @ApiModelProperty(value = "pet status in the store") public StatusEnum getStatus() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index ff231427df0f..51d1241ba7bf 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -49,7 +49,7 @@ public ReadOnlyFirst bar(String bar) { * Get bar * @return bar **/ - @JsonProperty("bar") + @JsonProperty(value = "bar", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getBar() { @@ -69,7 +69,7 @@ public ReadOnlyFirst baz(String baz) { * Get baz * @return baz **/ - @JsonProperty("baz") + @JsonProperty(value = "baz") @ApiModelProperty(value = "") public String getBaz() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/SpecialModelName.java index 0c4fbc16fdcd..172cd981a676 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -44,7 +44,7 @@ public class SpecialModelName implements Serializable { * Get $specialPropertyName * @return $specialPropertyName **/ - @JsonProperty("$special[property.name]") + @JsonProperty(value = "$special[property.name]") @ApiModelProperty(value = "") public Long get$SpecialPropertyName() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Tag.java index 2108bd16dd6a..cfe137b1be97 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Tag.java @@ -49,7 +49,7 @@ public Tag id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -69,7 +69,7 @@ public Tag name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/TypeHolderDefault.java index 50c0860a93eb..c32060bf63a5 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/TypeHolderDefault.java @@ -67,7 +67,7 @@ public TypeHolderDefault stringItem(String stringItem) { * Get stringItem * @return stringItem **/ - @JsonProperty("string_item") + @JsonProperty(value = "string_item") @ApiModelProperty(required = true, value = "") @NotNull public String getStringItem() { @@ -87,7 +87,7 @@ public TypeHolderDefault numberItem(BigDecimal numberItem) { * Get numberItem * @return numberItem **/ - @JsonProperty("number_item") + @JsonProperty(value = "number_item") @ApiModelProperty(required = true, value = "") @NotNull @Valid public BigDecimal getNumberItem() { @@ -107,7 +107,7 @@ public TypeHolderDefault integerItem(Integer integerItem) { * Get integerItem * @return integerItem **/ - @JsonProperty("integer_item") + @JsonProperty(value = "integer_item") @ApiModelProperty(required = true, value = "") @NotNull public Integer getIntegerItem() { @@ -127,7 +127,7 @@ public TypeHolderDefault boolItem(Boolean boolItem) { * Get boolItem * @return boolItem **/ - @JsonProperty("bool_item") + @JsonProperty(value = "bool_item") @ApiModelProperty(required = true, value = "") @NotNull public Boolean getBoolItem() { @@ -152,7 +152,7 @@ public TypeHolderDefault addArrayItemItem(Integer arrayItemItem) { * Get arrayItem * @return arrayItem **/ - @JsonProperty("array_item") + @JsonProperty(value = "array_item") @ApiModelProperty(required = true, value = "") @NotNull public List getArrayItem() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/TypeHolderExample.java index f7e12684f56e..e6e731b04cfe 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/TypeHolderExample.java @@ -72,7 +72,7 @@ public TypeHolderExample stringItem(String stringItem) { * Get stringItem * @return stringItem **/ - @JsonProperty("string_item") + @JsonProperty(value = "string_item") @ApiModelProperty(example = "what", required = true, value = "") @NotNull public String getStringItem() { @@ -92,7 +92,7 @@ public TypeHolderExample numberItem(BigDecimal numberItem) { * Get numberItem * @return numberItem **/ - @JsonProperty("number_item") + @JsonProperty(value = "number_item") @ApiModelProperty(example = "1.234", required = true, value = "") @NotNull @Valid public BigDecimal getNumberItem() { @@ -112,7 +112,7 @@ public TypeHolderExample floatItem(Float floatItem) { * Get floatItem * @return floatItem **/ - @JsonProperty("float_item") + @JsonProperty(value = "float_item") @ApiModelProperty(example = "1.234", required = true, value = "") @NotNull public Float getFloatItem() { @@ -132,7 +132,7 @@ public TypeHolderExample integerItem(Integer integerItem) { * Get integerItem * @return integerItem **/ - @JsonProperty("integer_item") + @JsonProperty(value = "integer_item") @ApiModelProperty(example = "-2", required = true, value = "") @NotNull public Integer getIntegerItem() { @@ -152,7 +152,7 @@ public TypeHolderExample boolItem(Boolean boolItem) { * Get boolItem * @return boolItem **/ - @JsonProperty("bool_item") + @JsonProperty(value = "bool_item") @ApiModelProperty(example = "true", required = true, value = "") @NotNull public Boolean getBoolItem() { @@ -177,7 +177,7 @@ public TypeHolderExample addArrayItemItem(Integer arrayItemItem) { * Get arrayItem * @return arrayItem **/ - @JsonProperty("array_item") + @JsonProperty(value = "array_item") @ApiModelProperty(example = "[0, 1, 2, 3]", required = true, value = "") @NotNull public List getArrayItem() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/User.java index d8d16a00ff51..72e9b20a083e 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/User.java @@ -79,7 +79,7 @@ public User id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -99,7 +99,7 @@ public User username(String username) { * Get username * @return username **/ - @JsonProperty("username") + @JsonProperty(value = "username") @ApiModelProperty(value = "") public String getUsername() { @@ -119,7 +119,7 @@ public User firstName(String firstName) { * Get firstName * @return firstName **/ - @JsonProperty("firstName") + @JsonProperty(value = "firstName") @ApiModelProperty(value = "") public String getFirstName() { @@ -139,7 +139,7 @@ public User lastName(String lastName) { * Get lastName * @return lastName **/ - @JsonProperty("lastName") + @JsonProperty(value = "lastName") @ApiModelProperty(value = "") public String getLastName() { @@ -159,7 +159,7 @@ public User email(String email) { * Get email * @return email **/ - @JsonProperty("email") + @JsonProperty(value = "email") @ApiModelProperty(value = "") public String getEmail() { @@ -179,7 +179,7 @@ public User password(String password) { * Get password * @return password **/ - @JsonProperty("password") + @JsonProperty(value = "password") @ApiModelProperty(value = "") public String getPassword() { @@ -199,7 +199,7 @@ public User phone(String phone) { * Get phone * @return phone **/ - @JsonProperty("phone") + @JsonProperty(value = "phone") @ApiModelProperty(value = "") public String getPhone() { @@ -219,7 +219,7 @@ public User userStatus(Integer userStatus) { * User Status * @return userStatus **/ - @JsonProperty("userStatus") + @JsonProperty(value = "userStatus") @ApiModelProperty(value = "User Status") public Integer getUserStatus() { diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/XmlItem.java index 3f9ee0ed32d5..cb6de49fbdb2 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/XmlItem.java @@ -187,7 +187,7 @@ public XmlItem attributeString(String attributeString) { * Get attributeString * @return attributeString **/ - @JsonProperty("attribute_string") + @JsonProperty(value = "attribute_string") @ApiModelProperty(example = "string", value = "") public String getAttributeString() { @@ -207,7 +207,7 @@ public XmlItem attributeNumber(BigDecimal attributeNumber) { * Get attributeNumber * @return attributeNumber **/ - @JsonProperty("attribute_number") + @JsonProperty(value = "attribute_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getAttributeNumber() { @@ -227,7 +227,7 @@ public XmlItem attributeInteger(Integer attributeInteger) { * Get attributeInteger * @return attributeInteger **/ - @JsonProperty("attribute_integer") + @JsonProperty(value = "attribute_integer") @ApiModelProperty(example = "-2", value = "") public Integer getAttributeInteger() { @@ -247,7 +247,7 @@ public XmlItem attributeBoolean(Boolean attributeBoolean) { * Get attributeBoolean * @return attributeBoolean **/ - @JsonProperty("attribute_boolean") + @JsonProperty(value = "attribute_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getAttributeBoolean() { @@ -275,7 +275,7 @@ public XmlItem addWrappedArrayItem(Integer wrappedArrayItem) { * Get wrappedArray * @return wrappedArray **/ - @JsonProperty("wrapped_array") + @JsonProperty(value = "wrapped_array") @ApiModelProperty(value = "") public List getWrappedArray() { @@ -295,7 +295,7 @@ public XmlItem nameString(String nameString) { * Get nameString * @return nameString **/ - @JsonProperty("name_string") + @JsonProperty(value = "name_string") @ApiModelProperty(example = "string", value = "") public String getNameString() { @@ -315,7 +315,7 @@ public XmlItem nameNumber(BigDecimal nameNumber) { * Get nameNumber * @return nameNumber **/ - @JsonProperty("name_number") + @JsonProperty(value = "name_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getNameNumber() { @@ -335,7 +335,7 @@ public XmlItem nameInteger(Integer nameInteger) { * Get nameInteger * @return nameInteger **/ - @JsonProperty("name_integer") + @JsonProperty(value = "name_integer") @ApiModelProperty(example = "-2", value = "") public Integer getNameInteger() { @@ -355,7 +355,7 @@ public XmlItem nameBoolean(Boolean nameBoolean) { * Get nameBoolean * @return nameBoolean **/ - @JsonProperty("name_boolean") + @JsonProperty(value = "name_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getNameBoolean() { @@ -383,7 +383,7 @@ public XmlItem addNameArrayItem(Integer nameArrayItem) { * Get nameArray * @return nameArray **/ - @JsonProperty("name_array") + @JsonProperty(value = "name_array") @ApiModelProperty(value = "") public List getNameArray() { @@ -411,7 +411,7 @@ public XmlItem addNameWrappedArrayItem(Integer nameWrappedArrayItem) { * Get nameWrappedArray * @return nameWrappedArray **/ - @JsonProperty("name_wrapped_array") + @JsonProperty(value = "name_wrapped_array") @ApiModelProperty(value = "") public List getNameWrappedArray() { @@ -431,7 +431,7 @@ public XmlItem prefixString(String prefixString) { * Get prefixString * @return prefixString **/ - @JsonProperty("prefix_string") + @JsonProperty(value = "prefix_string") @ApiModelProperty(example = "string", value = "") public String getPrefixString() { @@ -451,7 +451,7 @@ public XmlItem prefixNumber(BigDecimal prefixNumber) { * Get prefixNumber * @return prefixNumber **/ - @JsonProperty("prefix_number") + @JsonProperty(value = "prefix_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getPrefixNumber() { @@ -471,7 +471,7 @@ public XmlItem prefixInteger(Integer prefixInteger) { * Get prefixInteger * @return prefixInteger **/ - @JsonProperty("prefix_integer") + @JsonProperty(value = "prefix_integer") @ApiModelProperty(example = "-2", value = "") public Integer getPrefixInteger() { @@ -491,7 +491,7 @@ public XmlItem prefixBoolean(Boolean prefixBoolean) { * Get prefixBoolean * @return prefixBoolean **/ - @JsonProperty("prefix_boolean") + @JsonProperty(value = "prefix_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getPrefixBoolean() { @@ -519,7 +519,7 @@ public XmlItem addPrefixArrayItem(Integer prefixArrayItem) { * Get prefixArray * @return prefixArray **/ - @JsonProperty("prefix_array") + @JsonProperty(value = "prefix_array") @ApiModelProperty(value = "") public List getPrefixArray() { @@ -547,7 +547,7 @@ public XmlItem addPrefixWrappedArrayItem(Integer prefixWrappedArrayItem) { * Get prefixWrappedArray * @return prefixWrappedArray **/ - @JsonProperty("prefix_wrapped_array") + @JsonProperty(value = "prefix_wrapped_array") @ApiModelProperty(value = "") public List getPrefixWrappedArray() { @@ -567,7 +567,7 @@ public XmlItem namespaceString(String namespaceString) { * Get namespaceString * @return namespaceString **/ - @JsonProperty("namespace_string") + @JsonProperty(value = "namespace_string") @ApiModelProperty(example = "string", value = "") public String getNamespaceString() { @@ -587,7 +587,7 @@ public XmlItem namespaceNumber(BigDecimal namespaceNumber) { * Get namespaceNumber * @return namespaceNumber **/ - @JsonProperty("namespace_number") + @JsonProperty(value = "namespace_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getNamespaceNumber() { @@ -607,7 +607,7 @@ public XmlItem namespaceInteger(Integer namespaceInteger) { * Get namespaceInteger * @return namespaceInteger **/ - @JsonProperty("namespace_integer") + @JsonProperty(value = "namespace_integer") @ApiModelProperty(example = "-2", value = "") public Integer getNamespaceInteger() { @@ -627,7 +627,7 @@ public XmlItem namespaceBoolean(Boolean namespaceBoolean) { * Get namespaceBoolean * @return namespaceBoolean **/ - @JsonProperty("namespace_boolean") + @JsonProperty(value = "namespace_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getNamespaceBoolean() { @@ -655,7 +655,7 @@ public XmlItem addNamespaceArrayItem(Integer namespaceArrayItem) { * Get namespaceArray * @return namespaceArray **/ - @JsonProperty("namespace_array") + @JsonProperty(value = "namespace_array") @ApiModelProperty(value = "") public List getNamespaceArray() { @@ -683,7 +683,7 @@ public XmlItem addNamespaceWrappedArrayItem(Integer namespaceWrappedArrayItem) { * Get namespaceWrappedArray * @return namespaceWrappedArray **/ - @JsonProperty("namespace_wrapped_array") + @JsonProperty(value = "namespace_wrapped_array") @ApiModelProperty(value = "") public List getNamespaceWrappedArray() { @@ -703,7 +703,7 @@ public XmlItem prefixNsString(String prefixNsString) { * Get prefixNsString * @return prefixNsString **/ - @JsonProperty("prefix_ns_string") + @JsonProperty(value = "prefix_ns_string") @ApiModelProperty(example = "string", value = "") public String getPrefixNsString() { @@ -723,7 +723,7 @@ public XmlItem prefixNsNumber(BigDecimal prefixNsNumber) { * Get prefixNsNumber * @return prefixNsNumber **/ - @JsonProperty("prefix_ns_number") + @JsonProperty(value = "prefix_ns_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getPrefixNsNumber() { @@ -743,7 +743,7 @@ public XmlItem prefixNsInteger(Integer prefixNsInteger) { * Get prefixNsInteger * @return prefixNsInteger **/ - @JsonProperty("prefix_ns_integer") + @JsonProperty(value = "prefix_ns_integer") @ApiModelProperty(example = "-2", value = "") public Integer getPrefixNsInteger() { @@ -763,7 +763,7 @@ public XmlItem prefixNsBoolean(Boolean prefixNsBoolean) { * Get prefixNsBoolean * @return prefixNsBoolean **/ - @JsonProperty("prefix_ns_boolean") + @JsonProperty(value = "prefix_ns_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getPrefixNsBoolean() { @@ -791,7 +791,7 @@ public XmlItem addPrefixNsArrayItem(Integer prefixNsArrayItem) { * Get prefixNsArray * @return prefixNsArray **/ - @JsonProperty("prefix_ns_array") + @JsonProperty(value = "prefix_ns_array") @ApiModelProperty(value = "") public List getPrefixNsArray() { @@ -819,7 +819,7 @@ public XmlItem addPrefixNsWrappedArrayItem(Integer prefixNsWrappedArrayItem) { * Get prefixNsWrappedArray * @return prefixNsWrappedArray **/ - @JsonProperty("prefix_ns_wrapped_array") + @JsonProperty(value = "prefix_ns_wrapped_array") @ApiModelProperty(value = "") public List getPrefixNsWrappedArray() { diff --git a/samples/server/petstore/jaxrs-jersey/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-jersey/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs-jersey/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-jersey/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeApi.java index 43796a701ef1..9cfd7cd8869e 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeApi.java @@ -153,10 +153,22 @@ public Response fakePropertyEnumIntegerSerialize(@ApiParam(value = "Input enum ( return delegate.fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty, securityContext); } @PUT + @Path("/body-with-binary") + @Consumes({ "image/png" }) + + @io.swagger.annotations.ApiOperation(value = "", notes = "For this test, the body has to be a binary file.", response = Void.class, tags={ "fake", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "Success", response = Void.class) + }) + public Response testBodyWithBinary(@ApiParam(value = "image to upload", required = true) @NotNull File body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testBodyWithBinary(body, securityContext); + } + @PUT @Path("/body-with-file-schema") @Consumes({ "application/json" }) - @io.swagger.annotations.ApiOperation(value = "", notes = "For this test, the body for this request much reference a schema named `File`.", response = Void.class, tags={ "fake", }) + @io.swagger.annotations.ApiOperation(value = "", notes = "For this test, the body for this request must reference a schema named `File`.", response = Void.class, tags={ "fake", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "Success", response = Void.class) }) diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeApiService.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeApiService.java index 60685a8f5ff4..e5c1a063e882 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeApiService.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeApiService.java @@ -35,6 +35,7 @@ public abstract class FakeApiService { public abstract Response fakeOuterNumberSerialize(BigDecimal body,SecurityContext securityContext) throws NotFoundException; public abstract Response fakeOuterStringSerialize(String body,SecurityContext securityContext) throws NotFoundException; public abstract Response fakePropertyEnumIntegerSerialize(OuterObjectWithEnumProperty outerObjectWithEnumProperty,SecurityContext securityContext) throws NotFoundException; + public abstract Response testBodyWithBinary(File body,SecurityContext securityContext) throws NotFoundException; public abstract Response testBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass,SecurityContext securityContext) throws NotFoundException; public abstract Response testBodyWithQueryParams( @NotNull String query,User user,SecurityContext securityContext) throws NotFoundException; public abstract Response testClientModel(Client client,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index 0429935fefbb..8c2ff2504c06 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -59,7 +59,7 @@ public AdditionalPropertiesClass putMapPropertyItem(String key, String mapProper * Get mapProperty * @return mapProperty **/ - @JsonProperty("map_property") + @JsonProperty(value = "map_property") @ApiModelProperty(value = "") public Map getMapProperty() { @@ -87,7 +87,7 @@ public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map> getMapOfMapProperty() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Animal.java index 8b8033f340ae..eec45c1f7efc 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Animal.java @@ -55,7 +55,7 @@ public Animal className(String className) { * Get className * @return className **/ - @JsonProperty("className") + @JsonProperty(value = "className") @ApiModelProperty(required = true, value = "") @NotNull public String getClassName() { @@ -75,7 +75,7 @@ public Animal color(String color) { * Get color * @return color **/ - @JsonProperty("color") + @JsonProperty(value = "color") @ApiModelProperty(value = "") public String getColor() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index cd6a16edb265..d277c77993f3 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -54,7 +54,7 @@ public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayAr * Get arrayArrayNumber * @return arrayArrayNumber **/ - @JsonProperty("ArrayArrayNumber") + @JsonProperty(value = "ArrayArrayNumber") @ApiModelProperty(value = "") @Valid public List> getArrayArrayNumber() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index 71d88cd5d890..f8b08e16723e 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -54,7 +54,7 @@ public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { * Get arrayNumber * @return arrayNumber **/ - @JsonProperty("ArrayNumber") + @JsonProperty(value = "ArrayNumber") @ApiModelProperty(value = "") @Valid public List getArrayNumber() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayTest.java index 7fdd2b52d241..fdde01afe2f5 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayTest.java @@ -64,7 +64,7 @@ public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { * Get arrayOfString * @return arrayOfString **/ - @JsonProperty("array_of_string") + @JsonProperty(value = "array_of_string") @ApiModelProperty(value = "") @Size(min=0,max=3) public List getArrayOfString() { @@ -92,7 +92,7 @@ public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) * Get arrayArrayOfInteger * @return arrayArrayOfInteger **/ - @JsonProperty("array_array_of_integer") + @JsonProperty(value = "array_array_of_integer") @ApiModelProperty(value = "") @Valid public List> getArrayArrayOfInteger() { @@ -120,7 +120,7 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI * Get arrayArrayOfModel * @return arrayArrayOfModel **/ - @JsonProperty("array_array_of_model") + @JsonProperty(value = "array_array_of_model") @ApiModelProperty(value = "") @Valid public List> getArrayArrayOfModel() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Capitalization.java index 9b99fe2b58b3..650d2c7b790b 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Capitalization.java @@ -68,7 +68,7 @@ public Capitalization smallCamel(String smallCamel) { * Get smallCamel * @return smallCamel **/ - @JsonProperty("smallCamel") + @JsonProperty(value = "smallCamel") @ApiModelProperty(value = "") public String getSmallCamel() { @@ -88,7 +88,7 @@ public Capitalization capitalCamel(String capitalCamel) { * Get capitalCamel * @return capitalCamel **/ - @JsonProperty("CapitalCamel") + @JsonProperty(value = "CapitalCamel") @ApiModelProperty(value = "") public String getCapitalCamel() { @@ -108,7 +108,7 @@ public Capitalization smallSnake(String smallSnake) { * Get smallSnake * @return smallSnake **/ - @JsonProperty("small_Snake") + @JsonProperty(value = "small_Snake") @ApiModelProperty(value = "") public String getSmallSnake() { @@ -128,7 +128,7 @@ public Capitalization capitalSnake(String capitalSnake) { * Get capitalSnake * @return capitalSnake **/ - @JsonProperty("Capital_Snake") + @JsonProperty(value = "Capital_Snake") @ApiModelProperty(value = "") public String getCapitalSnake() { @@ -148,7 +148,7 @@ public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { * Get scAETHFlowPoints * @return scAETHFlowPoints **/ - @JsonProperty("SCA_ETH_Flow_Points") + @JsonProperty(value = "SCA_ETH_Flow_Points") @ApiModelProperty(value = "") public String getScAETHFlowPoints() { @@ -168,7 +168,7 @@ public Capitalization ATT_NAME(String ATT_NAME) { * Name of the pet * @return ATT_NAME **/ - @JsonProperty("ATT_NAME") + @JsonProperty(value = "ATT_NAME") @ApiModelProperty(value = "Name of the pet ") public String getATTNAME() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Cat.java index a393506d3aa5..ef4f615bfe76 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Cat.java @@ -45,7 +45,7 @@ public Cat declawed(Boolean declawed) { * Get declawed * @return declawed **/ - @JsonProperty("declawed") + @JsonProperty(value = "declawed") @ApiModelProperty(value = "") public Boolean getDeclawed() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/CatAllOf.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/CatAllOf.java index 7e2a72595950..83503a712d2b 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/CatAllOf.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/CatAllOf.java @@ -43,7 +43,7 @@ public CatAllOf declawed(Boolean declawed) { * Get declawed * @return declawed **/ - @JsonProperty("declawed") + @JsonProperty(value = "declawed") @ApiModelProperty(value = "") public Boolean getDeclawed() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Category.java index d7a5c2b2fafa..af6055dba4ea 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Category.java @@ -48,7 +48,7 @@ public Category id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -68,7 +68,7 @@ public Category name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(required = true, value = "") @NotNull public String getName() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ClassModel.java index 00352ed5bce9..ccfe8e27684e 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ClassModel.java @@ -44,7 +44,7 @@ public ClassModel propertyClass(String propertyClass) { * Get propertyClass * @return propertyClass **/ - @JsonProperty("_class") + @JsonProperty(value = "_class") @ApiModelProperty(value = "") public String getPropertyClass() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Client.java index 04b28287ed41..0c87d7030a57 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Client.java @@ -43,7 +43,7 @@ public Client client(String client) { * Get client * @return client **/ - @JsonProperty("client") + @JsonProperty(value = "client") @ApiModelProperty(value = "") public String getClient() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Dog.java index 7d6059b2fc1f..e126444fd61e 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Dog.java @@ -45,7 +45,7 @@ public Dog breed(String breed) { * Get breed * @return breed **/ - @JsonProperty("breed") + @JsonProperty(value = "breed") @ApiModelProperty(value = "") public String getBreed() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/DogAllOf.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/DogAllOf.java index 9fcfbfb92cfc..6902a980c243 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/DogAllOf.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/DogAllOf.java @@ -43,7 +43,7 @@ public DogAllOf breed(String breed) { * Get breed * @return breed **/ - @JsonProperty("breed") + @JsonProperty(value = "breed") @ApiModelProperty(value = "") public String getBreed() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/EnumArrays.java index 526f387372ca..08e6db1ffc92 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/EnumArrays.java @@ -113,7 +113,7 @@ public EnumArrays justSymbol(JustSymbolEnum justSymbol) { * Get justSymbol * @return justSymbol **/ - @JsonProperty("just_symbol") + @JsonProperty(value = "just_symbol") @ApiModelProperty(value = "") public JustSymbolEnum getJustSymbol() { @@ -141,7 +141,7 @@ public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { * Get arrayEnum * @return arrayEnum **/ - @JsonProperty("array_enum") + @JsonProperty(value = "array_enum") @ApiModelProperty(value = "") public List getArrayEnum() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/EnumTest.java index 84a9862fa90f..c0bc2c355fad 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/EnumTest.java @@ -211,7 +211,7 @@ public EnumTest enumString(EnumStringEnum enumString) { * Get enumString * @return enumString **/ - @JsonProperty("enum_string") + @JsonProperty(value = "enum_string") @ApiModelProperty(value = "") public EnumStringEnum getEnumString() { @@ -231,7 +231,7 @@ public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { * Get enumStringRequired * @return enumStringRequired **/ - @JsonProperty("enum_string_required") + @JsonProperty(value = "enum_string_required") @ApiModelProperty(required = true, value = "") @NotNull public EnumStringRequiredEnum getEnumStringRequired() { @@ -251,7 +251,7 @@ public EnumTest enumInteger(EnumIntegerEnum enumInteger) { * Get enumInteger * @return enumInteger **/ - @JsonProperty("enum_integer") + @JsonProperty(value = "enum_integer") @ApiModelProperty(value = "") public EnumIntegerEnum getEnumInteger() { @@ -271,7 +271,7 @@ public EnumTest enumNumber(EnumNumberEnum enumNumber) { * Get enumNumber * @return enumNumber **/ - @JsonProperty("enum_number") + @JsonProperty(value = "enum_number") @ApiModelProperty(value = "") public EnumNumberEnum getEnumNumber() { @@ -291,7 +291,7 @@ public EnumTest outerEnum(OuterEnum outerEnum) { * Get outerEnum * @return outerEnum **/ - @JsonProperty("outerEnum") + @JsonProperty(value = "outerEnum") @ApiModelProperty(value = "") @Valid public OuterEnum getOuterEnum() { @@ -311,7 +311,7 @@ public EnumTest outerEnumInteger(OuterEnumInteger outerEnumInteger) { * Get outerEnumInteger * @return outerEnumInteger **/ - @JsonProperty("outerEnumInteger") + @JsonProperty(value = "outerEnumInteger") @ApiModelProperty(value = "") @Valid public OuterEnumInteger getOuterEnumInteger() { @@ -331,7 +331,7 @@ public EnumTest outerEnumDefaultValue(OuterEnumDefaultValue outerEnumDefaultValu * Get outerEnumDefaultValue * @return outerEnumDefaultValue **/ - @JsonProperty("outerEnumDefaultValue") + @JsonProperty(value = "outerEnumDefaultValue") @ApiModelProperty(value = "") @Valid public OuterEnumDefaultValue getOuterEnumDefaultValue() { @@ -351,7 +351,7 @@ public EnumTest outerEnumIntegerDefaultValue(OuterEnumIntegerDefaultValue outerE * Get outerEnumIntegerDefaultValue * @return outerEnumIntegerDefaultValue **/ - @JsonProperty("outerEnumIntegerDefaultValue") + @JsonProperty(value = "outerEnumIntegerDefaultValue") @ApiModelProperty(value = "") @Valid public OuterEnumIntegerDefaultValue getOuterEnumIntegerDefaultValue() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 4be816893906..fb40a511e446 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -50,7 +50,7 @@ public FileSchemaTestClass file(java.io.File file) { * Get file * @return file **/ - @JsonProperty("file") + @JsonProperty(value = "file") @ApiModelProperty(value = "") @Valid public java.io.File getFile() { @@ -78,7 +78,7 @@ public FileSchemaTestClass addFilesItem(java.io.File filesItem) { * Get files * @return files **/ - @JsonProperty("files") + @JsonProperty(value = "files") @ApiModelProperty(value = "") @Valid public List getFiles() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Foo.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Foo.java index db05a7ee0996..eafca9cc314c 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Foo.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Foo.java @@ -43,7 +43,7 @@ public Foo bar(String bar) { * Get bar * @return bar **/ - @JsonProperty("bar") + @JsonProperty(value = "bar") @ApiModelProperty(value = "") public String getBar() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FormatTest.java index 614b54e17a7f..1459aa93dd2f 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FormatTest.java @@ -124,7 +124,7 @@ public FormatTest integer(Integer integer) { * maximum: 100 * @return integer **/ - @JsonProperty("integer") + @JsonProperty(value = "integer") @ApiModelProperty(value = "") @Min(10) @Max(100) public Integer getInteger() { @@ -146,7 +146,7 @@ public FormatTest int32(Integer int32) { * maximum: 200 * @return int32 **/ - @JsonProperty("int32") + @JsonProperty(value = "int32") @ApiModelProperty(value = "") @Min(20) @Max(200) public Integer getInt32() { @@ -166,7 +166,7 @@ public FormatTest int64(Long int64) { * Get int64 * @return int64 **/ - @JsonProperty("int64") + @JsonProperty(value = "int64") @ApiModelProperty(value = "") public Long getInt64() { @@ -188,7 +188,7 @@ public FormatTest number(BigDecimal number) { * maximum: 543.2 * @return number **/ - @JsonProperty("number") + @JsonProperty(value = "number") @ApiModelProperty(required = true, value = "") @NotNull @Valid @DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { @@ -210,7 +210,7 @@ public FormatTest _float(Float _float) { * maximum: 987.6 * @return _float **/ - @JsonProperty("float") + @JsonProperty(value = "float") @ApiModelProperty(value = "") @DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { @@ -232,7 +232,7 @@ public FormatTest _double(Double _double) { * maximum: 123.4 * @return _double **/ - @JsonProperty("double") + @JsonProperty(value = "double") @ApiModelProperty(value = "") @DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { @@ -252,7 +252,7 @@ public FormatTest decimal(BigDecimal decimal) { * Get decimal * @return decimal **/ - @JsonProperty("decimal") + @JsonProperty(value = "decimal") @ApiModelProperty(value = "") @Valid public BigDecimal getDecimal() { @@ -272,7 +272,7 @@ public FormatTest string(String string) { * Get string * @return string **/ - @JsonProperty("string") + @JsonProperty(value = "string") @ApiModelProperty(value = "") @Pattern(regexp="/[a-z]/i") public String getString() { @@ -292,7 +292,7 @@ public FormatTest _byte(byte[] _byte) { * Get _byte * @return _byte **/ - @JsonProperty("byte") + @JsonProperty(value = "byte") @ApiModelProperty(required = true, value = "") @NotNull public byte[] getByte() { @@ -312,7 +312,7 @@ public FormatTest binary(File binary) { * Get binary * @return binary **/ - @JsonProperty("binary") + @JsonProperty(value = "binary") @ApiModelProperty(value = "") public File getBinary() { @@ -332,7 +332,7 @@ public FormatTest date(Date date) { * Get date * @return date **/ - @JsonProperty("date") + @JsonProperty(value = "date") @ApiModelProperty(required = true, value = "") @NotNull public Date getDate() { @@ -352,7 +352,7 @@ public FormatTest dateTime(Date dateTime) { * Get dateTime * @return dateTime **/ - @JsonProperty("dateTime") + @JsonProperty(value = "dateTime") @ApiModelProperty(value = "") public Date getDateTime() { @@ -372,7 +372,7 @@ public FormatTest uuid(UUID uuid) { * Get uuid * @return uuid **/ - @JsonProperty("uuid") + @JsonProperty(value = "uuid") @ApiModelProperty(example = "72f98069-206d-4f12-9f12-3d1e525a8e84", value = "") public UUID getUuid() { @@ -392,7 +392,7 @@ public FormatTest password(String password) { * Get password * @return password **/ - @JsonProperty("password") + @JsonProperty(value = "password") @ApiModelProperty(required = true, value = "") @NotNull @Size(min=10,max=64) public String getPassword() { @@ -412,7 +412,7 @@ public FormatTest patternWithDigits(String patternWithDigits) { * A string that is a 10 digit number. Can have leading zeros. * @return patternWithDigits **/ - @JsonProperty("pattern_with_digits") + @JsonProperty(value = "pattern_with_digits") @ApiModelProperty(value = "A string that is a 10 digit number. Can have leading zeros.") @Pattern(regexp="^\\d{10}$") public String getPatternWithDigits() { @@ -432,7 +432,7 @@ public FormatTest patternWithDigitsAndDelimiter(String patternWithDigitsAndDelim * A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. * @return patternWithDigitsAndDelimiter **/ - @JsonProperty("pattern_with_digits_and_delimiter") + @JsonProperty(value = "pattern_with_digits_and_delimiter") @ApiModelProperty(value = "A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01.") @Pattern(regexp="/^image_\\d{1,3}$/i") public String getPatternWithDigitsAndDelimiter() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index 4f72442fd947..1b5042f61f59 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -48,7 +48,7 @@ public HasOnlyReadOnly bar(String bar) { * Get bar * @return bar **/ - @JsonProperty("bar") + @JsonProperty(value = "bar", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getBar() { @@ -68,7 +68,7 @@ public HasOnlyReadOnly foo(String foo) { * Get foo * @return foo **/ - @JsonProperty("foo") + @JsonProperty(value = "foo", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getFoo() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/HealthCheckResult.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/HealthCheckResult.java index 0da152286843..9757ba544587 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/HealthCheckResult.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/HealthCheckResult.java @@ -44,7 +44,7 @@ public HealthCheckResult nullableMessage(String nullableMessage) { * Get nullableMessage * @return nullableMessage **/ - @JsonProperty("NullableMessage") + @JsonProperty(value = "NullableMessage") @ApiModelProperty(value = "") public String getNullableMessage() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/InlineResponseDefault.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/InlineResponseDefault.java index 8882497a0215..789a62c847af 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/InlineResponseDefault.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/InlineResponseDefault.java @@ -44,7 +44,7 @@ public InlineResponseDefault string(Foo string) { * Get string * @return string **/ - @JsonProperty("string") + @JsonProperty(value = "string") @ApiModelProperty(value = "") @Valid public Foo getString() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/MapTest.java index 4db676efea2d..12516e0afba2 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/MapTest.java @@ -101,7 +101,7 @@ public MapTest putMapMapOfStringItem(String key, Map mapMapOfStr * Get mapMapOfString * @return mapMapOfString **/ - @JsonProperty("map_map_of_string") + @JsonProperty(value = "map_map_of_string") @ApiModelProperty(value = "") @Valid public Map> getMapMapOfString() { @@ -129,7 +129,7 @@ public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) * Get mapOfEnumString * @return mapOfEnumString **/ - @JsonProperty("map_of_enum_string") + @JsonProperty(value = "map_of_enum_string") @ApiModelProperty(value = "") public Map getMapOfEnumString() { @@ -157,7 +157,7 @@ public MapTest putDirectMapItem(String key, Boolean directMapItem) { * Get directMap * @return directMap **/ - @JsonProperty("direct_map") + @JsonProperty(value = "direct_map") @ApiModelProperty(value = "") public Map getDirectMap() { @@ -185,7 +185,7 @@ public MapTest putIndirectMapItem(String key, Boolean indirectMapItem) { * Get indirectMap * @return indirectMap **/ - @JsonProperty("indirect_map") + @JsonProperty(value = "indirect_map") @ApiModelProperty(value = "") public Map getIndirectMap() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index 0ba358c6b5c2..eb4fcd577811 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -59,7 +59,7 @@ public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { * Get uuid * @return uuid **/ - @JsonProperty("uuid") + @JsonProperty(value = "uuid") @ApiModelProperty(value = "") public UUID getUuid() { @@ -79,7 +79,7 @@ public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { * Get dateTime * @return dateTime **/ - @JsonProperty("dateTime") + @JsonProperty(value = "dateTime") @ApiModelProperty(value = "") public Date getDateTime() { @@ -107,7 +107,7 @@ public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal * Get map * @return map **/ - @JsonProperty("map") + @JsonProperty(value = "map") @ApiModelProperty(value = "") @Valid public Map getMap() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Model200Response.java index 2df0caa9725d..1a3e698983e5 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Model200Response.java @@ -49,7 +49,7 @@ public Model200Response name(Integer name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public Integer getName() { @@ -69,7 +69,7 @@ public Model200Response propertyClass(String propertyClass) { * Get propertyClass * @return propertyClass **/ - @JsonProperty("class") + @JsonProperty(value = "class") @ApiModelProperty(value = "") public String getPropertyClass() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelApiResponse.java index b0d01665ef6a..1552245d1dc8 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -53,7 +53,7 @@ public ModelApiResponse code(Integer code) { * Get code * @return code **/ - @JsonProperty("code") + @JsonProperty(value = "code") @ApiModelProperty(value = "") public Integer getCode() { @@ -73,7 +73,7 @@ public ModelApiResponse type(String type) { * Get type * @return type **/ - @JsonProperty("type") + @JsonProperty(value = "type") @ApiModelProperty(value = "") public String getType() { @@ -93,7 +93,7 @@ public ModelApiResponse message(String message) { * Get message * @return message **/ - @JsonProperty("message") + @JsonProperty(value = "message") @ApiModelProperty(value = "") public String getMessage() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelReturn.java index 41a1c059f7ef..c9f4504d3f0e 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelReturn.java @@ -44,7 +44,7 @@ public ModelReturn _return(Integer _return) { * Get _return * @return _return **/ - @JsonProperty("return") + @JsonProperty(value = "return") @ApiModelProperty(value = "") public Integer getReturn() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Name.java index a7a189571897..cdcef856cd21 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Name.java @@ -59,7 +59,7 @@ public Name name(Integer name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(required = true, value = "") @NotNull public Integer getName() { @@ -79,7 +79,7 @@ public Name snakeCase(Integer snakeCase) { * Get snakeCase * @return snakeCase **/ - @JsonProperty("snake_case") + @JsonProperty(value = "snake_case", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public Integer getSnakeCase() { @@ -99,7 +99,7 @@ public Name property(String property) { * Get property * @return property **/ - @JsonProperty("property") + @JsonProperty(value = "property") @ApiModelProperty(value = "") public String getProperty() { @@ -119,7 +119,7 @@ public Name _123number(Integer _123number) { * Get _123number * @return _123number **/ - @JsonProperty("123Number") + @JsonProperty(value = "123Number", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public Integer get123number() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/NullableClass.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/NullableClass.java index 090f6948d300..f1f9e12b46ea 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/NullableClass.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/NullableClass.java @@ -104,7 +104,7 @@ public NullableClass integerProp(Integer integerProp) { * Get integerProp * @return integerProp **/ - @JsonProperty("integer_prop") + @JsonProperty(value = "integer_prop") @ApiModelProperty(value = "") public Integer getIntegerProp() { @@ -124,7 +124,7 @@ public NullableClass numberProp(BigDecimal numberProp) { * Get numberProp * @return numberProp **/ - @JsonProperty("number_prop") + @JsonProperty(value = "number_prop") @ApiModelProperty(value = "") @Valid public BigDecimal getNumberProp() { @@ -144,7 +144,7 @@ public NullableClass booleanProp(Boolean booleanProp) { * Get booleanProp * @return booleanProp **/ - @JsonProperty("boolean_prop") + @JsonProperty(value = "boolean_prop") @ApiModelProperty(value = "") public Boolean getBooleanProp() { @@ -164,7 +164,7 @@ public NullableClass stringProp(String stringProp) { * Get stringProp * @return stringProp **/ - @JsonProperty("string_prop") + @JsonProperty(value = "string_prop") @ApiModelProperty(value = "") public String getStringProp() { @@ -184,7 +184,7 @@ public NullableClass dateProp(Date dateProp) { * Get dateProp * @return dateProp **/ - @JsonProperty("date_prop") + @JsonProperty(value = "date_prop") @ApiModelProperty(value = "") public Date getDateProp() { @@ -204,7 +204,7 @@ public NullableClass datetimeProp(Date datetimeProp) { * Get datetimeProp * @return datetimeProp **/ - @JsonProperty("datetime_prop") + @JsonProperty(value = "datetime_prop") @ApiModelProperty(value = "") public Date getDatetimeProp() { @@ -232,7 +232,7 @@ public NullableClass addArrayNullablePropItem(Object arrayNullablePropItem) { * Get arrayNullableProp * @return arrayNullableProp **/ - @JsonProperty("array_nullable_prop") + @JsonProperty(value = "array_nullable_prop") @ApiModelProperty(value = "") public List getArrayNullableProp() { @@ -260,7 +260,7 @@ public NullableClass addArrayAndItemsNullablePropItem(Object arrayAndItemsNullab * Get arrayAndItemsNullableProp * @return arrayAndItemsNullableProp **/ - @JsonProperty("array_and_items_nullable_prop") + @JsonProperty(value = "array_and_items_nullable_prop") @ApiModelProperty(value = "") public List getArrayAndItemsNullableProp() { @@ -288,7 +288,7 @@ public NullableClass addArrayItemsNullableItem(Object arrayItemsNullableItem) { * Get arrayItemsNullable * @return arrayItemsNullable **/ - @JsonProperty("array_items_nullable") + @JsonProperty(value = "array_items_nullable") @ApiModelProperty(value = "") public List getArrayItemsNullable() { @@ -316,7 +316,7 @@ public NullableClass putObjectNullablePropItem(String key, Object objectNullable * Get objectNullableProp * @return objectNullableProp **/ - @JsonProperty("object_nullable_prop") + @JsonProperty(value = "object_nullable_prop") @ApiModelProperty(value = "") public Map getObjectNullableProp() { @@ -344,7 +344,7 @@ public NullableClass putObjectAndItemsNullablePropItem(String key, Object object * Get objectAndItemsNullableProp * @return objectAndItemsNullableProp **/ - @JsonProperty("object_and_items_nullable_prop") + @JsonProperty(value = "object_and_items_nullable_prop") @ApiModelProperty(value = "") public Map getObjectAndItemsNullableProp() { @@ -372,7 +372,7 @@ public NullableClass putObjectItemsNullableItem(String key, Object objectItemsNu * Get objectItemsNullable * @return objectItemsNullable **/ - @JsonProperty("object_items_nullable") + @JsonProperty(value = "object_items_nullable") @ApiModelProperty(value = "") public Map getObjectItemsNullable() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/NumberOnly.java index 188899dc4460..3ec25c75ae59 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/NumberOnly.java @@ -44,7 +44,7 @@ public NumberOnly justNumber(BigDecimal justNumber) { * Get justNumber * @return justNumber **/ - @JsonProperty("JustNumber") + @JsonProperty(value = "JustNumber") @ApiModelProperty(value = "") @Valid public BigDecimal getJustNumber() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Order.java index 7ce0000199f9..b97b051ebc80 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Order.java @@ -103,7 +103,7 @@ public Order id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -123,7 +123,7 @@ public Order petId(Long petId) { * Get petId * @return petId **/ - @JsonProperty("petId") + @JsonProperty(value = "petId") @ApiModelProperty(value = "") public Long getPetId() { @@ -143,7 +143,7 @@ public Order quantity(Integer quantity) { * Get quantity * @return quantity **/ - @JsonProperty("quantity") + @JsonProperty(value = "quantity") @ApiModelProperty(value = "") public Integer getQuantity() { @@ -163,7 +163,7 @@ public Order shipDate(Date shipDate) { * Get shipDate * @return shipDate **/ - @JsonProperty("shipDate") + @JsonProperty(value = "shipDate") @ApiModelProperty(value = "") public Date getShipDate() { @@ -183,7 +183,7 @@ public Order status(StatusEnum status) { * Order Status * @return status **/ - @JsonProperty("status") + @JsonProperty(value = "status") @ApiModelProperty(value = "Order Status") public StatusEnum getStatus() { @@ -203,7 +203,7 @@ public Order complete(Boolean complete) { * Get complete * @return complete **/ - @JsonProperty("complete") + @JsonProperty(value = "complete") @ApiModelProperty(value = "") public Boolean getComplete() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/OuterComposite.java index 43b69002d036..577504e1bef2 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/OuterComposite.java @@ -54,7 +54,7 @@ public OuterComposite myNumber(BigDecimal myNumber) { * Get myNumber * @return myNumber **/ - @JsonProperty("my_number") + @JsonProperty(value = "my_number") @ApiModelProperty(value = "") @Valid public BigDecimal getMyNumber() { @@ -74,7 +74,7 @@ public OuterComposite myString(String myString) { * Get myString * @return myString **/ - @JsonProperty("my_string") + @JsonProperty(value = "my_string") @ApiModelProperty(value = "") public String getMyString() { @@ -94,7 +94,7 @@ public OuterComposite myBoolean(Boolean myBoolean) { * Get myBoolean * @return myBoolean **/ - @JsonProperty("my_boolean") + @JsonProperty(value = "my_boolean") @ApiModelProperty(value = "") public Boolean getMyBoolean() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/OuterObjectWithEnumProperty.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/OuterObjectWithEnumProperty.java index 55890a0c6ee1..2f7242fa36d1 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/OuterObjectWithEnumProperty.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/OuterObjectWithEnumProperty.java @@ -44,7 +44,7 @@ public OuterObjectWithEnumProperty value(OuterEnumInteger value) { * Get value * @return value **/ - @JsonProperty("value") + @JsonProperty(value = "value") @ApiModelProperty(required = true, value = "") @NotNull @Valid public OuterEnumInteger getValue() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Pet.java index adcdbf24a57d..4ed108d787e9 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Pet.java @@ -108,7 +108,7 @@ public Pet id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -128,7 +128,7 @@ public Pet category(Category category) { * Get category * @return category **/ - @JsonProperty("category") + @JsonProperty(value = "category") @ApiModelProperty(value = "") @Valid public Category getCategory() { @@ -148,7 +148,7 @@ public Pet name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(example = "doggie", required = true, value = "") @NotNull public String getName() { @@ -173,7 +173,7 @@ public Pet addPhotoUrlsItem(String photoUrlsItem) { * Get photoUrls * @return photoUrls **/ - @JsonProperty("photoUrls") + @JsonProperty(value = "photoUrls") @ApiModelProperty(required = true, value = "") @NotNull public Set getPhotoUrls() { @@ -201,7 +201,7 @@ public Pet addTagsItem(Tag tagsItem) { * Get tags * @return tags **/ - @JsonProperty("tags") + @JsonProperty(value = "tags") @ApiModelProperty(value = "") @Valid public List getTags() { @@ -221,7 +221,7 @@ public Pet status(StatusEnum status) { * pet status in the store * @return status **/ - @JsonProperty("status") + @JsonProperty(value = "status") @ApiModelProperty(value = "pet status in the store") public StatusEnum getStatus() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index e2e5ea910e68..05c01064ff67 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -48,7 +48,7 @@ public ReadOnlyFirst bar(String bar) { * Get bar * @return bar **/ - @JsonProperty("bar") + @JsonProperty(value = "bar", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getBar() { @@ -68,7 +68,7 @@ public ReadOnlyFirst baz(String baz) { * Get baz * @return baz **/ - @JsonProperty("baz") + @JsonProperty(value = "baz") @ApiModelProperty(value = "") public String getBaz() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/SpecialModelName.java index d5a487ed873d..912dd213133f 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -43,7 +43,7 @@ public class SpecialModelName { * Get $specialPropertyName * @return $specialPropertyName **/ - @JsonProperty("$special[property.name]") + @JsonProperty(value = "$special[property.name]") @ApiModelProperty(value = "") public Long get$SpecialPropertyName() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Tag.java index 80d098d57c16..5ac82ca92382 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Tag.java @@ -48,7 +48,7 @@ public Tag id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -68,7 +68,7 @@ public Tag name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/User.java index 1e702dd070d5..37ab5453c3d2 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/User.java @@ -78,7 +78,7 @@ public User id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -98,7 +98,7 @@ public User username(String username) { * Get username * @return username **/ - @JsonProperty("username") + @JsonProperty(value = "username") @ApiModelProperty(value = "") public String getUsername() { @@ -118,7 +118,7 @@ public User firstName(String firstName) { * Get firstName * @return firstName **/ - @JsonProperty("firstName") + @JsonProperty(value = "firstName") @ApiModelProperty(value = "") public String getFirstName() { @@ -138,7 +138,7 @@ public User lastName(String lastName) { * Get lastName * @return lastName **/ - @JsonProperty("lastName") + @JsonProperty(value = "lastName") @ApiModelProperty(value = "") public String getLastName() { @@ -158,7 +158,7 @@ public User email(String email) { * Get email * @return email **/ - @JsonProperty("email") + @JsonProperty(value = "email") @ApiModelProperty(value = "") public String getEmail() { @@ -178,7 +178,7 @@ public User password(String password) { * Get password * @return password **/ - @JsonProperty("password") + @JsonProperty(value = "password") @ApiModelProperty(value = "") public String getPassword() { @@ -198,7 +198,7 @@ public User phone(String phone) { * Get phone * @return phone **/ - @JsonProperty("phone") + @JsonProperty(value = "phone") @ApiModelProperty(value = "") public String getPhone() { @@ -218,7 +218,7 @@ public User userStatus(Integer userStatus) { * User Status * @return userStatus **/ - @JsonProperty("userStatus") + @JsonProperty(value = "userStatus") @ApiModelProperty(value = "User Status") public Integer getUserStatus() { diff --git a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java index 10c9235fe628..b9b569853635 100644 --- a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java @@ -64,6 +64,11 @@ public Response fakePropertyEnumIntegerSerialize(OuterObjectWithEnumProperty out return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override + public Response testBodyWithBinary(File body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override public Response testBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/samples/server/petstore/jaxrs-resteasy/default-value/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-resteasy/default-value/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs-resteasy/default-value/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-resteasy/default-value/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-resteasy/default/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-resteasy/default/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-resteasy/default/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-resteasy/eap-java8/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-resteasy/eap-java8/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-java8/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-resteasy/eap-java8/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-resteasy/eap-joda/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-resteasy/eap-joda/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-joda/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-resteasy/eap-joda/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-resteasy/eap/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-resteasy/eap/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-resteasy/eap/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-resteasy/joda/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-resteasy/joda/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-resteasy/joda/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-spec-interface/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-spec-interface/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs-spec-interface/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-spec-interface/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-spec/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-spec/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs-spec/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-spec/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/.openapi-generator/VERSION b/samples/server/petstore/jaxrs/jersey1-useTags/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs/jersey1-useTags/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java index 94ab4ee99b59..b69405239b38 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java @@ -45,7 +45,7 @@ public AdditionalPropertiesAnyType name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java index 8a7cbbfa5e79..f90d93c37aec 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java @@ -46,7 +46,7 @@ public AdditionalPropertiesArray name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java index 8e5e3a7ec7cc..473358d6cda0 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java @@ -45,7 +45,7 @@ public AdditionalPropertiesBoolean name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index df959efecfe6..bf846cfb6bf7 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -105,7 +105,7 @@ public AdditionalPropertiesClass putMapStringItem(String key, String mapStringIt * Get mapString * @return mapString **/ - @JsonProperty("map_string") + @JsonProperty(value = "map_string") @ApiModelProperty(value = "") public Map getMapString() { @@ -133,7 +133,7 @@ public AdditionalPropertiesClass putMapNumberItem(String key, BigDecimal mapNumb * Get mapNumber * @return mapNumber **/ - @JsonProperty("map_number") + @JsonProperty(value = "map_number") @ApiModelProperty(value = "") @Valid public Map getMapNumber() { @@ -161,7 +161,7 @@ public AdditionalPropertiesClass putMapIntegerItem(String key, Integer mapIntege * Get mapInteger * @return mapInteger **/ - @JsonProperty("map_integer") + @JsonProperty(value = "map_integer") @ApiModelProperty(value = "") public Map getMapInteger() { @@ -189,7 +189,7 @@ public AdditionalPropertiesClass putMapBooleanItem(String key, Boolean mapBoolea * Get mapBoolean * @return mapBoolean **/ - @JsonProperty("map_boolean") + @JsonProperty(value = "map_boolean") @ApiModelProperty(value = "") public Map getMapBoolean() { @@ -217,7 +217,7 @@ public AdditionalPropertiesClass putMapArrayIntegerItem(String key, List> getMapArrayInteger() { @@ -245,7 +245,7 @@ public AdditionalPropertiesClass putMapArrayAnytypeItem(String key, List * Get mapArrayAnytype * @return mapArrayAnytype **/ - @JsonProperty("map_array_anytype") + @JsonProperty(value = "map_array_anytype") @ApiModelProperty(value = "") @Valid public Map> getMapArrayAnytype() { @@ -273,7 +273,7 @@ public AdditionalPropertiesClass putMapMapStringItem(String key, Map> getMapMapString() { @@ -301,7 +301,7 @@ public AdditionalPropertiesClass putMapMapAnytypeItem(String key, Map> getMapMapAnytype() { @@ -321,7 +321,7 @@ public AdditionalPropertiesClass anytype1(Object anytype1) { * Get anytype1 * @return anytype1 **/ - @JsonProperty("anytype_1") + @JsonProperty(value = "anytype_1") @ApiModelProperty(value = "") public Object getAnytype1() { @@ -341,7 +341,7 @@ public AdditionalPropertiesClass anytype2(Object anytype2) { * Get anytype2 * @return anytype2 **/ - @JsonProperty("anytype_2") + @JsonProperty(value = "anytype_2") @ApiModelProperty(value = "") public Object getAnytype2() { @@ -361,7 +361,7 @@ public AdditionalPropertiesClass anytype3(Object anytype3) { * Get anytype3 * @return anytype3 **/ - @JsonProperty("anytype_3") + @JsonProperty(value = "anytype_3") @ApiModelProperty(value = "") public Object getAnytype3() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java index ac5f7501b3a8..29bd12be784b 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java @@ -45,7 +45,7 @@ public AdditionalPropertiesInteger name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java index d3072f447dca..f05484cd7cc7 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java @@ -46,7 +46,7 @@ public AdditionalPropertiesNumber name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java index 8f8b575df2a2..fb246cac6598 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java @@ -45,7 +45,7 @@ public AdditionalPropertiesObject name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java index c5d4ac7f7c1b..b7018e370e50 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java @@ -45,7 +45,7 @@ public AdditionalPropertiesString name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Animal.java index db142b932d90..97cdd70ab0a1 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Animal.java @@ -56,7 +56,7 @@ public Animal className(String className) { * Get className * @return className **/ - @JsonProperty("className") + @JsonProperty(value = "className") @ApiModelProperty(required = true, value = "") @NotNull public String getClassName() { @@ -76,7 +76,7 @@ public Animal color(String color) { * Get color * @return color **/ - @JsonProperty("color") + @JsonProperty(value = "color") @ApiModelProperty(value = "") public String getColor() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index cd6a16edb265..d277c77993f3 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -54,7 +54,7 @@ public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayAr * Get arrayArrayNumber * @return arrayArrayNumber **/ - @JsonProperty("ArrayArrayNumber") + @JsonProperty(value = "ArrayArrayNumber") @ApiModelProperty(value = "") @Valid public List> getArrayArrayNumber() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index 71d88cd5d890..f8b08e16723e 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -54,7 +54,7 @@ public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { * Get arrayNumber * @return arrayNumber **/ - @JsonProperty("ArrayNumber") + @JsonProperty(value = "ArrayNumber") @ApiModelProperty(value = "") @Valid public List getArrayNumber() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ArrayTest.java index 738fa858e7e7..dfeb88958dca 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ArrayTest.java @@ -64,7 +64,7 @@ public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { * Get arrayOfString * @return arrayOfString **/ - @JsonProperty("array_of_string") + @JsonProperty(value = "array_of_string") @ApiModelProperty(value = "") public List getArrayOfString() { @@ -92,7 +92,7 @@ public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) * Get arrayArrayOfInteger * @return arrayArrayOfInteger **/ - @JsonProperty("array_array_of_integer") + @JsonProperty(value = "array_array_of_integer") @ApiModelProperty(value = "") @Valid public List> getArrayArrayOfInteger() { @@ -120,7 +120,7 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI * Get arrayArrayOfModel * @return arrayArrayOfModel **/ - @JsonProperty("array_array_of_model") + @JsonProperty(value = "array_array_of_model") @ApiModelProperty(value = "") @Valid public List> getArrayArrayOfModel() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/BigCat.java index 0af195ad0a72..867f51230021 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/BigCat.java @@ -81,7 +81,7 @@ public BigCat kind(KindEnum kind) { * Get kind * @return kind **/ - @JsonProperty("kind") + @JsonProperty(value = "kind") @ApiModelProperty(value = "") public KindEnum getKind() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/BigCatAllOf.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/BigCatAllOf.java index eaf4e4f49f5e..ae1220fcefd1 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/BigCatAllOf.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/BigCatAllOf.java @@ -79,7 +79,7 @@ public BigCatAllOf kind(KindEnum kind) { * Get kind * @return kind **/ - @JsonProperty("kind") + @JsonProperty(value = "kind") @ApiModelProperty(value = "") public KindEnum getKind() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Capitalization.java index 9b99fe2b58b3..650d2c7b790b 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Capitalization.java @@ -68,7 +68,7 @@ public Capitalization smallCamel(String smallCamel) { * Get smallCamel * @return smallCamel **/ - @JsonProperty("smallCamel") + @JsonProperty(value = "smallCamel") @ApiModelProperty(value = "") public String getSmallCamel() { @@ -88,7 +88,7 @@ public Capitalization capitalCamel(String capitalCamel) { * Get capitalCamel * @return capitalCamel **/ - @JsonProperty("CapitalCamel") + @JsonProperty(value = "CapitalCamel") @ApiModelProperty(value = "") public String getCapitalCamel() { @@ -108,7 +108,7 @@ public Capitalization smallSnake(String smallSnake) { * Get smallSnake * @return smallSnake **/ - @JsonProperty("small_Snake") + @JsonProperty(value = "small_Snake") @ApiModelProperty(value = "") public String getSmallSnake() { @@ -128,7 +128,7 @@ public Capitalization capitalSnake(String capitalSnake) { * Get capitalSnake * @return capitalSnake **/ - @JsonProperty("Capital_Snake") + @JsonProperty(value = "Capital_Snake") @ApiModelProperty(value = "") public String getCapitalSnake() { @@ -148,7 +148,7 @@ public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { * Get scAETHFlowPoints * @return scAETHFlowPoints **/ - @JsonProperty("SCA_ETH_Flow_Points") + @JsonProperty(value = "SCA_ETH_Flow_Points") @ApiModelProperty(value = "") public String getScAETHFlowPoints() { @@ -168,7 +168,7 @@ public Capitalization ATT_NAME(String ATT_NAME) { * Name of the pet * @return ATT_NAME **/ - @JsonProperty("ATT_NAME") + @JsonProperty(value = "ATT_NAME") @ApiModelProperty(value = "Name of the pet ") public String getATTNAME() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Cat.java index a393506d3aa5..ef4f615bfe76 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Cat.java @@ -45,7 +45,7 @@ public Cat declawed(Boolean declawed) { * Get declawed * @return declawed **/ - @JsonProperty("declawed") + @JsonProperty(value = "declawed") @ApiModelProperty(value = "") public Boolean getDeclawed() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/CatAllOf.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/CatAllOf.java index 7e2a72595950..83503a712d2b 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/CatAllOf.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/CatAllOf.java @@ -43,7 +43,7 @@ public CatAllOf declawed(Boolean declawed) { * Get declawed * @return declawed **/ - @JsonProperty("declawed") + @JsonProperty(value = "declawed") @ApiModelProperty(value = "") public Boolean getDeclawed() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Category.java index d7a5c2b2fafa..af6055dba4ea 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Category.java @@ -48,7 +48,7 @@ public Category id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -68,7 +68,7 @@ public Category name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(required = true, value = "") @NotNull public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ClassModel.java index 00352ed5bce9..ccfe8e27684e 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ClassModel.java @@ -44,7 +44,7 @@ public ClassModel propertyClass(String propertyClass) { * Get propertyClass * @return propertyClass **/ - @JsonProperty("_class") + @JsonProperty(value = "_class") @ApiModelProperty(value = "") public String getPropertyClass() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Client.java index 04b28287ed41..0c87d7030a57 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Client.java @@ -43,7 +43,7 @@ public Client client(String client) { * Get client * @return client **/ - @JsonProperty("client") + @JsonProperty(value = "client") @ApiModelProperty(value = "") public String getClient() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Dog.java index 7d6059b2fc1f..e126444fd61e 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Dog.java @@ -45,7 +45,7 @@ public Dog breed(String breed) { * Get breed * @return breed **/ - @JsonProperty("breed") + @JsonProperty(value = "breed") @ApiModelProperty(value = "") public String getBreed() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/DogAllOf.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/DogAllOf.java index 9fcfbfb92cfc..6902a980c243 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/DogAllOf.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/DogAllOf.java @@ -43,7 +43,7 @@ public DogAllOf breed(String breed) { * Get breed * @return breed **/ - @JsonProperty("breed") + @JsonProperty(value = "breed") @ApiModelProperty(value = "") public String getBreed() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/EnumArrays.java index 526f387372ca..08e6db1ffc92 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/EnumArrays.java @@ -113,7 +113,7 @@ public EnumArrays justSymbol(JustSymbolEnum justSymbol) { * Get justSymbol * @return justSymbol **/ - @JsonProperty("just_symbol") + @JsonProperty(value = "just_symbol") @ApiModelProperty(value = "") public JustSymbolEnum getJustSymbol() { @@ -141,7 +141,7 @@ public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { * Get arrayEnum * @return arrayEnum **/ - @JsonProperty("array_enum") + @JsonProperty(value = "array_enum") @ApiModelProperty(value = "") public List getArrayEnum() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/EnumTest.java index ee08eadfa8d7..937a9f7f6aeb 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/EnumTest.java @@ -193,7 +193,7 @@ public EnumTest enumString(EnumStringEnum enumString) { * Get enumString * @return enumString **/ - @JsonProperty("enum_string") + @JsonProperty(value = "enum_string") @ApiModelProperty(value = "") public EnumStringEnum getEnumString() { @@ -213,7 +213,7 @@ public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { * Get enumStringRequired * @return enumStringRequired **/ - @JsonProperty("enum_string_required") + @JsonProperty(value = "enum_string_required") @ApiModelProperty(required = true, value = "") @NotNull public EnumStringRequiredEnum getEnumStringRequired() { @@ -233,7 +233,7 @@ public EnumTest enumInteger(EnumIntegerEnum enumInteger) { * Get enumInteger * @return enumInteger **/ - @JsonProperty("enum_integer") + @JsonProperty(value = "enum_integer") @ApiModelProperty(value = "") public EnumIntegerEnum getEnumInteger() { @@ -253,7 +253,7 @@ public EnumTest enumNumber(EnumNumberEnum enumNumber) { * Get enumNumber * @return enumNumber **/ - @JsonProperty("enum_number") + @JsonProperty(value = "enum_number") @ApiModelProperty(value = "") public EnumNumberEnum getEnumNumber() { @@ -273,7 +273,7 @@ public EnumTest outerEnum(OuterEnum outerEnum) { * Get outerEnum * @return outerEnum **/ - @JsonProperty("outerEnum") + @JsonProperty(value = "outerEnum") @ApiModelProperty(value = "") @Valid public OuterEnum getOuterEnum() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 4be816893906..fb40a511e446 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -50,7 +50,7 @@ public FileSchemaTestClass file(java.io.File file) { * Get file * @return file **/ - @JsonProperty("file") + @JsonProperty(value = "file") @ApiModelProperty(value = "") @Valid public java.io.File getFile() { @@ -78,7 +78,7 @@ public FileSchemaTestClass addFilesItem(java.io.File filesItem) { * Get files * @return files **/ - @JsonProperty("files") + @JsonProperty(value = "files") @ApiModelProperty(value = "") @Valid public List getFiles() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/FormatTest.java index 9817e78712a7..d640a11342c7 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/FormatTest.java @@ -114,7 +114,7 @@ public FormatTest integer(Integer integer) { * maximum: 100 * @return integer **/ - @JsonProperty("integer") + @JsonProperty(value = "integer") @ApiModelProperty(value = "") @Min(10) @Max(100) public Integer getInteger() { @@ -136,7 +136,7 @@ public FormatTest int32(Integer int32) { * maximum: 200 * @return int32 **/ - @JsonProperty("int32") + @JsonProperty(value = "int32") @ApiModelProperty(value = "") @Min(20) @Max(200) public Integer getInt32() { @@ -156,7 +156,7 @@ public FormatTest int64(Long int64) { * Get int64 * @return int64 **/ - @JsonProperty("int64") + @JsonProperty(value = "int64") @ApiModelProperty(value = "") public Long getInt64() { @@ -178,7 +178,7 @@ public FormatTest number(BigDecimal number) { * maximum: 543.2 * @return number **/ - @JsonProperty("number") + @JsonProperty(value = "number") @ApiModelProperty(required = true, value = "") @NotNull @Valid @DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { @@ -200,7 +200,7 @@ public FormatTest _float(Float _float) { * maximum: 987.6 * @return _float **/ - @JsonProperty("float") + @JsonProperty(value = "float") @ApiModelProperty(value = "") @DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { @@ -222,7 +222,7 @@ public FormatTest _double(Double _double) { * maximum: 123.4 * @return _double **/ - @JsonProperty("double") + @JsonProperty(value = "double") @ApiModelProperty(value = "") @DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { @@ -242,7 +242,7 @@ public FormatTest string(String string) { * Get string * @return string **/ - @JsonProperty("string") + @JsonProperty(value = "string") @ApiModelProperty(value = "") @Pattern(regexp="/[a-z]/i") public String getString() { @@ -262,7 +262,7 @@ public FormatTest _byte(byte[] _byte) { * Get _byte * @return _byte **/ - @JsonProperty("byte") + @JsonProperty(value = "byte") @ApiModelProperty(required = true, value = "") @NotNull public byte[] getByte() { @@ -282,7 +282,7 @@ public FormatTest binary(File binary) { * Get binary * @return binary **/ - @JsonProperty("binary") + @JsonProperty(value = "binary") @ApiModelProperty(value = "") public File getBinary() { @@ -302,7 +302,7 @@ public FormatTest date(Date date) { * Get date * @return date **/ - @JsonProperty("date") + @JsonProperty(value = "date") @ApiModelProperty(required = true, value = "") @NotNull public Date getDate() { @@ -322,7 +322,7 @@ public FormatTest dateTime(Date dateTime) { * Get dateTime * @return dateTime **/ - @JsonProperty("dateTime") + @JsonProperty(value = "dateTime") @ApiModelProperty(value = "") public Date getDateTime() { @@ -342,7 +342,7 @@ public FormatTest uuid(UUID uuid) { * Get uuid * @return uuid **/ - @JsonProperty("uuid") + @JsonProperty(value = "uuid") @ApiModelProperty(example = "72f98069-206d-4f12-9f12-3d1e525a8e84", value = "") public UUID getUuid() { @@ -362,7 +362,7 @@ public FormatTest password(String password) { * Get password * @return password **/ - @JsonProperty("password") + @JsonProperty(value = "password") @ApiModelProperty(required = true, value = "") @NotNull @Size(min=10,max=64) public String getPassword() { @@ -382,7 +382,7 @@ public FormatTest bigDecimal(BigDecimal bigDecimal) { * Get bigDecimal * @return bigDecimal **/ - @JsonProperty("BigDecimal") + @JsonProperty(value = "BigDecimal") @ApiModelProperty(value = "") @Valid public BigDecimal getBigDecimal() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index 4f72442fd947..1b5042f61f59 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -48,7 +48,7 @@ public HasOnlyReadOnly bar(String bar) { * Get bar * @return bar **/ - @JsonProperty("bar") + @JsonProperty(value = "bar", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getBar() { @@ -68,7 +68,7 @@ public HasOnlyReadOnly foo(String foo) { * Get foo * @return foo **/ - @JsonProperty("foo") + @JsonProperty(value = "foo", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getFoo() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/MapTest.java index 4db676efea2d..12516e0afba2 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/MapTest.java @@ -101,7 +101,7 @@ public MapTest putMapMapOfStringItem(String key, Map mapMapOfStr * Get mapMapOfString * @return mapMapOfString **/ - @JsonProperty("map_map_of_string") + @JsonProperty(value = "map_map_of_string") @ApiModelProperty(value = "") @Valid public Map> getMapMapOfString() { @@ -129,7 +129,7 @@ public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) * Get mapOfEnumString * @return mapOfEnumString **/ - @JsonProperty("map_of_enum_string") + @JsonProperty(value = "map_of_enum_string") @ApiModelProperty(value = "") public Map getMapOfEnumString() { @@ -157,7 +157,7 @@ public MapTest putDirectMapItem(String key, Boolean directMapItem) { * Get directMap * @return directMap **/ - @JsonProperty("direct_map") + @JsonProperty(value = "direct_map") @ApiModelProperty(value = "") public Map getDirectMap() { @@ -185,7 +185,7 @@ public MapTest putIndirectMapItem(String key, Boolean indirectMapItem) { * Get indirectMap * @return indirectMap **/ - @JsonProperty("indirect_map") + @JsonProperty(value = "indirect_map") @ApiModelProperty(value = "") public Map getIndirectMap() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index 0ba358c6b5c2..eb4fcd577811 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -59,7 +59,7 @@ public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { * Get uuid * @return uuid **/ - @JsonProperty("uuid") + @JsonProperty(value = "uuid") @ApiModelProperty(value = "") public UUID getUuid() { @@ -79,7 +79,7 @@ public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { * Get dateTime * @return dateTime **/ - @JsonProperty("dateTime") + @JsonProperty(value = "dateTime") @ApiModelProperty(value = "") public Date getDateTime() { @@ -107,7 +107,7 @@ public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal * Get map * @return map **/ - @JsonProperty("map") + @JsonProperty(value = "map") @ApiModelProperty(value = "") @Valid public Map getMap() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Model200Response.java index 2df0caa9725d..1a3e698983e5 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Model200Response.java @@ -49,7 +49,7 @@ public Model200Response name(Integer name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public Integer getName() { @@ -69,7 +69,7 @@ public Model200Response propertyClass(String propertyClass) { * Get propertyClass * @return propertyClass **/ - @JsonProperty("class") + @JsonProperty(value = "class") @ApiModelProperty(value = "") public String getPropertyClass() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ModelApiResponse.java index b0d01665ef6a..1552245d1dc8 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -53,7 +53,7 @@ public ModelApiResponse code(Integer code) { * Get code * @return code **/ - @JsonProperty("code") + @JsonProperty(value = "code") @ApiModelProperty(value = "") public Integer getCode() { @@ -73,7 +73,7 @@ public ModelApiResponse type(String type) { * Get type * @return type **/ - @JsonProperty("type") + @JsonProperty(value = "type") @ApiModelProperty(value = "") public String getType() { @@ -93,7 +93,7 @@ public ModelApiResponse message(String message) { * Get message * @return message **/ - @JsonProperty("message") + @JsonProperty(value = "message") @ApiModelProperty(value = "") public String getMessage() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ModelReturn.java index 41a1c059f7ef..c9f4504d3f0e 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ModelReturn.java @@ -44,7 +44,7 @@ public ModelReturn _return(Integer _return) { * Get _return * @return _return **/ - @JsonProperty("return") + @JsonProperty(value = "return") @ApiModelProperty(value = "") public Integer getReturn() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Name.java index a7a189571897..cdcef856cd21 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Name.java @@ -59,7 +59,7 @@ public Name name(Integer name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(required = true, value = "") @NotNull public Integer getName() { @@ -79,7 +79,7 @@ public Name snakeCase(Integer snakeCase) { * Get snakeCase * @return snakeCase **/ - @JsonProperty("snake_case") + @JsonProperty(value = "snake_case", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public Integer getSnakeCase() { @@ -99,7 +99,7 @@ public Name property(String property) { * Get property * @return property **/ - @JsonProperty("property") + @JsonProperty(value = "property") @ApiModelProperty(value = "") public String getProperty() { @@ -119,7 +119,7 @@ public Name _123number(Integer _123number) { * Get _123number * @return _123number **/ - @JsonProperty("123Number") + @JsonProperty(value = "123Number", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public Integer get123number() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/NumberOnly.java index 188899dc4460..3ec25c75ae59 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/NumberOnly.java @@ -44,7 +44,7 @@ public NumberOnly justNumber(BigDecimal justNumber) { * Get justNumber * @return justNumber **/ - @JsonProperty("JustNumber") + @JsonProperty(value = "JustNumber") @ApiModelProperty(value = "") @Valid public BigDecimal getJustNumber() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Order.java index 7ce0000199f9..b97b051ebc80 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Order.java @@ -103,7 +103,7 @@ public Order id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -123,7 +123,7 @@ public Order petId(Long petId) { * Get petId * @return petId **/ - @JsonProperty("petId") + @JsonProperty(value = "petId") @ApiModelProperty(value = "") public Long getPetId() { @@ -143,7 +143,7 @@ public Order quantity(Integer quantity) { * Get quantity * @return quantity **/ - @JsonProperty("quantity") + @JsonProperty(value = "quantity") @ApiModelProperty(value = "") public Integer getQuantity() { @@ -163,7 +163,7 @@ public Order shipDate(Date shipDate) { * Get shipDate * @return shipDate **/ - @JsonProperty("shipDate") + @JsonProperty(value = "shipDate") @ApiModelProperty(value = "") public Date getShipDate() { @@ -183,7 +183,7 @@ public Order status(StatusEnum status) { * Order Status * @return status **/ - @JsonProperty("status") + @JsonProperty(value = "status") @ApiModelProperty(value = "Order Status") public StatusEnum getStatus() { @@ -203,7 +203,7 @@ public Order complete(Boolean complete) { * Get complete * @return complete **/ - @JsonProperty("complete") + @JsonProperty(value = "complete") @ApiModelProperty(value = "") public Boolean getComplete() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/OuterComposite.java index 43b69002d036..577504e1bef2 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/OuterComposite.java @@ -54,7 +54,7 @@ public OuterComposite myNumber(BigDecimal myNumber) { * Get myNumber * @return myNumber **/ - @JsonProperty("my_number") + @JsonProperty(value = "my_number") @ApiModelProperty(value = "") @Valid public BigDecimal getMyNumber() { @@ -74,7 +74,7 @@ public OuterComposite myString(String myString) { * Get myString * @return myString **/ - @JsonProperty("my_string") + @JsonProperty(value = "my_string") @ApiModelProperty(value = "") public String getMyString() { @@ -94,7 +94,7 @@ public OuterComposite myBoolean(Boolean myBoolean) { * Get myBoolean * @return myBoolean **/ - @JsonProperty("my_boolean") + @JsonProperty(value = "my_boolean") @ApiModelProperty(value = "") public Boolean getMyBoolean() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Pet.java index adcdbf24a57d..4ed108d787e9 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Pet.java @@ -108,7 +108,7 @@ public Pet id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -128,7 +128,7 @@ public Pet category(Category category) { * Get category * @return category **/ - @JsonProperty("category") + @JsonProperty(value = "category") @ApiModelProperty(value = "") @Valid public Category getCategory() { @@ -148,7 +148,7 @@ public Pet name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(example = "doggie", required = true, value = "") @NotNull public String getName() { @@ -173,7 +173,7 @@ public Pet addPhotoUrlsItem(String photoUrlsItem) { * Get photoUrls * @return photoUrls **/ - @JsonProperty("photoUrls") + @JsonProperty(value = "photoUrls") @ApiModelProperty(required = true, value = "") @NotNull public Set getPhotoUrls() { @@ -201,7 +201,7 @@ public Pet addTagsItem(Tag tagsItem) { * Get tags * @return tags **/ - @JsonProperty("tags") + @JsonProperty(value = "tags") @ApiModelProperty(value = "") @Valid public List getTags() { @@ -221,7 +221,7 @@ public Pet status(StatusEnum status) { * pet status in the store * @return status **/ - @JsonProperty("status") + @JsonProperty(value = "status") @ApiModelProperty(value = "pet status in the store") public StatusEnum getStatus() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index e2e5ea910e68..05c01064ff67 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -48,7 +48,7 @@ public ReadOnlyFirst bar(String bar) { * Get bar * @return bar **/ - @JsonProperty("bar") + @JsonProperty(value = "bar", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getBar() { @@ -68,7 +68,7 @@ public ReadOnlyFirst baz(String baz) { * Get baz * @return baz **/ - @JsonProperty("baz") + @JsonProperty(value = "baz") @ApiModelProperty(value = "") public String getBaz() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/SpecialModelName.java index 48ed44ecf621..1fbc58e301e6 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -43,7 +43,7 @@ public class SpecialModelName { * Get $specialPropertyName * @return $specialPropertyName **/ - @JsonProperty("$special[property.name]") + @JsonProperty(value = "$special[property.name]") @ApiModelProperty(value = "") public Long get$SpecialPropertyName() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Tag.java index 80d098d57c16..5ac82ca92382 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/Tag.java @@ -48,7 +48,7 @@ public Tag id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -68,7 +68,7 @@ public Tag name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/TypeHolderDefault.java index 52830413a08c..a8450d0e61d5 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/TypeHolderDefault.java @@ -66,7 +66,7 @@ public TypeHolderDefault stringItem(String stringItem) { * Get stringItem * @return stringItem **/ - @JsonProperty("string_item") + @JsonProperty(value = "string_item") @ApiModelProperty(required = true, value = "") @NotNull public String getStringItem() { @@ -86,7 +86,7 @@ public TypeHolderDefault numberItem(BigDecimal numberItem) { * Get numberItem * @return numberItem **/ - @JsonProperty("number_item") + @JsonProperty(value = "number_item") @ApiModelProperty(required = true, value = "") @NotNull @Valid public BigDecimal getNumberItem() { @@ -106,7 +106,7 @@ public TypeHolderDefault integerItem(Integer integerItem) { * Get integerItem * @return integerItem **/ - @JsonProperty("integer_item") + @JsonProperty(value = "integer_item") @ApiModelProperty(required = true, value = "") @NotNull public Integer getIntegerItem() { @@ -126,7 +126,7 @@ public TypeHolderDefault boolItem(Boolean boolItem) { * Get boolItem * @return boolItem **/ - @JsonProperty("bool_item") + @JsonProperty(value = "bool_item") @ApiModelProperty(required = true, value = "") @NotNull public Boolean getBoolItem() { @@ -151,7 +151,7 @@ public TypeHolderDefault addArrayItemItem(Integer arrayItemItem) { * Get arrayItem * @return arrayItem **/ - @JsonProperty("array_item") + @JsonProperty(value = "array_item") @ApiModelProperty(required = true, value = "") @NotNull public List getArrayItem() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/TypeHolderExample.java index 8e57cc93cef4..026943cb64e3 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/TypeHolderExample.java @@ -71,7 +71,7 @@ public TypeHolderExample stringItem(String stringItem) { * Get stringItem * @return stringItem **/ - @JsonProperty("string_item") + @JsonProperty(value = "string_item") @ApiModelProperty(example = "what", required = true, value = "") @NotNull public String getStringItem() { @@ -91,7 +91,7 @@ public TypeHolderExample numberItem(BigDecimal numberItem) { * Get numberItem * @return numberItem **/ - @JsonProperty("number_item") + @JsonProperty(value = "number_item") @ApiModelProperty(example = "1.234", required = true, value = "") @NotNull @Valid public BigDecimal getNumberItem() { @@ -111,7 +111,7 @@ public TypeHolderExample floatItem(Float floatItem) { * Get floatItem * @return floatItem **/ - @JsonProperty("float_item") + @JsonProperty(value = "float_item") @ApiModelProperty(example = "1.234", required = true, value = "") @NotNull public Float getFloatItem() { @@ -131,7 +131,7 @@ public TypeHolderExample integerItem(Integer integerItem) { * Get integerItem * @return integerItem **/ - @JsonProperty("integer_item") + @JsonProperty(value = "integer_item") @ApiModelProperty(example = "-2", required = true, value = "") @NotNull public Integer getIntegerItem() { @@ -151,7 +151,7 @@ public TypeHolderExample boolItem(Boolean boolItem) { * Get boolItem * @return boolItem **/ - @JsonProperty("bool_item") + @JsonProperty(value = "bool_item") @ApiModelProperty(example = "true", required = true, value = "") @NotNull public Boolean getBoolItem() { @@ -176,7 +176,7 @@ public TypeHolderExample addArrayItemItem(Integer arrayItemItem) { * Get arrayItem * @return arrayItem **/ - @JsonProperty("array_item") + @JsonProperty(value = "array_item") @ApiModelProperty(example = "[0, 1, 2, 3]", required = true, value = "") @NotNull public List getArrayItem() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/User.java index 1e702dd070d5..37ab5453c3d2 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/User.java @@ -78,7 +78,7 @@ public User id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -98,7 +98,7 @@ public User username(String username) { * Get username * @return username **/ - @JsonProperty("username") + @JsonProperty(value = "username") @ApiModelProperty(value = "") public String getUsername() { @@ -118,7 +118,7 @@ public User firstName(String firstName) { * Get firstName * @return firstName **/ - @JsonProperty("firstName") + @JsonProperty(value = "firstName") @ApiModelProperty(value = "") public String getFirstName() { @@ -138,7 +138,7 @@ public User lastName(String lastName) { * Get lastName * @return lastName **/ - @JsonProperty("lastName") + @JsonProperty(value = "lastName") @ApiModelProperty(value = "") public String getLastName() { @@ -158,7 +158,7 @@ public User email(String email) { * Get email * @return email **/ - @JsonProperty("email") + @JsonProperty(value = "email") @ApiModelProperty(value = "") public String getEmail() { @@ -178,7 +178,7 @@ public User password(String password) { * Get password * @return password **/ - @JsonProperty("password") + @JsonProperty(value = "password") @ApiModelProperty(value = "") public String getPassword() { @@ -198,7 +198,7 @@ public User phone(String phone) { * Get phone * @return phone **/ - @JsonProperty("phone") + @JsonProperty(value = "phone") @ApiModelProperty(value = "") public String getPhone() { @@ -218,7 +218,7 @@ public User userStatus(Integer userStatus) { * User Status * @return userStatus **/ - @JsonProperty("userStatus") + @JsonProperty(value = "userStatus") @ApiModelProperty(value = "User Status") public Integer getUserStatus() { diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/XmlItem.java index 8c61e3e4cc0e..46c2de9ca268 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/model/XmlItem.java @@ -186,7 +186,7 @@ public XmlItem attributeString(String attributeString) { * Get attributeString * @return attributeString **/ - @JsonProperty("attribute_string") + @JsonProperty(value = "attribute_string") @ApiModelProperty(example = "string", value = "") public String getAttributeString() { @@ -206,7 +206,7 @@ public XmlItem attributeNumber(BigDecimal attributeNumber) { * Get attributeNumber * @return attributeNumber **/ - @JsonProperty("attribute_number") + @JsonProperty(value = "attribute_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getAttributeNumber() { @@ -226,7 +226,7 @@ public XmlItem attributeInteger(Integer attributeInteger) { * Get attributeInteger * @return attributeInteger **/ - @JsonProperty("attribute_integer") + @JsonProperty(value = "attribute_integer") @ApiModelProperty(example = "-2", value = "") public Integer getAttributeInteger() { @@ -246,7 +246,7 @@ public XmlItem attributeBoolean(Boolean attributeBoolean) { * Get attributeBoolean * @return attributeBoolean **/ - @JsonProperty("attribute_boolean") + @JsonProperty(value = "attribute_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getAttributeBoolean() { @@ -274,7 +274,7 @@ public XmlItem addWrappedArrayItem(Integer wrappedArrayItem) { * Get wrappedArray * @return wrappedArray **/ - @JsonProperty("wrapped_array") + @JsonProperty(value = "wrapped_array") @ApiModelProperty(value = "") public List getWrappedArray() { @@ -294,7 +294,7 @@ public XmlItem nameString(String nameString) { * Get nameString * @return nameString **/ - @JsonProperty("name_string") + @JsonProperty(value = "name_string") @ApiModelProperty(example = "string", value = "") public String getNameString() { @@ -314,7 +314,7 @@ public XmlItem nameNumber(BigDecimal nameNumber) { * Get nameNumber * @return nameNumber **/ - @JsonProperty("name_number") + @JsonProperty(value = "name_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getNameNumber() { @@ -334,7 +334,7 @@ public XmlItem nameInteger(Integer nameInteger) { * Get nameInteger * @return nameInteger **/ - @JsonProperty("name_integer") + @JsonProperty(value = "name_integer") @ApiModelProperty(example = "-2", value = "") public Integer getNameInteger() { @@ -354,7 +354,7 @@ public XmlItem nameBoolean(Boolean nameBoolean) { * Get nameBoolean * @return nameBoolean **/ - @JsonProperty("name_boolean") + @JsonProperty(value = "name_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getNameBoolean() { @@ -382,7 +382,7 @@ public XmlItem addNameArrayItem(Integer nameArrayItem) { * Get nameArray * @return nameArray **/ - @JsonProperty("name_array") + @JsonProperty(value = "name_array") @ApiModelProperty(value = "") public List getNameArray() { @@ -410,7 +410,7 @@ public XmlItem addNameWrappedArrayItem(Integer nameWrappedArrayItem) { * Get nameWrappedArray * @return nameWrappedArray **/ - @JsonProperty("name_wrapped_array") + @JsonProperty(value = "name_wrapped_array") @ApiModelProperty(value = "") public List getNameWrappedArray() { @@ -430,7 +430,7 @@ public XmlItem prefixString(String prefixString) { * Get prefixString * @return prefixString **/ - @JsonProperty("prefix_string") + @JsonProperty(value = "prefix_string") @ApiModelProperty(example = "string", value = "") public String getPrefixString() { @@ -450,7 +450,7 @@ public XmlItem prefixNumber(BigDecimal prefixNumber) { * Get prefixNumber * @return prefixNumber **/ - @JsonProperty("prefix_number") + @JsonProperty(value = "prefix_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getPrefixNumber() { @@ -470,7 +470,7 @@ public XmlItem prefixInteger(Integer prefixInteger) { * Get prefixInteger * @return prefixInteger **/ - @JsonProperty("prefix_integer") + @JsonProperty(value = "prefix_integer") @ApiModelProperty(example = "-2", value = "") public Integer getPrefixInteger() { @@ -490,7 +490,7 @@ public XmlItem prefixBoolean(Boolean prefixBoolean) { * Get prefixBoolean * @return prefixBoolean **/ - @JsonProperty("prefix_boolean") + @JsonProperty(value = "prefix_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getPrefixBoolean() { @@ -518,7 +518,7 @@ public XmlItem addPrefixArrayItem(Integer prefixArrayItem) { * Get prefixArray * @return prefixArray **/ - @JsonProperty("prefix_array") + @JsonProperty(value = "prefix_array") @ApiModelProperty(value = "") public List getPrefixArray() { @@ -546,7 +546,7 @@ public XmlItem addPrefixWrappedArrayItem(Integer prefixWrappedArrayItem) { * Get prefixWrappedArray * @return prefixWrappedArray **/ - @JsonProperty("prefix_wrapped_array") + @JsonProperty(value = "prefix_wrapped_array") @ApiModelProperty(value = "") public List getPrefixWrappedArray() { @@ -566,7 +566,7 @@ public XmlItem namespaceString(String namespaceString) { * Get namespaceString * @return namespaceString **/ - @JsonProperty("namespace_string") + @JsonProperty(value = "namespace_string") @ApiModelProperty(example = "string", value = "") public String getNamespaceString() { @@ -586,7 +586,7 @@ public XmlItem namespaceNumber(BigDecimal namespaceNumber) { * Get namespaceNumber * @return namespaceNumber **/ - @JsonProperty("namespace_number") + @JsonProperty(value = "namespace_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getNamespaceNumber() { @@ -606,7 +606,7 @@ public XmlItem namespaceInteger(Integer namespaceInteger) { * Get namespaceInteger * @return namespaceInteger **/ - @JsonProperty("namespace_integer") + @JsonProperty(value = "namespace_integer") @ApiModelProperty(example = "-2", value = "") public Integer getNamespaceInteger() { @@ -626,7 +626,7 @@ public XmlItem namespaceBoolean(Boolean namespaceBoolean) { * Get namespaceBoolean * @return namespaceBoolean **/ - @JsonProperty("namespace_boolean") + @JsonProperty(value = "namespace_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getNamespaceBoolean() { @@ -654,7 +654,7 @@ public XmlItem addNamespaceArrayItem(Integer namespaceArrayItem) { * Get namespaceArray * @return namespaceArray **/ - @JsonProperty("namespace_array") + @JsonProperty(value = "namespace_array") @ApiModelProperty(value = "") public List getNamespaceArray() { @@ -682,7 +682,7 @@ public XmlItem addNamespaceWrappedArrayItem(Integer namespaceWrappedArrayItem) { * Get namespaceWrappedArray * @return namespaceWrappedArray **/ - @JsonProperty("namespace_wrapped_array") + @JsonProperty(value = "namespace_wrapped_array") @ApiModelProperty(value = "") public List getNamespaceWrappedArray() { @@ -702,7 +702,7 @@ public XmlItem prefixNsString(String prefixNsString) { * Get prefixNsString * @return prefixNsString **/ - @JsonProperty("prefix_ns_string") + @JsonProperty(value = "prefix_ns_string") @ApiModelProperty(example = "string", value = "") public String getPrefixNsString() { @@ -722,7 +722,7 @@ public XmlItem prefixNsNumber(BigDecimal prefixNsNumber) { * Get prefixNsNumber * @return prefixNsNumber **/ - @JsonProperty("prefix_ns_number") + @JsonProperty(value = "prefix_ns_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getPrefixNsNumber() { @@ -742,7 +742,7 @@ public XmlItem prefixNsInteger(Integer prefixNsInteger) { * Get prefixNsInteger * @return prefixNsInteger **/ - @JsonProperty("prefix_ns_integer") + @JsonProperty(value = "prefix_ns_integer") @ApiModelProperty(example = "-2", value = "") public Integer getPrefixNsInteger() { @@ -762,7 +762,7 @@ public XmlItem prefixNsBoolean(Boolean prefixNsBoolean) { * Get prefixNsBoolean * @return prefixNsBoolean **/ - @JsonProperty("prefix_ns_boolean") + @JsonProperty(value = "prefix_ns_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getPrefixNsBoolean() { @@ -790,7 +790,7 @@ public XmlItem addPrefixNsArrayItem(Integer prefixNsArrayItem) { * Get prefixNsArray * @return prefixNsArray **/ - @JsonProperty("prefix_ns_array") + @JsonProperty(value = "prefix_ns_array") @ApiModelProperty(value = "") public List getPrefixNsArray() { @@ -818,7 +818,7 @@ public XmlItem addPrefixNsWrappedArrayItem(Integer prefixNsWrappedArrayItem) { * Get prefixNsWrappedArray * @return prefixNsWrappedArray **/ - @JsonProperty("prefix_ns_wrapped_array") + @JsonProperty(value = "prefix_ns_wrapped_array") @ApiModelProperty(value = "") public List getPrefixNsWrappedArray() { diff --git a/samples/server/petstore/jaxrs/jersey1/.openapi-generator/VERSION b/samples/server/petstore/jaxrs/jersey1/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs/jersey1/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs/jersey1/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java index 94ab4ee99b59..b69405239b38 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java @@ -45,7 +45,7 @@ public AdditionalPropertiesAnyType name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java index 8a7cbbfa5e79..f90d93c37aec 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java @@ -46,7 +46,7 @@ public AdditionalPropertiesArray name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java index 8e5e3a7ec7cc..473358d6cda0 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java @@ -45,7 +45,7 @@ public AdditionalPropertiesBoolean name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index df959efecfe6..bf846cfb6bf7 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -105,7 +105,7 @@ public AdditionalPropertiesClass putMapStringItem(String key, String mapStringIt * Get mapString * @return mapString **/ - @JsonProperty("map_string") + @JsonProperty(value = "map_string") @ApiModelProperty(value = "") public Map getMapString() { @@ -133,7 +133,7 @@ public AdditionalPropertiesClass putMapNumberItem(String key, BigDecimal mapNumb * Get mapNumber * @return mapNumber **/ - @JsonProperty("map_number") + @JsonProperty(value = "map_number") @ApiModelProperty(value = "") @Valid public Map getMapNumber() { @@ -161,7 +161,7 @@ public AdditionalPropertiesClass putMapIntegerItem(String key, Integer mapIntege * Get mapInteger * @return mapInteger **/ - @JsonProperty("map_integer") + @JsonProperty(value = "map_integer") @ApiModelProperty(value = "") public Map getMapInteger() { @@ -189,7 +189,7 @@ public AdditionalPropertiesClass putMapBooleanItem(String key, Boolean mapBoolea * Get mapBoolean * @return mapBoolean **/ - @JsonProperty("map_boolean") + @JsonProperty(value = "map_boolean") @ApiModelProperty(value = "") public Map getMapBoolean() { @@ -217,7 +217,7 @@ public AdditionalPropertiesClass putMapArrayIntegerItem(String key, List> getMapArrayInteger() { @@ -245,7 +245,7 @@ public AdditionalPropertiesClass putMapArrayAnytypeItem(String key, List * Get mapArrayAnytype * @return mapArrayAnytype **/ - @JsonProperty("map_array_anytype") + @JsonProperty(value = "map_array_anytype") @ApiModelProperty(value = "") @Valid public Map> getMapArrayAnytype() { @@ -273,7 +273,7 @@ public AdditionalPropertiesClass putMapMapStringItem(String key, Map> getMapMapString() { @@ -301,7 +301,7 @@ public AdditionalPropertiesClass putMapMapAnytypeItem(String key, Map> getMapMapAnytype() { @@ -321,7 +321,7 @@ public AdditionalPropertiesClass anytype1(Object anytype1) { * Get anytype1 * @return anytype1 **/ - @JsonProperty("anytype_1") + @JsonProperty(value = "anytype_1") @ApiModelProperty(value = "") public Object getAnytype1() { @@ -341,7 +341,7 @@ public AdditionalPropertiesClass anytype2(Object anytype2) { * Get anytype2 * @return anytype2 **/ - @JsonProperty("anytype_2") + @JsonProperty(value = "anytype_2") @ApiModelProperty(value = "") public Object getAnytype2() { @@ -361,7 +361,7 @@ public AdditionalPropertiesClass anytype3(Object anytype3) { * Get anytype3 * @return anytype3 **/ - @JsonProperty("anytype_3") + @JsonProperty(value = "anytype_3") @ApiModelProperty(value = "") public Object getAnytype3() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java index ac5f7501b3a8..29bd12be784b 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java @@ -45,7 +45,7 @@ public AdditionalPropertiesInteger name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java index d3072f447dca..f05484cd7cc7 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java @@ -46,7 +46,7 @@ public AdditionalPropertiesNumber name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java index 8f8b575df2a2..fb246cac6598 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java @@ -45,7 +45,7 @@ public AdditionalPropertiesObject name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java index c5d4ac7f7c1b..b7018e370e50 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java @@ -45,7 +45,7 @@ public AdditionalPropertiesString name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Animal.java index db142b932d90..97cdd70ab0a1 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Animal.java @@ -56,7 +56,7 @@ public Animal className(String className) { * Get className * @return className **/ - @JsonProperty("className") + @JsonProperty(value = "className") @ApiModelProperty(required = true, value = "") @NotNull public String getClassName() { @@ -76,7 +76,7 @@ public Animal color(String color) { * Get color * @return color **/ - @JsonProperty("color") + @JsonProperty(value = "color") @ApiModelProperty(value = "") public String getColor() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index cd6a16edb265..d277c77993f3 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -54,7 +54,7 @@ public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayAr * Get arrayArrayNumber * @return arrayArrayNumber **/ - @JsonProperty("ArrayArrayNumber") + @JsonProperty(value = "ArrayArrayNumber") @ApiModelProperty(value = "") @Valid public List> getArrayArrayNumber() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index 71d88cd5d890..f8b08e16723e 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -54,7 +54,7 @@ public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { * Get arrayNumber * @return arrayNumber **/ - @JsonProperty("ArrayNumber") + @JsonProperty(value = "ArrayNumber") @ApiModelProperty(value = "") @Valid public List getArrayNumber() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ArrayTest.java index 738fa858e7e7..dfeb88958dca 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ArrayTest.java @@ -64,7 +64,7 @@ public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { * Get arrayOfString * @return arrayOfString **/ - @JsonProperty("array_of_string") + @JsonProperty(value = "array_of_string") @ApiModelProperty(value = "") public List getArrayOfString() { @@ -92,7 +92,7 @@ public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) * Get arrayArrayOfInteger * @return arrayArrayOfInteger **/ - @JsonProperty("array_array_of_integer") + @JsonProperty(value = "array_array_of_integer") @ApiModelProperty(value = "") @Valid public List> getArrayArrayOfInteger() { @@ -120,7 +120,7 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI * Get arrayArrayOfModel * @return arrayArrayOfModel **/ - @JsonProperty("array_array_of_model") + @JsonProperty(value = "array_array_of_model") @ApiModelProperty(value = "") @Valid public List> getArrayArrayOfModel() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/BigCat.java index 0af195ad0a72..867f51230021 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/BigCat.java @@ -81,7 +81,7 @@ public BigCat kind(KindEnum kind) { * Get kind * @return kind **/ - @JsonProperty("kind") + @JsonProperty(value = "kind") @ApiModelProperty(value = "") public KindEnum getKind() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/BigCatAllOf.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/BigCatAllOf.java index eaf4e4f49f5e..ae1220fcefd1 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/BigCatAllOf.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/BigCatAllOf.java @@ -79,7 +79,7 @@ public BigCatAllOf kind(KindEnum kind) { * Get kind * @return kind **/ - @JsonProperty("kind") + @JsonProperty(value = "kind") @ApiModelProperty(value = "") public KindEnum getKind() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Capitalization.java index 9b99fe2b58b3..650d2c7b790b 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Capitalization.java @@ -68,7 +68,7 @@ public Capitalization smallCamel(String smallCamel) { * Get smallCamel * @return smallCamel **/ - @JsonProperty("smallCamel") + @JsonProperty(value = "smallCamel") @ApiModelProperty(value = "") public String getSmallCamel() { @@ -88,7 +88,7 @@ public Capitalization capitalCamel(String capitalCamel) { * Get capitalCamel * @return capitalCamel **/ - @JsonProperty("CapitalCamel") + @JsonProperty(value = "CapitalCamel") @ApiModelProperty(value = "") public String getCapitalCamel() { @@ -108,7 +108,7 @@ public Capitalization smallSnake(String smallSnake) { * Get smallSnake * @return smallSnake **/ - @JsonProperty("small_Snake") + @JsonProperty(value = "small_Snake") @ApiModelProperty(value = "") public String getSmallSnake() { @@ -128,7 +128,7 @@ public Capitalization capitalSnake(String capitalSnake) { * Get capitalSnake * @return capitalSnake **/ - @JsonProperty("Capital_Snake") + @JsonProperty(value = "Capital_Snake") @ApiModelProperty(value = "") public String getCapitalSnake() { @@ -148,7 +148,7 @@ public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { * Get scAETHFlowPoints * @return scAETHFlowPoints **/ - @JsonProperty("SCA_ETH_Flow_Points") + @JsonProperty(value = "SCA_ETH_Flow_Points") @ApiModelProperty(value = "") public String getScAETHFlowPoints() { @@ -168,7 +168,7 @@ public Capitalization ATT_NAME(String ATT_NAME) { * Name of the pet * @return ATT_NAME **/ - @JsonProperty("ATT_NAME") + @JsonProperty(value = "ATT_NAME") @ApiModelProperty(value = "Name of the pet ") public String getATTNAME() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Cat.java index a393506d3aa5..ef4f615bfe76 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Cat.java @@ -45,7 +45,7 @@ public Cat declawed(Boolean declawed) { * Get declawed * @return declawed **/ - @JsonProperty("declawed") + @JsonProperty(value = "declawed") @ApiModelProperty(value = "") public Boolean getDeclawed() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/CatAllOf.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/CatAllOf.java index 7e2a72595950..83503a712d2b 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/CatAllOf.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/CatAllOf.java @@ -43,7 +43,7 @@ public CatAllOf declawed(Boolean declawed) { * Get declawed * @return declawed **/ - @JsonProperty("declawed") + @JsonProperty(value = "declawed") @ApiModelProperty(value = "") public Boolean getDeclawed() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Category.java index d7a5c2b2fafa..af6055dba4ea 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Category.java @@ -48,7 +48,7 @@ public Category id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -68,7 +68,7 @@ public Category name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(required = true, value = "") @NotNull public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ClassModel.java index 00352ed5bce9..ccfe8e27684e 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ClassModel.java @@ -44,7 +44,7 @@ public ClassModel propertyClass(String propertyClass) { * Get propertyClass * @return propertyClass **/ - @JsonProperty("_class") + @JsonProperty(value = "_class") @ApiModelProperty(value = "") public String getPropertyClass() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Client.java index 04b28287ed41..0c87d7030a57 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Client.java @@ -43,7 +43,7 @@ public Client client(String client) { * Get client * @return client **/ - @JsonProperty("client") + @JsonProperty(value = "client") @ApiModelProperty(value = "") public String getClient() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Dog.java index 7d6059b2fc1f..e126444fd61e 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Dog.java @@ -45,7 +45,7 @@ public Dog breed(String breed) { * Get breed * @return breed **/ - @JsonProperty("breed") + @JsonProperty(value = "breed") @ApiModelProperty(value = "") public String getBreed() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/DogAllOf.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/DogAllOf.java index 9fcfbfb92cfc..6902a980c243 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/DogAllOf.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/DogAllOf.java @@ -43,7 +43,7 @@ public DogAllOf breed(String breed) { * Get breed * @return breed **/ - @JsonProperty("breed") + @JsonProperty(value = "breed") @ApiModelProperty(value = "") public String getBreed() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/EnumArrays.java index 526f387372ca..08e6db1ffc92 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/EnumArrays.java @@ -113,7 +113,7 @@ public EnumArrays justSymbol(JustSymbolEnum justSymbol) { * Get justSymbol * @return justSymbol **/ - @JsonProperty("just_symbol") + @JsonProperty(value = "just_symbol") @ApiModelProperty(value = "") public JustSymbolEnum getJustSymbol() { @@ -141,7 +141,7 @@ public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { * Get arrayEnum * @return arrayEnum **/ - @JsonProperty("array_enum") + @JsonProperty(value = "array_enum") @ApiModelProperty(value = "") public List getArrayEnum() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/EnumTest.java index ee08eadfa8d7..937a9f7f6aeb 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/EnumTest.java @@ -193,7 +193,7 @@ public EnumTest enumString(EnumStringEnum enumString) { * Get enumString * @return enumString **/ - @JsonProperty("enum_string") + @JsonProperty(value = "enum_string") @ApiModelProperty(value = "") public EnumStringEnum getEnumString() { @@ -213,7 +213,7 @@ public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { * Get enumStringRequired * @return enumStringRequired **/ - @JsonProperty("enum_string_required") + @JsonProperty(value = "enum_string_required") @ApiModelProperty(required = true, value = "") @NotNull public EnumStringRequiredEnum getEnumStringRequired() { @@ -233,7 +233,7 @@ public EnumTest enumInteger(EnumIntegerEnum enumInteger) { * Get enumInteger * @return enumInteger **/ - @JsonProperty("enum_integer") + @JsonProperty(value = "enum_integer") @ApiModelProperty(value = "") public EnumIntegerEnum getEnumInteger() { @@ -253,7 +253,7 @@ public EnumTest enumNumber(EnumNumberEnum enumNumber) { * Get enumNumber * @return enumNumber **/ - @JsonProperty("enum_number") + @JsonProperty(value = "enum_number") @ApiModelProperty(value = "") public EnumNumberEnum getEnumNumber() { @@ -273,7 +273,7 @@ public EnumTest outerEnum(OuterEnum outerEnum) { * Get outerEnum * @return outerEnum **/ - @JsonProperty("outerEnum") + @JsonProperty(value = "outerEnum") @ApiModelProperty(value = "") @Valid public OuterEnum getOuterEnum() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 4be816893906..fb40a511e446 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -50,7 +50,7 @@ public FileSchemaTestClass file(java.io.File file) { * Get file * @return file **/ - @JsonProperty("file") + @JsonProperty(value = "file") @ApiModelProperty(value = "") @Valid public java.io.File getFile() { @@ -78,7 +78,7 @@ public FileSchemaTestClass addFilesItem(java.io.File filesItem) { * Get files * @return files **/ - @JsonProperty("files") + @JsonProperty(value = "files") @ApiModelProperty(value = "") @Valid public List getFiles() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/FormatTest.java index 9817e78712a7..d640a11342c7 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/FormatTest.java @@ -114,7 +114,7 @@ public FormatTest integer(Integer integer) { * maximum: 100 * @return integer **/ - @JsonProperty("integer") + @JsonProperty(value = "integer") @ApiModelProperty(value = "") @Min(10) @Max(100) public Integer getInteger() { @@ -136,7 +136,7 @@ public FormatTest int32(Integer int32) { * maximum: 200 * @return int32 **/ - @JsonProperty("int32") + @JsonProperty(value = "int32") @ApiModelProperty(value = "") @Min(20) @Max(200) public Integer getInt32() { @@ -156,7 +156,7 @@ public FormatTest int64(Long int64) { * Get int64 * @return int64 **/ - @JsonProperty("int64") + @JsonProperty(value = "int64") @ApiModelProperty(value = "") public Long getInt64() { @@ -178,7 +178,7 @@ public FormatTest number(BigDecimal number) { * maximum: 543.2 * @return number **/ - @JsonProperty("number") + @JsonProperty(value = "number") @ApiModelProperty(required = true, value = "") @NotNull @Valid @DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { @@ -200,7 +200,7 @@ public FormatTest _float(Float _float) { * maximum: 987.6 * @return _float **/ - @JsonProperty("float") + @JsonProperty(value = "float") @ApiModelProperty(value = "") @DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { @@ -222,7 +222,7 @@ public FormatTest _double(Double _double) { * maximum: 123.4 * @return _double **/ - @JsonProperty("double") + @JsonProperty(value = "double") @ApiModelProperty(value = "") @DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { @@ -242,7 +242,7 @@ public FormatTest string(String string) { * Get string * @return string **/ - @JsonProperty("string") + @JsonProperty(value = "string") @ApiModelProperty(value = "") @Pattern(regexp="/[a-z]/i") public String getString() { @@ -262,7 +262,7 @@ public FormatTest _byte(byte[] _byte) { * Get _byte * @return _byte **/ - @JsonProperty("byte") + @JsonProperty(value = "byte") @ApiModelProperty(required = true, value = "") @NotNull public byte[] getByte() { @@ -282,7 +282,7 @@ public FormatTest binary(File binary) { * Get binary * @return binary **/ - @JsonProperty("binary") + @JsonProperty(value = "binary") @ApiModelProperty(value = "") public File getBinary() { @@ -302,7 +302,7 @@ public FormatTest date(Date date) { * Get date * @return date **/ - @JsonProperty("date") + @JsonProperty(value = "date") @ApiModelProperty(required = true, value = "") @NotNull public Date getDate() { @@ -322,7 +322,7 @@ public FormatTest dateTime(Date dateTime) { * Get dateTime * @return dateTime **/ - @JsonProperty("dateTime") + @JsonProperty(value = "dateTime") @ApiModelProperty(value = "") public Date getDateTime() { @@ -342,7 +342,7 @@ public FormatTest uuid(UUID uuid) { * Get uuid * @return uuid **/ - @JsonProperty("uuid") + @JsonProperty(value = "uuid") @ApiModelProperty(example = "72f98069-206d-4f12-9f12-3d1e525a8e84", value = "") public UUID getUuid() { @@ -362,7 +362,7 @@ public FormatTest password(String password) { * Get password * @return password **/ - @JsonProperty("password") + @JsonProperty(value = "password") @ApiModelProperty(required = true, value = "") @NotNull @Size(min=10,max=64) public String getPassword() { @@ -382,7 +382,7 @@ public FormatTest bigDecimal(BigDecimal bigDecimal) { * Get bigDecimal * @return bigDecimal **/ - @JsonProperty("BigDecimal") + @JsonProperty(value = "BigDecimal") @ApiModelProperty(value = "") @Valid public BigDecimal getBigDecimal() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index 4f72442fd947..1b5042f61f59 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -48,7 +48,7 @@ public HasOnlyReadOnly bar(String bar) { * Get bar * @return bar **/ - @JsonProperty("bar") + @JsonProperty(value = "bar", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getBar() { @@ -68,7 +68,7 @@ public HasOnlyReadOnly foo(String foo) { * Get foo * @return foo **/ - @JsonProperty("foo") + @JsonProperty(value = "foo", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getFoo() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/MapTest.java index 4db676efea2d..12516e0afba2 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/MapTest.java @@ -101,7 +101,7 @@ public MapTest putMapMapOfStringItem(String key, Map mapMapOfStr * Get mapMapOfString * @return mapMapOfString **/ - @JsonProperty("map_map_of_string") + @JsonProperty(value = "map_map_of_string") @ApiModelProperty(value = "") @Valid public Map> getMapMapOfString() { @@ -129,7 +129,7 @@ public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) * Get mapOfEnumString * @return mapOfEnumString **/ - @JsonProperty("map_of_enum_string") + @JsonProperty(value = "map_of_enum_string") @ApiModelProperty(value = "") public Map getMapOfEnumString() { @@ -157,7 +157,7 @@ public MapTest putDirectMapItem(String key, Boolean directMapItem) { * Get directMap * @return directMap **/ - @JsonProperty("direct_map") + @JsonProperty(value = "direct_map") @ApiModelProperty(value = "") public Map getDirectMap() { @@ -185,7 +185,7 @@ public MapTest putIndirectMapItem(String key, Boolean indirectMapItem) { * Get indirectMap * @return indirectMap **/ - @JsonProperty("indirect_map") + @JsonProperty(value = "indirect_map") @ApiModelProperty(value = "") public Map getIndirectMap() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index 0ba358c6b5c2..eb4fcd577811 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -59,7 +59,7 @@ public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { * Get uuid * @return uuid **/ - @JsonProperty("uuid") + @JsonProperty(value = "uuid") @ApiModelProperty(value = "") public UUID getUuid() { @@ -79,7 +79,7 @@ public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { * Get dateTime * @return dateTime **/ - @JsonProperty("dateTime") + @JsonProperty(value = "dateTime") @ApiModelProperty(value = "") public Date getDateTime() { @@ -107,7 +107,7 @@ public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal * Get map * @return map **/ - @JsonProperty("map") + @JsonProperty(value = "map") @ApiModelProperty(value = "") @Valid public Map getMap() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Model200Response.java index 2df0caa9725d..1a3e698983e5 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Model200Response.java @@ -49,7 +49,7 @@ public Model200Response name(Integer name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public Integer getName() { @@ -69,7 +69,7 @@ public Model200Response propertyClass(String propertyClass) { * Get propertyClass * @return propertyClass **/ - @JsonProperty("class") + @JsonProperty(value = "class") @ApiModelProperty(value = "") public String getPropertyClass() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ModelApiResponse.java index b0d01665ef6a..1552245d1dc8 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -53,7 +53,7 @@ public ModelApiResponse code(Integer code) { * Get code * @return code **/ - @JsonProperty("code") + @JsonProperty(value = "code") @ApiModelProperty(value = "") public Integer getCode() { @@ -73,7 +73,7 @@ public ModelApiResponse type(String type) { * Get type * @return type **/ - @JsonProperty("type") + @JsonProperty(value = "type") @ApiModelProperty(value = "") public String getType() { @@ -93,7 +93,7 @@ public ModelApiResponse message(String message) { * Get message * @return message **/ - @JsonProperty("message") + @JsonProperty(value = "message") @ApiModelProperty(value = "") public String getMessage() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ModelReturn.java index 41a1c059f7ef..c9f4504d3f0e 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ModelReturn.java @@ -44,7 +44,7 @@ public ModelReturn _return(Integer _return) { * Get _return * @return _return **/ - @JsonProperty("return") + @JsonProperty(value = "return") @ApiModelProperty(value = "") public Integer getReturn() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Name.java index a7a189571897..cdcef856cd21 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Name.java @@ -59,7 +59,7 @@ public Name name(Integer name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(required = true, value = "") @NotNull public Integer getName() { @@ -79,7 +79,7 @@ public Name snakeCase(Integer snakeCase) { * Get snakeCase * @return snakeCase **/ - @JsonProperty("snake_case") + @JsonProperty(value = "snake_case", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public Integer getSnakeCase() { @@ -99,7 +99,7 @@ public Name property(String property) { * Get property * @return property **/ - @JsonProperty("property") + @JsonProperty(value = "property") @ApiModelProperty(value = "") public String getProperty() { @@ -119,7 +119,7 @@ public Name _123number(Integer _123number) { * Get _123number * @return _123number **/ - @JsonProperty("123Number") + @JsonProperty(value = "123Number", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public Integer get123number() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/NumberOnly.java index 188899dc4460..3ec25c75ae59 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/NumberOnly.java @@ -44,7 +44,7 @@ public NumberOnly justNumber(BigDecimal justNumber) { * Get justNumber * @return justNumber **/ - @JsonProperty("JustNumber") + @JsonProperty(value = "JustNumber") @ApiModelProperty(value = "") @Valid public BigDecimal getJustNumber() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Order.java index 7ce0000199f9..b97b051ebc80 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Order.java @@ -103,7 +103,7 @@ public Order id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -123,7 +123,7 @@ public Order petId(Long petId) { * Get petId * @return petId **/ - @JsonProperty("petId") + @JsonProperty(value = "petId") @ApiModelProperty(value = "") public Long getPetId() { @@ -143,7 +143,7 @@ public Order quantity(Integer quantity) { * Get quantity * @return quantity **/ - @JsonProperty("quantity") + @JsonProperty(value = "quantity") @ApiModelProperty(value = "") public Integer getQuantity() { @@ -163,7 +163,7 @@ public Order shipDate(Date shipDate) { * Get shipDate * @return shipDate **/ - @JsonProperty("shipDate") + @JsonProperty(value = "shipDate") @ApiModelProperty(value = "") public Date getShipDate() { @@ -183,7 +183,7 @@ public Order status(StatusEnum status) { * Order Status * @return status **/ - @JsonProperty("status") + @JsonProperty(value = "status") @ApiModelProperty(value = "Order Status") public StatusEnum getStatus() { @@ -203,7 +203,7 @@ public Order complete(Boolean complete) { * Get complete * @return complete **/ - @JsonProperty("complete") + @JsonProperty(value = "complete") @ApiModelProperty(value = "") public Boolean getComplete() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/OuterComposite.java index 43b69002d036..577504e1bef2 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/OuterComposite.java @@ -54,7 +54,7 @@ public OuterComposite myNumber(BigDecimal myNumber) { * Get myNumber * @return myNumber **/ - @JsonProperty("my_number") + @JsonProperty(value = "my_number") @ApiModelProperty(value = "") @Valid public BigDecimal getMyNumber() { @@ -74,7 +74,7 @@ public OuterComposite myString(String myString) { * Get myString * @return myString **/ - @JsonProperty("my_string") + @JsonProperty(value = "my_string") @ApiModelProperty(value = "") public String getMyString() { @@ -94,7 +94,7 @@ public OuterComposite myBoolean(Boolean myBoolean) { * Get myBoolean * @return myBoolean **/ - @JsonProperty("my_boolean") + @JsonProperty(value = "my_boolean") @ApiModelProperty(value = "") public Boolean getMyBoolean() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Pet.java index adcdbf24a57d..4ed108d787e9 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Pet.java @@ -108,7 +108,7 @@ public Pet id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -128,7 +128,7 @@ public Pet category(Category category) { * Get category * @return category **/ - @JsonProperty("category") + @JsonProperty(value = "category") @ApiModelProperty(value = "") @Valid public Category getCategory() { @@ -148,7 +148,7 @@ public Pet name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(example = "doggie", required = true, value = "") @NotNull public String getName() { @@ -173,7 +173,7 @@ public Pet addPhotoUrlsItem(String photoUrlsItem) { * Get photoUrls * @return photoUrls **/ - @JsonProperty("photoUrls") + @JsonProperty(value = "photoUrls") @ApiModelProperty(required = true, value = "") @NotNull public Set getPhotoUrls() { @@ -201,7 +201,7 @@ public Pet addTagsItem(Tag tagsItem) { * Get tags * @return tags **/ - @JsonProperty("tags") + @JsonProperty(value = "tags") @ApiModelProperty(value = "") @Valid public List getTags() { @@ -221,7 +221,7 @@ public Pet status(StatusEnum status) { * pet status in the store * @return status **/ - @JsonProperty("status") + @JsonProperty(value = "status") @ApiModelProperty(value = "pet status in the store") public StatusEnum getStatus() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index e2e5ea910e68..05c01064ff67 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -48,7 +48,7 @@ public ReadOnlyFirst bar(String bar) { * Get bar * @return bar **/ - @JsonProperty("bar") + @JsonProperty(value = "bar", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getBar() { @@ -68,7 +68,7 @@ public ReadOnlyFirst baz(String baz) { * Get baz * @return baz **/ - @JsonProperty("baz") + @JsonProperty(value = "baz") @ApiModelProperty(value = "") public String getBaz() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/SpecialModelName.java index 48ed44ecf621..1fbc58e301e6 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -43,7 +43,7 @@ public class SpecialModelName { * Get $specialPropertyName * @return $specialPropertyName **/ - @JsonProperty("$special[property.name]") + @JsonProperty(value = "$special[property.name]") @ApiModelProperty(value = "") public Long get$SpecialPropertyName() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Tag.java index 80d098d57c16..5ac82ca92382 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/Tag.java @@ -48,7 +48,7 @@ public Tag id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -68,7 +68,7 @@ public Tag name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/TypeHolderDefault.java index 52830413a08c..a8450d0e61d5 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/TypeHolderDefault.java @@ -66,7 +66,7 @@ public TypeHolderDefault stringItem(String stringItem) { * Get stringItem * @return stringItem **/ - @JsonProperty("string_item") + @JsonProperty(value = "string_item") @ApiModelProperty(required = true, value = "") @NotNull public String getStringItem() { @@ -86,7 +86,7 @@ public TypeHolderDefault numberItem(BigDecimal numberItem) { * Get numberItem * @return numberItem **/ - @JsonProperty("number_item") + @JsonProperty(value = "number_item") @ApiModelProperty(required = true, value = "") @NotNull @Valid public BigDecimal getNumberItem() { @@ -106,7 +106,7 @@ public TypeHolderDefault integerItem(Integer integerItem) { * Get integerItem * @return integerItem **/ - @JsonProperty("integer_item") + @JsonProperty(value = "integer_item") @ApiModelProperty(required = true, value = "") @NotNull public Integer getIntegerItem() { @@ -126,7 +126,7 @@ public TypeHolderDefault boolItem(Boolean boolItem) { * Get boolItem * @return boolItem **/ - @JsonProperty("bool_item") + @JsonProperty(value = "bool_item") @ApiModelProperty(required = true, value = "") @NotNull public Boolean getBoolItem() { @@ -151,7 +151,7 @@ public TypeHolderDefault addArrayItemItem(Integer arrayItemItem) { * Get arrayItem * @return arrayItem **/ - @JsonProperty("array_item") + @JsonProperty(value = "array_item") @ApiModelProperty(required = true, value = "") @NotNull public List getArrayItem() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/TypeHolderExample.java index 8e57cc93cef4..026943cb64e3 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/TypeHolderExample.java @@ -71,7 +71,7 @@ public TypeHolderExample stringItem(String stringItem) { * Get stringItem * @return stringItem **/ - @JsonProperty("string_item") + @JsonProperty(value = "string_item") @ApiModelProperty(example = "what", required = true, value = "") @NotNull public String getStringItem() { @@ -91,7 +91,7 @@ public TypeHolderExample numberItem(BigDecimal numberItem) { * Get numberItem * @return numberItem **/ - @JsonProperty("number_item") + @JsonProperty(value = "number_item") @ApiModelProperty(example = "1.234", required = true, value = "") @NotNull @Valid public BigDecimal getNumberItem() { @@ -111,7 +111,7 @@ public TypeHolderExample floatItem(Float floatItem) { * Get floatItem * @return floatItem **/ - @JsonProperty("float_item") + @JsonProperty(value = "float_item") @ApiModelProperty(example = "1.234", required = true, value = "") @NotNull public Float getFloatItem() { @@ -131,7 +131,7 @@ public TypeHolderExample integerItem(Integer integerItem) { * Get integerItem * @return integerItem **/ - @JsonProperty("integer_item") + @JsonProperty(value = "integer_item") @ApiModelProperty(example = "-2", required = true, value = "") @NotNull public Integer getIntegerItem() { @@ -151,7 +151,7 @@ public TypeHolderExample boolItem(Boolean boolItem) { * Get boolItem * @return boolItem **/ - @JsonProperty("bool_item") + @JsonProperty(value = "bool_item") @ApiModelProperty(example = "true", required = true, value = "") @NotNull public Boolean getBoolItem() { @@ -176,7 +176,7 @@ public TypeHolderExample addArrayItemItem(Integer arrayItemItem) { * Get arrayItem * @return arrayItem **/ - @JsonProperty("array_item") + @JsonProperty(value = "array_item") @ApiModelProperty(example = "[0, 1, 2, 3]", required = true, value = "") @NotNull public List getArrayItem() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/User.java index 1e702dd070d5..37ab5453c3d2 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/User.java @@ -78,7 +78,7 @@ public User id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -98,7 +98,7 @@ public User username(String username) { * Get username * @return username **/ - @JsonProperty("username") + @JsonProperty(value = "username") @ApiModelProperty(value = "") public String getUsername() { @@ -118,7 +118,7 @@ public User firstName(String firstName) { * Get firstName * @return firstName **/ - @JsonProperty("firstName") + @JsonProperty(value = "firstName") @ApiModelProperty(value = "") public String getFirstName() { @@ -138,7 +138,7 @@ public User lastName(String lastName) { * Get lastName * @return lastName **/ - @JsonProperty("lastName") + @JsonProperty(value = "lastName") @ApiModelProperty(value = "") public String getLastName() { @@ -158,7 +158,7 @@ public User email(String email) { * Get email * @return email **/ - @JsonProperty("email") + @JsonProperty(value = "email") @ApiModelProperty(value = "") public String getEmail() { @@ -178,7 +178,7 @@ public User password(String password) { * Get password * @return password **/ - @JsonProperty("password") + @JsonProperty(value = "password") @ApiModelProperty(value = "") public String getPassword() { @@ -198,7 +198,7 @@ public User phone(String phone) { * Get phone * @return phone **/ - @JsonProperty("phone") + @JsonProperty(value = "phone") @ApiModelProperty(value = "") public String getPhone() { @@ -218,7 +218,7 @@ public User userStatus(Integer userStatus) { * User Status * @return userStatus **/ - @JsonProperty("userStatus") + @JsonProperty(value = "userStatus") @ApiModelProperty(value = "User Status") public Integer getUserStatus() { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/XmlItem.java index 8c61e3e4cc0e..46c2de9ca268 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/model/XmlItem.java @@ -186,7 +186,7 @@ public XmlItem attributeString(String attributeString) { * Get attributeString * @return attributeString **/ - @JsonProperty("attribute_string") + @JsonProperty(value = "attribute_string") @ApiModelProperty(example = "string", value = "") public String getAttributeString() { @@ -206,7 +206,7 @@ public XmlItem attributeNumber(BigDecimal attributeNumber) { * Get attributeNumber * @return attributeNumber **/ - @JsonProperty("attribute_number") + @JsonProperty(value = "attribute_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getAttributeNumber() { @@ -226,7 +226,7 @@ public XmlItem attributeInteger(Integer attributeInteger) { * Get attributeInteger * @return attributeInteger **/ - @JsonProperty("attribute_integer") + @JsonProperty(value = "attribute_integer") @ApiModelProperty(example = "-2", value = "") public Integer getAttributeInteger() { @@ -246,7 +246,7 @@ public XmlItem attributeBoolean(Boolean attributeBoolean) { * Get attributeBoolean * @return attributeBoolean **/ - @JsonProperty("attribute_boolean") + @JsonProperty(value = "attribute_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getAttributeBoolean() { @@ -274,7 +274,7 @@ public XmlItem addWrappedArrayItem(Integer wrappedArrayItem) { * Get wrappedArray * @return wrappedArray **/ - @JsonProperty("wrapped_array") + @JsonProperty(value = "wrapped_array") @ApiModelProperty(value = "") public List getWrappedArray() { @@ -294,7 +294,7 @@ public XmlItem nameString(String nameString) { * Get nameString * @return nameString **/ - @JsonProperty("name_string") + @JsonProperty(value = "name_string") @ApiModelProperty(example = "string", value = "") public String getNameString() { @@ -314,7 +314,7 @@ public XmlItem nameNumber(BigDecimal nameNumber) { * Get nameNumber * @return nameNumber **/ - @JsonProperty("name_number") + @JsonProperty(value = "name_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getNameNumber() { @@ -334,7 +334,7 @@ public XmlItem nameInteger(Integer nameInteger) { * Get nameInteger * @return nameInteger **/ - @JsonProperty("name_integer") + @JsonProperty(value = "name_integer") @ApiModelProperty(example = "-2", value = "") public Integer getNameInteger() { @@ -354,7 +354,7 @@ public XmlItem nameBoolean(Boolean nameBoolean) { * Get nameBoolean * @return nameBoolean **/ - @JsonProperty("name_boolean") + @JsonProperty(value = "name_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getNameBoolean() { @@ -382,7 +382,7 @@ public XmlItem addNameArrayItem(Integer nameArrayItem) { * Get nameArray * @return nameArray **/ - @JsonProperty("name_array") + @JsonProperty(value = "name_array") @ApiModelProperty(value = "") public List getNameArray() { @@ -410,7 +410,7 @@ public XmlItem addNameWrappedArrayItem(Integer nameWrappedArrayItem) { * Get nameWrappedArray * @return nameWrappedArray **/ - @JsonProperty("name_wrapped_array") + @JsonProperty(value = "name_wrapped_array") @ApiModelProperty(value = "") public List getNameWrappedArray() { @@ -430,7 +430,7 @@ public XmlItem prefixString(String prefixString) { * Get prefixString * @return prefixString **/ - @JsonProperty("prefix_string") + @JsonProperty(value = "prefix_string") @ApiModelProperty(example = "string", value = "") public String getPrefixString() { @@ -450,7 +450,7 @@ public XmlItem prefixNumber(BigDecimal prefixNumber) { * Get prefixNumber * @return prefixNumber **/ - @JsonProperty("prefix_number") + @JsonProperty(value = "prefix_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getPrefixNumber() { @@ -470,7 +470,7 @@ public XmlItem prefixInteger(Integer prefixInteger) { * Get prefixInteger * @return prefixInteger **/ - @JsonProperty("prefix_integer") + @JsonProperty(value = "prefix_integer") @ApiModelProperty(example = "-2", value = "") public Integer getPrefixInteger() { @@ -490,7 +490,7 @@ public XmlItem prefixBoolean(Boolean prefixBoolean) { * Get prefixBoolean * @return prefixBoolean **/ - @JsonProperty("prefix_boolean") + @JsonProperty(value = "prefix_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getPrefixBoolean() { @@ -518,7 +518,7 @@ public XmlItem addPrefixArrayItem(Integer prefixArrayItem) { * Get prefixArray * @return prefixArray **/ - @JsonProperty("prefix_array") + @JsonProperty(value = "prefix_array") @ApiModelProperty(value = "") public List getPrefixArray() { @@ -546,7 +546,7 @@ public XmlItem addPrefixWrappedArrayItem(Integer prefixWrappedArrayItem) { * Get prefixWrappedArray * @return prefixWrappedArray **/ - @JsonProperty("prefix_wrapped_array") + @JsonProperty(value = "prefix_wrapped_array") @ApiModelProperty(value = "") public List getPrefixWrappedArray() { @@ -566,7 +566,7 @@ public XmlItem namespaceString(String namespaceString) { * Get namespaceString * @return namespaceString **/ - @JsonProperty("namespace_string") + @JsonProperty(value = "namespace_string") @ApiModelProperty(example = "string", value = "") public String getNamespaceString() { @@ -586,7 +586,7 @@ public XmlItem namespaceNumber(BigDecimal namespaceNumber) { * Get namespaceNumber * @return namespaceNumber **/ - @JsonProperty("namespace_number") + @JsonProperty(value = "namespace_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getNamespaceNumber() { @@ -606,7 +606,7 @@ public XmlItem namespaceInteger(Integer namespaceInteger) { * Get namespaceInteger * @return namespaceInteger **/ - @JsonProperty("namespace_integer") + @JsonProperty(value = "namespace_integer") @ApiModelProperty(example = "-2", value = "") public Integer getNamespaceInteger() { @@ -626,7 +626,7 @@ public XmlItem namespaceBoolean(Boolean namespaceBoolean) { * Get namespaceBoolean * @return namespaceBoolean **/ - @JsonProperty("namespace_boolean") + @JsonProperty(value = "namespace_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getNamespaceBoolean() { @@ -654,7 +654,7 @@ public XmlItem addNamespaceArrayItem(Integer namespaceArrayItem) { * Get namespaceArray * @return namespaceArray **/ - @JsonProperty("namespace_array") + @JsonProperty(value = "namespace_array") @ApiModelProperty(value = "") public List getNamespaceArray() { @@ -682,7 +682,7 @@ public XmlItem addNamespaceWrappedArrayItem(Integer namespaceWrappedArrayItem) { * Get namespaceWrappedArray * @return namespaceWrappedArray **/ - @JsonProperty("namespace_wrapped_array") + @JsonProperty(value = "namespace_wrapped_array") @ApiModelProperty(value = "") public List getNamespaceWrappedArray() { @@ -702,7 +702,7 @@ public XmlItem prefixNsString(String prefixNsString) { * Get prefixNsString * @return prefixNsString **/ - @JsonProperty("prefix_ns_string") + @JsonProperty(value = "prefix_ns_string") @ApiModelProperty(example = "string", value = "") public String getPrefixNsString() { @@ -722,7 +722,7 @@ public XmlItem prefixNsNumber(BigDecimal prefixNsNumber) { * Get prefixNsNumber * @return prefixNsNumber **/ - @JsonProperty("prefix_ns_number") + @JsonProperty(value = "prefix_ns_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getPrefixNsNumber() { @@ -742,7 +742,7 @@ public XmlItem prefixNsInteger(Integer prefixNsInteger) { * Get prefixNsInteger * @return prefixNsInteger **/ - @JsonProperty("prefix_ns_integer") + @JsonProperty(value = "prefix_ns_integer") @ApiModelProperty(example = "-2", value = "") public Integer getPrefixNsInteger() { @@ -762,7 +762,7 @@ public XmlItem prefixNsBoolean(Boolean prefixNsBoolean) { * Get prefixNsBoolean * @return prefixNsBoolean **/ - @JsonProperty("prefix_ns_boolean") + @JsonProperty(value = "prefix_ns_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getPrefixNsBoolean() { @@ -790,7 +790,7 @@ public XmlItem addPrefixNsArrayItem(Integer prefixNsArrayItem) { * Get prefixNsArray * @return prefixNsArray **/ - @JsonProperty("prefix_ns_array") + @JsonProperty(value = "prefix_ns_array") @ApiModelProperty(value = "") public List getPrefixNsArray() { @@ -818,7 +818,7 @@ public XmlItem addPrefixNsWrappedArrayItem(Integer prefixNsWrappedArrayItem) { * Get prefixNsWrappedArray * @return prefixNsWrappedArray **/ - @JsonProperty("prefix_ns_wrapped_array") + @JsonProperty(value = "prefix_ns_wrapped_array") @ApiModelProperty(value = "") public List getPrefixNsWrappedArray() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/.openapi-generator/VERSION b/samples/server/petstore/jaxrs/jersey2-useTags/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs/jersey2-useTags/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java index 94ab4ee99b59..b69405239b38 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java @@ -45,7 +45,7 @@ public AdditionalPropertiesAnyType name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java index 8a7cbbfa5e79..f90d93c37aec 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java @@ -46,7 +46,7 @@ public AdditionalPropertiesArray name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java index 8e5e3a7ec7cc..473358d6cda0 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java @@ -45,7 +45,7 @@ public AdditionalPropertiesBoolean name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index df959efecfe6..bf846cfb6bf7 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -105,7 +105,7 @@ public AdditionalPropertiesClass putMapStringItem(String key, String mapStringIt * Get mapString * @return mapString **/ - @JsonProperty("map_string") + @JsonProperty(value = "map_string") @ApiModelProperty(value = "") public Map getMapString() { @@ -133,7 +133,7 @@ public AdditionalPropertiesClass putMapNumberItem(String key, BigDecimal mapNumb * Get mapNumber * @return mapNumber **/ - @JsonProperty("map_number") + @JsonProperty(value = "map_number") @ApiModelProperty(value = "") @Valid public Map getMapNumber() { @@ -161,7 +161,7 @@ public AdditionalPropertiesClass putMapIntegerItem(String key, Integer mapIntege * Get mapInteger * @return mapInteger **/ - @JsonProperty("map_integer") + @JsonProperty(value = "map_integer") @ApiModelProperty(value = "") public Map getMapInteger() { @@ -189,7 +189,7 @@ public AdditionalPropertiesClass putMapBooleanItem(String key, Boolean mapBoolea * Get mapBoolean * @return mapBoolean **/ - @JsonProperty("map_boolean") + @JsonProperty(value = "map_boolean") @ApiModelProperty(value = "") public Map getMapBoolean() { @@ -217,7 +217,7 @@ public AdditionalPropertiesClass putMapArrayIntegerItem(String key, List> getMapArrayInteger() { @@ -245,7 +245,7 @@ public AdditionalPropertiesClass putMapArrayAnytypeItem(String key, List * Get mapArrayAnytype * @return mapArrayAnytype **/ - @JsonProperty("map_array_anytype") + @JsonProperty(value = "map_array_anytype") @ApiModelProperty(value = "") @Valid public Map> getMapArrayAnytype() { @@ -273,7 +273,7 @@ public AdditionalPropertiesClass putMapMapStringItem(String key, Map> getMapMapString() { @@ -301,7 +301,7 @@ public AdditionalPropertiesClass putMapMapAnytypeItem(String key, Map> getMapMapAnytype() { @@ -321,7 +321,7 @@ public AdditionalPropertiesClass anytype1(Object anytype1) { * Get anytype1 * @return anytype1 **/ - @JsonProperty("anytype_1") + @JsonProperty(value = "anytype_1") @ApiModelProperty(value = "") public Object getAnytype1() { @@ -341,7 +341,7 @@ public AdditionalPropertiesClass anytype2(Object anytype2) { * Get anytype2 * @return anytype2 **/ - @JsonProperty("anytype_2") + @JsonProperty(value = "anytype_2") @ApiModelProperty(value = "") public Object getAnytype2() { @@ -361,7 +361,7 @@ public AdditionalPropertiesClass anytype3(Object anytype3) { * Get anytype3 * @return anytype3 **/ - @JsonProperty("anytype_3") + @JsonProperty(value = "anytype_3") @ApiModelProperty(value = "") public Object getAnytype3() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java index ac5f7501b3a8..29bd12be784b 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java @@ -45,7 +45,7 @@ public AdditionalPropertiesInteger name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java index d3072f447dca..f05484cd7cc7 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java @@ -46,7 +46,7 @@ public AdditionalPropertiesNumber name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java index 8f8b575df2a2..fb246cac6598 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java @@ -45,7 +45,7 @@ public AdditionalPropertiesObject name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java index c5d4ac7f7c1b..b7018e370e50 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java @@ -45,7 +45,7 @@ public AdditionalPropertiesString name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Animal.java index db142b932d90..97cdd70ab0a1 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Animal.java @@ -56,7 +56,7 @@ public Animal className(String className) { * Get className * @return className **/ - @JsonProperty("className") + @JsonProperty(value = "className") @ApiModelProperty(required = true, value = "") @NotNull public String getClassName() { @@ -76,7 +76,7 @@ public Animal color(String color) { * Get color * @return color **/ - @JsonProperty("color") + @JsonProperty(value = "color") @ApiModelProperty(value = "") public String getColor() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index cd6a16edb265..d277c77993f3 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -54,7 +54,7 @@ public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayAr * Get arrayArrayNumber * @return arrayArrayNumber **/ - @JsonProperty("ArrayArrayNumber") + @JsonProperty(value = "ArrayArrayNumber") @ApiModelProperty(value = "") @Valid public List> getArrayArrayNumber() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index 71d88cd5d890..f8b08e16723e 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -54,7 +54,7 @@ public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { * Get arrayNumber * @return arrayNumber **/ - @JsonProperty("ArrayNumber") + @JsonProperty(value = "ArrayNumber") @ApiModelProperty(value = "") @Valid public List getArrayNumber() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayTest.java index 738fa858e7e7..dfeb88958dca 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayTest.java @@ -64,7 +64,7 @@ public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { * Get arrayOfString * @return arrayOfString **/ - @JsonProperty("array_of_string") + @JsonProperty(value = "array_of_string") @ApiModelProperty(value = "") public List getArrayOfString() { @@ -92,7 +92,7 @@ public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) * Get arrayArrayOfInteger * @return arrayArrayOfInteger **/ - @JsonProperty("array_array_of_integer") + @JsonProperty(value = "array_array_of_integer") @ApiModelProperty(value = "") @Valid public List> getArrayArrayOfInteger() { @@ -120,7 +120,7 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI * Get arrayArrayOfModel * @return arrayArrayOfModel **/ - @JsonProperty("array_array_of_model") + @JsonProperty(value = "array_array_of_model") @ApiModelProperty(value = "") @Valid public List> getArrayArrayOfModel() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/BigCat.java index 0af195ad0a72..867f51230021 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/BigCat.java @@ -81,7 +81,7 @@ public BigCat kind(KindEnum kind) { * Get kind * @return kind **/ - @JsonProperty("kind") + @JsonProperty(value = "kind") @ApiModelProperty(value = "") public KindEnum getKind() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/BigCatAllOf.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/BigCatAllOf.java index eaf4e4f49f5e..ae1220fcefd1 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/BigCatAllOf.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/BigCatAllOf.java @@ -79,7 +79,7 @@ public BigCatAllOf kind(KindEnum kind) { * Get kind * @return kind **/ - @JsonProperty("kind") + @JsonProperty(value = "kind") @ApiModelProperty(value = "") public KindEnum getKind() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Capitalization.java index 9b99fe2b58b3..650d2c7b790b 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Capitalization.java @@ -68,7 +68,7 @@ public Capitalization smallCamel(String smallCamel) { * Get smallCamel * @return smallCamel **/ - @JsonProperty("smallCamel") + @JsonProperty(value = "smallCamel") @ApiModelProperty(value = "") public String getSmallCamel() { @@ -88,7 +88,7 @@ public Capitalization capitalCamel(String capitalCamel) { * Get capitalCamel * @return capitalCamel **/ - @JsonProperty("CapitalCamel") + @JsonProperty(value = "CapitalCamel") @ApiModelProperty(value = "") public String getCapitalCamel() { @@ -108,7 +108,7 @@ public Capitalization smallSnake(String smallSnake) { * Get smallSnake * @return smallSnake **/ - @JsonProperty("small_Snake") + @JsonProperty(value = "small_Snake") @ApiModelProperty(value = "") public String getSmallSnake() { @@ -128,7 +128,7 @@ public Capitalization capitalSnake(String capitalSnake) { * Get capitalSnake * @return capitalSnake **/ - @JsonProperty("Capital_Snake") + @JsonProperty(value = "Capital_Snake") @ApiModelProperty(value = "") public String getCapitalSnake() { @@ -148,7 +148,7 @@ public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { * Get scAETHFlowPoints * @return scAETHFlowPoints **/ - @JsonProperty("SCA_ETH_Flow_Points") + @JsonProperty(value = "SCA_ETH_Flow_Points") @ApiModelProperty(value = "") public String getScAETHFlowPoints() { @@ -168,7 +168,7 @@ public Capitalization ATT_NAME(String ATT_NAME) { * Name of the pet * @return ATT_NAME **/ - @JsonProperty("ATT_NAME") + @JsonProperty(value = "ATT_NAME") @ApiModelProperty(value = "Name of the pet ") public String getATTNAME() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Cat.java index a393506d3aa5..ef4f615bfe76 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Cat.java @@ -45,7 +45,7 @@ public Cat declawed(Boolean declawed) { * Get declawed * @return declawed **/ - @JsonProperty("declawed") + @JsonProperty(value = "declawed") @ApiModelProperty(value = "") public Boolean getDeclawed() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/CatAllOf.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/CatAllOf.java index 7e2a72595950..83503a712d2b 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/CatAllOf.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/CatAllOf.java @@ -43,7 +43,7 @@ public CatAllOf declawed(Boolean declawed) { * Get declawed * @return declawed **/ - @JsonProperty("declawed") + @JsonProperty(value = "declawed") @ApiModelProperty(value = "") public Boolean getDeclawed() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Category.java index d7a5c2b2fafa..af6055dba4ea 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Category.java @@ -48,7 +48,7 @@ public Category id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -68,7 +68,7 @@ public Category name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(required = true, value = "") @NotNull public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ClassModel.java index 00352ed5bce9..ccfe8e27684e 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ClassModel.java @@ -44,7 +44,7 @@ public ClassModel propertyClass(String propertyClass) { * Get propertyClass * @return propertyClass **/ - @JsonProperty("_class") + @JsonProperty(value = "_class") @ApiModelProperty(value = "") public String getPropertyClass() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Client.java index 04b28287ed41..0c87d7030a57 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Client.java @@ -43,7 +43,7 @@ public Client client(String client) { * Get client * @return client **/ - @JsonProperty("client") + @JsonProperty(value = "client") @ApiModelProperty(value = "") public String getClient() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Dog.java index 7d6059b2fc1f..e126444fd61e 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Dog.java @@ -45,7 +45,7 @@ public Dog breed(String breed) { * Get breed * @return breed **/ - @JsonProperty("breed") + @JsonProperty(value = "breed") @ApiModelProperty(value = "") public String getBreed() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/DogAllOf.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/DogAllOf.java index 9fcfbfb92cfc..6902a980c243 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/DogAllOf.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/DogAllOf.java @@ -43,7 +43,7 @@ public DogAllOf breed(String breed) { * Get breed * @return breed **/ - @JsonProperty("breed") + @JsonProperty(value = "breed") @ApiModelProperty(value = "") public String getBreed() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/EnumArrays.java index 526f387372ca..08e6db1ffc92 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/EnumArrays.java @@ -113,7 +113,7 @@ public EnumArrays justSymbol(JustSymbolEnum justSymbol) { * Get justSymbol * @return justSymbol **/ - @JsonProperty("just_symbol") + @JsonProperty(value = "just_symbol") @ApiModelProperty(value = "") public JustSymbolEnum getJustSymbol() { @@ -141,7 +141,7 @@ public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { * Get arrayEnum * @return arrayEnum **/ - @JsonProperty("array_enum") + @JsonProperty(value = "array_enum") @ApiModelProperty(value = "") public List getArrayEnum() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/EnumTest.java index ee08eadfa8d7..937a9f7f6aeb 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/EnumTest.java @@ -193,7 +193,7 @@ public EnumTest enumString(EnumStringEnum enumString) { * Get enumString * @return enumString **/ - @JsonProperty("enum_string") + @JsonProperty(value = "enum_string") @ApiModelProperty(value = "") public EnumStringEnum getEnumString() { @@ -213,7 +213,7 @@ public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { * Get enumStringRequired * @return enumStringRequired **/ - @JsonProperty("enum_string_required") + @JsonProperty(value = "enum_string_required") @ApiModelProperty(required = true, value = "") @NotNull public EnumStringRequiredEnum getEnumStringRequired() { @@ -233,7 +233,7 @@ public EnumTest enumInteger(EnumIntegerEnum enumInteger) { * Get enumInteger * @return enumInteger **/ - @JsonProperty("enum_integer") + @JsonProperty(value = "enum_integer") @ApiModelProperty(value = "") public EnumIntegerEnum getEnumInteger() { @@ -253,7 +253,7 @@ public EnumTest enumNumber(EnumNumberEnum enumNumber) { * Get enumNumber * @return enumNumber **/ - @JsonProperty("enum_number") + @JsonProperty(value = "enum_number") @ApiModelProperty(value = "") public EnumNumberEnum getEnumNumber() { @@ -273,7 +273,7 @@ public EnumTest outerEnum(OuterEnum outerEnum) { * Get outerEnum * @return outerEnum **/ - @JsonProperty("outerEnum") + @JsonProperty(value = "outerEnum") @ApiModelProperty(value = "") @Valid public OuterEnum getOuterEnum() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 4be816893906..fb40a511e446 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -50,7 +50,7 @@ public FileSchemaTestClass file(java.io.File file) { * Get file * @return file **/ - @JsonProperty("file") + @JsonProperty(value = "file") @ApiModelProperty(value = "") @Valid public java.io.File getFile() { @@ -78,7 +78,7 @@ public FileSchemaTestClass addFilesItem(java.io.File filesItem) { * Get files * @return files **/ - @JsonProperty("files") + @JsonProperty(value = "files") @ApiModelProperty(value = "") @Valid public List getFiles() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/FormatTest.java index 9817e78712a7..d640a11342c7 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/FormatTest.java @@ -114,7 +114,7 @@ public FormatTest integer(Integer integer) { * maximum: 100 * @return integer **/ - @JsonProperty("integer") + @JsonProperty(value = "integer") @ApiModelProperty(value = "") @Min(10) @Max(100) public Integer getInteger() { @@ -136,7 +136,7 @@ public FormatTest int32(Integer int32) { * maximum: 200 * @return int32 **/ - @JsonProperty("int32") + @JsonProperty(value = "int32") @ApiModelProperty(value = "") @Min(20) @Max(200) public Integer getInt32() { @@ -156,7 +156,7 @@ public FormatTest int64(Long int64) { * Get int64 * @return int64 **/ - @JsonProperty("int64") + @JsonProperty(value = "int64") @ApiModelProperty(value = "") public Long getInt64() { @@ -178,7 +178,7 @@ public FormatTest number(BigDecimal number) { * maximum: 543.2 * @return number **/ - @JsonProperty("number") + @JsonProperty(value = "number") @ApiModelProperty(required = true, value = "") @NotNull @Valid @DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { @@ -200,7 +200,7 @@ public FormatTest _float(Float _float) { * maximum: 987.6 * @return _float **/ - @JsonProperty("float") + @JsonProperty(value = "float") @ApiModelProperty(value = "") @DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { @@ -222,7 +222,7 @@ public FormatTest _double(Double _double) { * maximum: 123.4 * @return _double **/ - @JsonProperty("double") + @JsonProperty(value = "double") @ApiModelProperty(value = "") @DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { @@ -242,7 +242,7 @@ public FormatTest string(String string) { * Get string * @return string **/ - @JsonProperty("string") + @JsonProperty(value = "string") @ApiModelProperty(value = "") @Pattern(regexp="/[a-z]/i") public String getString() { @@ -262,7 +262,7 @@ public FormatTest _byte(byte[] _byte) { * Get _byte * @return _byte **/ - @JsonProperty("byte") + @JsonProperty(value = "byte") @ApiModelProperty(required = true, value = "") @NotNull public byte[] getByte() { @@ -282,7 +282,7 @@ public FormatTest binary(File binary) { * Get binary * @return binary **/ - @JsonProperty("binary") + @JsonProperty(value = "binary") @ApiModelProperty(value = "") public File getBinary() { @@ -302,7 +302,7 @@ public FormatTest date(Date date) { * Get date * @return date **/ - @JsonProperty("date") + @JsonProperty(value = "date") @ApiModelProperty(required = true, value = "") @NotNull public Date getDate() { @@ -322,7 +322,7 @@ public FormatTest dateTime(Date dateTime) { * Get dateTime * @return dateTime **/ - @JsonProperty("dateTime") + @JsonProperty(value = "dateTime") @ApiModelProperty(value = "") public Date getDateTime() { @@ -342,7 +342,7 @@ public FormatTest uuid(UUID uuid) { * Get uuid * @return uuid **/ - @JsonProperty("uuid") + @JsonProperty(value = "uuid") @ApiModelProperty(example = "72f98069-206d-4f12-9f12-3d1e525a8e84", value = "") public UUID getUuid() { @@ -362,7 +362,7 @@ public FormatTest password(String password) { * Get password * @return password **/ - @JsonProperty("password") + @JsonProperty(value = "password") @ApiModelProperty(required = true, value = "") @NotNull @Size(min=10,max=64) public String getPassword() { @@ -382,7 +382,7 @@ public FormatTest bigDecimal(BigDecimal bigDecimal) { * Get bigDecimal * @return bigDecimal **/ - @JsonProperty("BigDecimal") + @JsonProperty(value = "BigDecimal") @ApiModelProperty(value = "") @Valid public BigDecimal getBigDecimal() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index 4f72442fd947..1b5042f61f59 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -48,7 +48,7 @@ public HasOnlyReadOnly bar(String bar) { * Get bar * @return bar **/ - @JsonProperty("bar") + @JsonProperty(value = "bar", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getBar() { @@ -68,7 +68,7 @@ public HasOnlyReadOnly foo(String foo) { * Get foo * @return foo **/ - @JsonProperty("foo") + @JsonProperty(value = "foo", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getFoo() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/MapTest.java index 4db676efea2d..12516e0afba2 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/MapTest.java @@ -101,7 +101,7 @@ public MapTest putMapMapOfStringItem(String key, Map mapMapOfStr * Get mapMapOfString * @return mapMapOfString **/ - @JsonProperty("map_map_of_string") + @JsonProperty(value = "map_map_of_string") @ApiModelProperty(value = "") @Valid public Map> getMapMapOfString() { @@ -129,7 +129,7 @@ public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) * Get mapOfEnumString * @return mapOfEnumString **/ - @JsonProperty("map_of_enum_string") + @JsonProperty(value = "map_of_enum_string") @ApiModelProperty(value = "") public Map getMapOfEnumString() { @@ -157,7 +157,7 @@ public MapTest putDirectMapItem(String key, Boolean directMapItem) { * Get directMap * @return directMap **/ - @JsonProperty("direct_map") + @JsonProperty(value = "direct_map") @ApiModelProperty(value = "") public Map getDirectMap() { @@ -185,7 +185,7 @@ public MapTest putIndirectMapItem(String key, Boolean indirectMapItem) { * Get indirectMap * @return indirectMap **/ - @JsonProperty("indirect_map") + @JsonProperty(value = "indirect_map") @ApiModelProperty(value = "") public Map getIndirectMap() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index 0ba358c6b5c2..eb4fcd577811 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -59,7 +59,7 @@ public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { * Get uuid * @return uuid **/ - @JsonProperty("uuid") + @JsonProperty(value = "uuid") @ApiModelProperty(value = "") public UUID getUuid() { @@ -79,7 +79,7 @@ public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { * Get dateTime * @return dateTime **/ - @JsonProperty("dateTime") + @JsonProperty(value = "dateTime") @ApiModelProperty(value = "") public Date getDateTime() { @@ -107,7 +107,7 @@ public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal * Get map * @return map **/ - @JsonProperty("map") + @JsonProperty(value = "map") @ApiModelProperty(value = "") @Valid public Map getMap() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Model200Response.java index 2df0caa9725d..1a3e698983e5 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Model200Response.java @@ -49,7 +49,7 @@ public Model200Response name(Integer name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public Integer getName() { @@ -69,7 +69,7 @@ public Model200Response propertyClass(String propertyClass) { * Get propertyClass * @return propertyClass **/ - @JsonProperty("class") + @JsonProperty(value = "class") @ApiModelProperty(value = "") public String getPropertyClass() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelApiResponse.java index b0d01665ef6a..1552245d1dc8 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -53,7 +53,7 @@ public ModelApiResponse code(Integer code) { * Get code * @return code **/ - @JsonProperty("code") + @JsonProperty(value = "code") @ApiModelProperty(value = "") public Integer getCode() { @@ -73,7 +73,7 @@ public ModelApiResponse type(String type) { * Get type * @return type **/ - @JsonProperty("type") + @JsonProperty(value = "type") @ApiModelProperty(value = "") public String getType() { @@ -93,7 +93,7 @@ public ModelApiResponse message(String message) { * Get message * @return message **/ - @JsonProperty("message") + @JsonProperty(value = "message") @ApiModelProperty(value = "") public String getMessage() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelReturn.java index 41a1c059f7ef..c9f4504d3f0e 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelReturn.java @@ -44,7 +44,7 @@ public ModelReturn _return(Integer _return) { * Get _return * @return _return **/ - @JsonProperty("return") + @JsonProperty(value = "return") @ApiModelProperty(value = "") public Integer getReturn() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Name.java index a7a189571897..cdcef856cd21 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Name.java @@ -59,7 +59,7 @@ public Name name(Integer name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(required = true, value = "") @NotNull public Integer getName() { @@ -79,7 +79,7 @@ public Name snakeCase(Integer snakeCase) { * Get snakeCase * @return snakeCase **/ - @JsonProperty("snake_case") + @JsonProperty(value = "snake_case", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public Integer getSnakeCase() { @@ -99,7 +99,7 @@ public Name property(String property) { * Get property * @return property **/ - @JsonProperty("property") + @JsonProperty(value = "property") @ApiModelProperty(value = "") public String getProperty() { @@ -119,7 +119,7 @@ public Name _123number(Integer _123number) { * Get _123number * @return _123number **/ - @JsonProperty("123Number") + @JsonProperty(value = "123Number", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public Integer get123number() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/NumberOnly.java index 188899dc4460..3ec25c75ae59 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/NumberOnly.java @@ -44,7 +44,7 @@ public NumberOnly justNumber(BigDecimal justNumber) { * Get justNumber * @return justNumber **/ - @JsonProperty("JustNumber") + @JsonProperty(value = "JustNumber") @ApiModelProperty(value = "") @Valid public BigDecimal getJustNumber() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Order.java index 7ce0000199f9..b97b051ebc80 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Order.java @@ -103,7 +103,7 @@ public Order id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -123,7 +123,7 @@ public Order petId(Long petId) { * Get petId * @return petId **/ - @JsonProperty("petId") + @JsonProperty(value = "petId") @ApiModelProperty(value = "") public Long getPetId() { @@ -143,7 +143,7 @@ public Order quantity(Integer quantity) { * Get quantity * @return quantity **/ - @JsonProperty("quantity") + @JsonProperty(value = "quantity") @ApiModelProperty(value = "") public Integer getQuantity() { @@ -163,7 +163,7 @@ public Order shipDate(Date shipDate) { * Get shipDate * @return shipDate **/ - @JsonProperty("shipDate") + @JsonProperty(value = "shipDate") @ApiModelProperty(value = "") public Date getShipDate() { @@ -183,7 +183,7 @@ public Order status(StatusEnum status) { * Order Status * @return status **/ - @JsonProperty("status") + @JsonProperty(value = "status") @ApiModelProperty(value = "Order Status") public StatusEnum getStatus() { @@ -203,7 +203,7 @@ public Order complete(Boolean complete) { * Get complete * @return complete **/ - @JsonProperty("complete") + @JsonProperty(value = "complete") @ApiModelProperty(value = "") public Boolean getComplete() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/OuterComposite.java index 43b69002d036..577504e1bef2 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/OuterComposite.java @@ -54,7 +54,7 @@ public OuterComposite myNumber(BigDecimal myNumber) { * Get myNumber * @return myNumber **/ - @JsonProperty("my_number") + @JsonProperty(value = "my_number") @ApiModelProperty(value = "") @Valid public BigDecimal getMyNumber() { @@ -74,7 +74,7 @@ public OuterComposite myString(String myString) { * Get myString * @return myString **/ - @JsonProperty("my_string") + @JsonProperty(value = "my_string") @ApiModelProperty(value = "") public String getMyString() { @@ -94,7 +94,7 @@ public OuterComposite myBoolean(Boolean myBoolean) { * Get myBoolean * @return myBoolean **/ - @JsonProperty("my_boolean") + @JsonProperty(value = "my_boolean") @ApiModelProperty(value = "") public Boolean getMyBoolean() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Pet.java index adcdbf24a57d..4ed108d787e9 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Pet.java @@ -108,7 +108,7 @@ public Pet id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -128,7 +128,7 @@ public Pet category(Category category) { * Get category * @return category **/ - @JsonProperty("category") + @JsonProperty(value = "category") @ApiModelProperty(value = "") @Valid public Category getCategory() { @@ -148,7 +148,7 @@ public Pet name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(example = "doggie", required = true, value = "") @NotNull public String getName() { @@ -173,7 +173,7 @@ public Pet addPhotoUrlsItem(String photoUrlsItem) { * Get photoUrls * @return photoUrls **/ - @JsonProperty("photoUrls") + @JsonProperty(value = "photoUrls") @ApiModelProperty(required = true, value = "") @NotNull public Set getPhotoUrls() { @@ -201,7 +201,7 @@ public Pet addTagsItem(Tag tagsItem) { * Get tags * @return tags **/ - @JsonProperty("tags") + @JsonProperty(value = "tags") @ApiModelProperty(value = "") @Valid public List getTags() { @@ -221,7 +221,7 @@ public Pet status(StatusEnum status) { * pet status in the store * @return status **/ - @JsonProperty("status") + @JsonProperty(value = "status") @ApiModelProperty(value = "pet status in the store") public StatusEnum getStatus() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index e2e5ea910e68..05c01064ff67 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -48,7 +48,7 @@ public ReadOnlyFirst bar(String bar) { * Get bar * @return bar **/ - @JsonProperty("bar") + @JsonProperty(value = "bar", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getBar() { @@ -68,7 +68,7 @@ public ReadOnlyFirst baz(String baz) { * Get baz * @return baz **/ - @JsonProperty("baz") + @JsonProperty(value = "baz") @ApiModelProperty(value = "") public String getBaz() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/SpecialModelName.java index 48ed44ecf621..1fbc58e301e6 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -43,7 +43,7 @@ public class SpecialModelName { * Get $specialPropertyName * @return $specialPropertyName **/ - @JsonProperty("$special[property.name]") + @JsonProperty(value = "$special[property.name]") @ApiModelProperty(value = "") public Long get$SpecialPropertyName() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Tag.java index 80d098d57c16..5ac82ca92382 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Tag.java @@ -48,7 +48,7 @@ public Tag id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -68,7 +68,7 @@ public Tag name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/TypeHolderDefault.java index 52830413a08c..a8450d0e61d5 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/TypeHolderDefault.java @@ -66,7 +66,7 @@ public TypeHolderDefault stringItem(String stringItem) { * Get stringItem * @return stringItem **/ - @JsonProperty("string_item") + @JsonProperty(value = "string_item") @ApiModelProperty(required = true, value = "") @NotNull public String getStringItem() { @@ -86,7 +86,7 @@ public TypeHolderDefault numberItem(BigDecimal numberItem) { * Get numberItem * @return numberItem **/ - @JsonProperty("number_item") + @JsonProperty(value = "number_item") @ApiModelProperty(required = true, value = "") @NotNull @Valid public BigDecimal getNumberItem() { @@ -106,7 +106,7 @@ public TypeHolderDefault integerItem(Integer integerItem) { * Get integerItem * @return integerItem **/ - @JsonProperty("integer_item") + @JsonProperty(value = "integer_item") @ApiModelProperty(required = true, value = "") @NotNull public Integer getIntegerItem() { @@ -126,7 +126,7 @@ public TypeHolderDefault boolItem(Boolean boolItem) { * Get boolItem * @return boolItem **/ - @JsonProperty("bool_item") + @JsonProperty(value = "bool_item") @ApiModelProperty(required = true, value = "") @NotNull public Boolean getBoolItem() { @@ -151,7 +151,7 @@ public TypeHolderDefault addArrayItemItem(Integer arrayItemItem) { * Get arrayItem * @return arrayItem **/ - @JsonProperty("array_item") + @JsonProperty(value = "array_item") @ApiModelProperty(required = true, value = "") @NotNull public List getArrayItem() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/TypeHolderExample.java index 8e57cc93cef4..026943cb64e3 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/TypeHolderExample.java @@ -71,7 +71,7 @@ public TypeHolderExample stringItem(String stringItem) { * Get stringItem * @return stringItem **/ - @JsonProperty("string_item") + @JsonProperty(value = "string_item") @ApiModelProperty(example = "what", required = true, value = "") @NotNull public String getStringItem() { @@ -91,7 +91,7 @@ public TypeHolderExample numberItem(BigDecimal numberItem) { * Get numberItem * @return numberItem **/ - @JsonProperty("number_item") + @JsonProperty(value = "number_item") @ApiModelProperty(example = "1.234", required = true, value = "") @NotNull @Valid public BigDecimal getNumberItem() { @@ -111,7 +111,7 @@ public TypeHolderExample floatItem(Float floatItem) { * Get floatItem * @return floatItem **/ - @JsonProperty("float_item") + @JsonProperty(value = "float_item") @ApiModelProperty(example = "1.234", required = true, value = "") @NotNull public Float getFloatItem() { @@ -131,7 +131,7 @@ public TypeHolderExample integerItem(Integer integerItem) { * Get integerItem * @return integerItem **/ - @JsonProperty("integer_item") + @JsonProperty(value = "integer_item") @ApiModelProperty(example = "-2", required = true, value = "") @NotNull public Integer getIntegerItem() { @@ -151,7 +151,7 @@ public TypeHolderExample boolItem(Boolean boolItem) { * Get boolItem * @return boolItem **/ - @JsonProperty("bool_item") + @JsonProperty(value = "bool_item") @ApiModelProperty(example = "true", required = true, value = "") @NotNull public Boolean getBoolItem() { @@ -176,7 +176,7 @@ public TypeHolderExample addArrayItemItem(Integer arrayItemItem) { * Get arrayItem * @return arrayItem **/ - @JsonProperty("array_item") + @JsonProperty(value = "array_item") @ApiModelProperty(example = "[0, 1, 2, 3]", required = true, value = "") @NotNull public List getArrayItem() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/User.java index 1e702dd070d5..37ab5453c3d2 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/User.java @@ -78,7 +78,7 @@ public User id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -98,7 +98,7 @@ public User username(String username) { * Get username * @return username **/ - @JsonProperty("username") + @JsonProperty(value = "username") @ApiModelProperty(value = "") public String getUsername() { @@ -118,7 +118,7 @@ public User firstName(String firstName) { * Get firstName * @return firstName **/ - @JsonProperty("firstName") + @JsonProperty(value = "firstName") @ApiModelProperty(value = "") public String getFirstName() { @@ -138,7 +138,7 @@ public User lastName(String lastName) { * Get lastName * @return lastName **/ - @JsonProperty("lastName") + @JsonProperty(value = "lastName") @ApiModelProperty(value = "") public String getLastName() { @@ -158,7 +158,7 @@ public User email(String email) { * Get email * @return email **/ - @JsonProperty("email") + @JsonProperty(value = "email") @ApiModelProperty(value = "") public String getEmail() { @@ -178,7 +178,7 @@ public User password(String password) { * Get password * @return password **/ - @JsonProperty("password") + @JsonProperty(value = "password") @ApiModelProperty(value = "") public String getPassword() { @@ -198,7 +198,7 @@ public User phone(String phone) { * Get phone * @return phone **/ - @JsonProperty("phone") + @JsonProperty(value = "phone") @ApiModelProperty(value = "") public String getPhone() { @@ -218,7 +218,7 @@ public User userStatus(Integer userStatus) { * User Status * @return userStatus **/ - @JsonProperty("userStatus") + @JsonProperty(value = "userStatus") @ApiModelProperty(value = "User Status") public Integer getUserStatus() { diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/XmlItem.java index 8c61e3e4cc0e..46c2de9ca268 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/XmlItem.java @@ -186,7 +186,7 @@ public XmlItem attributeString(String attributeString) { * Get attributeString * @return attributeString **/ - @JsonProperty("attribute_string") + @JsonProperty(value = "attribute_string") @ApiModelProperty(example = "string", value = "") public String getAttributeString() { @@ -206,7 +206,7 @@ public XmlItem attributeNumber(BigDecimal attributeNumber) { * Get attributeNumber * @return attributeNumber **/ - @JsonProperty("attribute_number") + @JsonProperty(value = "attribute_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getAttributeNumber() { @@ -226,7 +226,7 @@ public XmlItem attributeInteger(Integer attributeInteger) { * Get attributeInteger * @return attributeInteger **/ - @JsonProperty("attribute_integer") + @JsonProperty(value = "attribute_integer") @ApiModelProperty(example = "-2", value = "") public Integer getAttributeInteger() { @@ -246,7 +246,7 @@ public XmlItem attributeBoolean(Boolean attributeBoolean) { * Get attributeBoolean * @return attributeBoolean **/ - @JsonProperty("attribute_boolean") + @JsonProperty(value = "attribute_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getAttributeBoolean() { @@ -274,7 +274,7 @@ public XmlItem addWrappedArrayItem(Integer wrappedArrayItem) { * Get wrappedArray * @return wrappedArray **/ - @JsonProperty("wrapped_array") + @JsonProperty(value = "wrapped_array") @ApiModelProperty(value = "") public List getWrappedArray() { @@ -294,7 +294,7 @@ public XmlItem nameString(String nameString) { * Get nameString * @return nameString **/ - @JsonProperty("name_string") + @JsonProperty(value = "name_string") @ApiModelProperty(example = "string", value = "") public String getNameString() { @@ -314,7 +314,7 @@ public XmlItem nameNumber(BigDecimal nameNumber) { * Get nameNumber * @return nameNumber **/ - @JsonProperty("name_number") + @JsonProperty(value = "name_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getNameNumber() { @@ -334,7 +334,7 @@ public XmlItem nameInteger(Integer nameInteger) { * Get nameInteger * @return nameInteger **/ - @JsonProperty("name_integer") + @JsonProperty(value = "name_integer") @ApiModelProperty(example = "-2", value = "") public Integer getNameInteger() { @@ -354,7 +354,7 @@ public XmlItem nameBoolean(Boolean nameBoolean) { * Get nameBoolean * @return nameBoolean **/ - @JsonProperty("name_boolean") + @JsonProperty(value = "name_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getNameBoolean() { @@ -382,7 +382,7 @@ public XmlItem addNameArrayItem(Integer nameArrayItem) { * Get nameArray * @return nameArray **/ - @JsonProperty("name_array") + @JsonProperty(value = "name_array") @ApiModelProperty(value = "") public List getNameArray() { @@ -410,7 +410,7 @@ public XmlItem addNameWrappedArrayItem(Integer nameWrappedArrayItem) { * Get nameWrappedArray * @return nameWrappedArray **/ - @JsonProperty("name_wrapped_array") + @JsonProperty(value = "name_wrapped_array") @ApiModelProperty(value = "") public List getNameWrappedArray() { @@ -430,7 +430,7 @@ public XmlItem prefixString(String prefixString) { * Get prefixString * @return prefixString **/ - @JsonProperty("prefix_string") + @JsonProperty(value = "prefix_string") @ApiModelProperty(example = "string", value = "") public String getPrefixString() { @@ -450,7 +450,7 @@ public XmlItem prefixNumber(BigDecimal prefixNumber) { * Get prefixNumber * @return prefixNumber **/ - @JsonProperty("prefix_number") + @JsonProperty(value = "prefix_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getPrefixNumber() { @@ -470,7 +470,7 @@ public XmlItem prefixInteger(Integer prefixInteger) { * Get prefixInteger * @return prefixInteger **/ - @JsonProperty("prefix_integer") + @JsonProperty(value = "prefix_integer") @ApiModelProperty(example = "-2", value = "") public Integer getPrefixInteger() { @@ -490,7 +490,7 @@ public XmlItem prefixBoolean(Boolean prefixBoolean) { * Get prefixBoolean * @return prefixBoolean **/ - @JsonProperty("prefix_boolean") + @JsonProperty(value = "prefix_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getPrefixBoolean() { @@ -518,7 +518,7 @@ public XmlItem addPrefixArrayItem(Integer prefixArrayItem) { * Get prefixArray * @return prefixArray **/ - @JsonProperty("prefix_array") + @JsonProperty(value = "prefix_array") @ApiModelProperty(value = "") public List getPrefixArray() { @@ -546,7 +546,7 @@ public XmlItem addPrefixWrappedArrayItem(Integer prefixWrappedArrayItem) { * Get prefixWrappedArray * @return prefixWrappedArray **/ - @JsonProperty("prefix_wrapped_array") + @JsonProperty(value = "prefix_wrapped_array") @ApiModelProperty(value = "") public List getPrefixWrappedArray() { @@ -566,7 +566,7 @@ public XmlItem namespaceString(String namespaceString) { * Get namespaceString * @return namespaceString **/ - @JsonProperty("namespace_string") + @JsonProperty(value = "namespace_string") @ApiModelProperty(example = "string", value = "") public String getNamespaceString() { @@ -586,7 +586,7 @@ public XmlItem namespaceNumber(BigDecimal namespaceNumber) { * Get namespaceNumber * @return namespaceNumber **/ - @JsonProperty("namespace_number") + @JsonProperty(value = "namespace_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getNamespaceNumber() { @@ -606,7 +606,7 @@ public XmlItem namespaceInteger(Integer namespaceInteger) { * Get namespaceInteger * @return namespaceInteger **/ - @JsonProperty("namespace_integer") + @JsonProperty(value = "namespace_integer") @ApiModelProperty(example = "-2", value = "") public Integer getNamespaceInteger() { @@ -626,7 +626,7 @@ public XmlItem namespaceBoolean(Boolean namespaceBoolean) { * Get namespaceBoolean * @return namespaceBoolean **/ - @JsonProperty("namespace_boolean") + @JsonProperty(value = "namespace_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getNamespaceBoolean() { @@ -654,7 +654,7 @@ public XmlItem addNamespaceArrayItem(Integer namespaceArrayItem) { * Get namespaceArray * @return namespaceArray **/ - @JsonProperty("namespace_array") + @JsonProperty(value = "namespace_array") @ApiModelProperty(value = "") public List getNamespaceArray() { @@ -682,7 +682,7 @@ public XmlItem addNamespaceWrappedArrayItem(Integer namespaceWrappedArrayItem) { * Get namespaceWrappedArray * @return namespaceWrappedArray **/ - @JsonProperty("namespace_wrapped_array") + @JsonProperty(value = "namespace_wrapped_array") @ApiModelProperty(value = "") public List getNamespaceWrappedArray() { @@ -702,7 +702,7 @@ public XmlItem prefixNsString(String prefixNsString) { * Get prefixNsString * @return prefixNsString **/ - @JsonProperty("prefix_ns_string") + @JsonProperty(value = "prefix_ns_string") @ApiModelProperty(example = "string", value = "") public String getPrefixNsString() { @@ -722,7 +722,7 @@ public XmlItem prefixNsNumber(BigDecimal prefixNsNumber) { * Get prefixNsNumber * @return prefixNsNumber **/ - @JsonProperty("prefix_ns_number") + @JsonProperty(value = "prefix_ns_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getPrefixNsNumber() { @@ -742,7 +742,7 @@ public XmlItem prefixNsInteger(Integer prefixNsInteger) { * Get prefixNsInteger * @return prefixNsInteger **/ - @JsonProperty("prefix_ns_integer") + @JsonProperty(value = "prefix_ns_integer") @ApiModelProperty(example = "-2", value = "") public Integer getPrefixNsInteger() { @@ -762,7 +762,7 @@ public XmlItem prefixNsBoolean(Boolean prefixNsBoolean) { * Get prefixNsBoolean * @return prefixNsBoolean **/ - @JsonProperty("prefix_ns_boolean") + @JsonProperty(value = "prefix_ns_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getPrefixNsBoolean() { @@ -790,7 +790,7 @@ public XmlItem addPrefixNsArrayItem(Integer prefixNsArrayItem) { * Get prefixNsArray * @return prefixNsArray **/ - @JsonProperty("prefix_ns_array") + @JsonProperty(value = "prefix_ns_array") @ApiModelProperty(value = "") public List getPrefixNsArray() { @@ -818,7 +818,7 @@ public XmlItem addPrefixNsWrappedArrayItem(Integer prefixNsWrappedArrayItem) { * Get prefixNsWrappedArray * @return prefixNsWrappedArray **/ - @JsonProperty("prefix_ns_wrapped_array") + @JsonProperty(value = "prefix_ns_wrapped_array") @ApiModelProperty(value = "") public List getPrefixNsWrappedArray() { diff --git a/samples/server/petstore/jaxrs/jersey2/.openapi-generator/VERSION b/samples/server/petstore/jaxrs/jersey2/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/jaxrs/jersey2/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs/jersey2/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java index 94ab4ee99b59..b69405239b38 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java @@ -45,7 +45,7 @@ public AdditionalPropertiesAnyType name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java index 8a7cbbfa5e79..f90d93c37aec 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java @@ -46,7 +46,7 @@ public AdditionalPropertiesArray name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java index 8e5e3a7ec7cc..473358d6cda0 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java @@ -45,7 +45,7 @@ public AdditionalPropertiesBoolean name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index df959efecfe6..bf846cfb6bf7 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -105,7 +105,7 @@ public AdditionalPropertiesClass putMapStringItem(String key, String mapStringIt * Get mapString * @return mapString **/ - @JsonProperty("map_string") + @JsonProperty(value = "map_string") @ApiModelProperty(value = "") public Map getMapString() { @@ -133,7 +133,7 @@ public AdditionalPropertiesClass putMapNumberItem(String key, BigDecimal mapNumb * Get mapNumber * @return mapNumber **/ - @JsonProperty("map_number") + @JsonProperty(value = "map_number") @ApiModelProperty(value = "") @Valid public Map getMapNumber() { @@ -161,7 +161,7 @@ public AdditionalPropertiesClass putMapIntegerItem(String key, Integer mapIntege * Get mapInteger * @return mapInteger **/ - @JsonProperty("map_integer") + @JsonProperty(value = "map_integer") @ApiModelProperty(value = "") public Map getMapInteger() { @@ -189,7 +189,7 @@ public AdditionalPropertiesClass putMapBooleanItem(String key, Boolean mapBoolea * Get mapBoolean * @return mapBoolean **/ - @JsonProperty("map_boolean") + @JsonProperty(value = "map_boolean") @ApiModelProperty(value = "") public Map getMapBoolean() { @@ -217,7 +217,7 @@ public AdditionalPropertiesClass putMapArrayIntegerItem(String key, List> getMapArrayInteger() { @@ -245,7 +245,7 @@ public AdditionalPropertiesClass putMapArrayAnytypeItem(String key, List * Get mapArrayAnytype * @return mapArrayAnytype **/ - @JsonProperty("map_array_anytype") + @JsonProperty(value = "map_array_anytype") @ApiModelProperty(value = "") @Valid public Map> getMapArrayAnytype() { @@ -273,7 +273,7 @@ public AdditionalPropertiesClass putMapMapStringItem(String key, Map> getMapMapString() { @@ -301,7 +301,7 @@ public AdditionalPropertiesClass putMapMapAnytypeItem(String key, Map> getMapMapAnytype() { @@ -321,7 +321,7 @@ public AdditionalPropertiesClass anytype1(Object anytype1) { * Get anytype1 * @return anytype1 **/ - @JsonProperty("anytype_1") + @JsonProperty(value = "anytype_1") @ApiModelProperty(value = "") public Object getAnytype1() { @@ -341,7 +341,7 @@ public AdditionalPropertiesClass anytype2(Object anytype2) { * Get anytype2 * @return anytype2 **/ - @JsonProperty("anytype_2") + @JsonProperty(value = "anytype_2") @ApiModelProperty(value = "") public Object getAnytype2() { @@ -361,7 +361,7 @@ public AdditionalPropertiesClass anytype3(Object anytype3) { * Get anytype3 * @return anytype3 **/ - @JsonProperty("anytype_3") + @JsonProperty(value = "anytype_3") @ApiModelProperty(value = "") public Object getAnytype3() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java index ac5f7501b3a8..29bd12be784b 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java @@ -45,7 +45,7 @@ public AdditionalPropertiesInteger name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java index d3072f447dca..f05484cd7cc7 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java @@ -46,7 +46,7 @@ public AdditionalPropertiesNumber name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java index 8f8b575df2a2..fb246cac6598 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java @@ -45,7 +45,7 @@ public AdditionalPropertiesObject name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java index c5d4ac7f7c1b..b7018e370e50 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java @@ -45,7 +45,7 @@ public AdditionalPropertiesString name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Animal.java index db142b932d90..97cdd70ab0a1 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Animal.java @@ -56,7 +56,7 @@ public Animal className(String className) { * Get className * @return className **/ - @JsonProperty("className") + @JsonProperty(value = "className") @ApiModelProperty(required = true, value = "") @NotNull public String getClassName() { @@ -76,7 +76,7 @@ public Animal color(String color) { * Get color * @return color **/ - @JsonProperty("color") + @JsonProperty(value = "color") @ApiModelProperty(value = "") public String getColor() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index cd6a16edb265..d277c77993f3 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -54,7 +54,7 @@ public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayAr * Get arrayArrayNumber * @return arrayArrayNumber **/ - @JsonProperty("ArrayArrayNumber") + @JsonProperty(value = "ArrayArrayNumber") @ApiModelProperty(value = "") @Valid public List> getArrayArrayNumber() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index 71d88cd5d890..f8b08e16723e 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -54,7 +54,7 @@ public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { * Get arrayNumber * @return arrayNumber **/ - @JsonProperty("ArrayNumber") + @JsonProperty(value = "ArrayNumber") @ApiModelProperty(value = "") @Valid public List getArrayNumber() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayTest.java index 738fa858e7e7..dfeb88958dca 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayTest.java @@ -64,7 +64,7 @@ public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { * Get arrayOfString * @return arrayOfString **/ - @JsonProperty("array_of_string") + @JsonProperty(value = "array_of_string") @ApiModelProperty(value = "") public List getArrayOfString() { @@ -92,7 +92,7 @@ public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) * Get arrayArrayOfInteger * @return arrayArrayOfInteger **/ - @JsonProperty("array_array_of_integer") + @JsonProperty(value = "array_array_of_integer") @ApiModelProperty(value = "") @Valid public List> getArrayArrayOfInteger() { @@ -120,7 +120,7 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI * Get arrayArrayOfModel * @return arrayArrayOfModel **/ - @JsonProperty("array_array_of_model") + @JsonProperty(value = "array_array_of_model") @ApiModelProperty(value = "") @Valid public List> getArrayArrayOfModel() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/BigCat.java index 0af195ad0a72..867f51230021 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/BigCat.java @@ -81,7 +81,7 @@ public BigCat kind(KindEnum kind) { * Get kind * @return kind **/ - @JsonProperty("kind") + @JsonProperty(value = "kind") @ApiModelProperty(value = "") public KindEnum getKind() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/BigCatAllOf.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/BigCatAllOf.java index eaf4e4f49f5e..ae1220fcefd1 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/BigCatAllOf.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/BigCatAllOf.java @@ -79,7 +79,7 @@ public BigCatAllOf kind(KindEnum kind) { * Get kind * @return kind **/ - @JsonProperty("kind") + @JsonProperty(value = "kind") @ApiModelProperty(value = "") public KindEnum getKind() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Capitalization.java index 9b99fe2b58b3..650d2c7b790b 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Capitalization.java @@ -68,7 +68,7 @@ public Capitalization smallCamel(String smallCamel) { * Get smallCamel * @return smallCamel **/ - @JsonProperty("smallCamel") + @JsonProperty(value = "smallCamel") @ApiModelProperty(value = "") public String getSmallCamel() { @@ -88,7 +88,7 @@ public Capitalization capitalCamel(String capitalCamel) { * Get capitalCamel * @return capitalCamel **/ - @JsonProperty("CapitalCamel") + @JsonProperty(value = "CapitalCamel") @ApiModelProperty(value = "") public String getCapitalCamel() { @@ -108,7 +108,7 @@ public Capitalization smallSnake(String smallSnake) { * Get smallSnake * @return smallSnake **/ - @JsonProperty("small_Snake") + @JsonProperty(value = "small_Snake") @ApiModelProperty(value = "") public String getSmallSnake() { @@ -128,7 +128,7 @@ public Capitalization capitalSnake(String capitalSnake) { * Get capitalSnake * @return capitalSnake **/ - @JsonProperty("Capital_Snake") + @JsonProperty(value = "Capital_Snake") @ApiModelProperty(value = "") public String getCapitalSnake() { @@ -148,7 +148,7 @@ public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { * Get scAETHFlowPoints * @return scAETHFlowPoints **/ - @JsonProperty("SCA_ETH_Flow_Points") + @JsonProperty(value = "SCA_ETH_Flow_Points") @ApiModelProperty(value = "") public String getScAETHFlowPoints() { @@ -168,7 +168,7 @@ public Capitalization ATT_NAME(String ATT_NAME) { * Name of the pet * @return ATT_NAME **/ - @JsonProperty("ATT_NAME") + @JsonProperty(value = "ATT_NAME") @ApiModelProperty(value = "Name of the pet ") public String getATTNAME() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Cat.java index a393506d3aa5..ef4f615bfe76 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Cat.java @@ -45,7 +45,7 @@ public Cat declawed(Boolean declawed) { * Get declawed * @return declawed **/ - @JsonProperty("declawed") + @JsonProperty(value = "declawed") @ApiModelProperty(value = "") public Boolean getDeclawed() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/CatAllOf.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/CatAllOf.java index 7e2a72595950..83503a712d2b 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/CatAllOf.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/CatAllOf.java @@ -43,7 +43,7 @@ public CatAllOf declawed(Boolean declawed) { * Get declawed * @return declawed **/ - @JsonProperty("declawed") + @JsonProperty(value = "declawed") @ApiModelProperty(value = "") public Boolean getDeclawed() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Category.java index d7a5c2b2fafa..af6055dba4ea 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Category.java @@ -48,7 +48,7 @@ public Category id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -68,7 +68,7 @@ public Category name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(required = true, value = "") @NotNull public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ClassModel.java index 00352ed5bce9..ccfe8e27684e 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ClassModel.java @@ -44,7 +44,7 @@ public ClassModel propertyClass(String propertyClass) { * Get propertyClass * @return propertyClass **/ - @JsonProperty("_class") + @JsonProperty(value = "_class") @ApiModelProperty(value = "") public String getPropertyClass() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Client.java index 04b28287ed41..0c87d7030a57 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Client.java @@ -43,7 +43,7 @@ public Client client(String client) { * Get client * @return client **/ - @JsonProperty("client") + @JsonProperty(value = "client") @ApiModelProperty(value = "") public String getClient() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Dog.java index 7d6059b2fc1f..e126444fd61e 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Dog.java @@ -45,7 +45,7 @@ public Dog breed(String breed) { * Get breed * @return breed **/ - @JsonProperty("breed") + @JsonProperty(value = "breed") @ApiModelProperty(value = "") public String getBreed() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/DogAllOf.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/DogAllOf.java index 9fcfbfb92cfc..6902a980c243 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/DogAllOf.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/DogAllOf.java @@ -43,7 +43,7 @@ public DogAllOf breed(String breed) { * Get breed * @return breed **/ - @JsonProperty("breed") + @JsonProperty(value = "breed") @ApiModelProperty(value = "") public String getBreed() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/EnumArrays.java index 526f387372ca..08e6db1ffc92 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/EnumArrays.java @@ -113,7 +113,7 @@ public EnumArrays justSymbol(JustSymbolEnum justSymbol) { * Get justSymbol * @return justSymbol **/ - @JsonProperty("just_symbol") + @JsonProperty(value = "just_symbol") @ApiModelProperty(value = "") public JustSymbolEnum getJustSymbol() { @@ -141,7 +141,7 @@ public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { * Get arrayEnum * @return arrayEnum **/ - @JsonProperty("array_enum") + @JsonProperty(value = "array_enum") @ApiModelProperty(value = "") public List getArrayEnum() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/EnumTest.java index ee08eadfa8d7..937a9f7f6aeb 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/EnumTest.java @@ -193,7 +193,7 @@ public EnumTest enumString(EnumStringEnum enumString) { * Get enumString * @return enumString **/ - @JsonProperty("enum_string") + @JsonProperty(value = "enum_string") @ApiModelProperty(value = "") public EnumStringEnum getEnumString() { @@ -213,7 +213,7 @@ public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { * Get enumStringRequired * @return enumStringRequired **/ - @JsonProperty("enum_string_required") + @JsonProperty(value = "enum_string_required") @ApiModelProperty(required = true, value = "") @NotNull public EnumStringRequiredEnum getEnumStringRequired() { @@ -233,7 +233,7 @@ public EnumTest enumInteger(EnumIntegerEnum enumInteger) { * Get enumInteger * @return enumInteger **/ - @JsonProperty("enum_integer") + @JsonProperty(value = "enum_integer") @ApiModelProperty(value = "") public EnumIntegerEnum getEnumInteger() { @@ -253,7 +253,7 @@ public EnumTest enumNumber(EnumNumberEnum enumNumber) { * Get enumNumber * @return enumNumber **/ - @JsonProperty("enum_number") + @JsonProperty(value = "enum_number") @ApiModelProperty(value = "") public EnumNumberEnum getEnumNumber() { @@ -273,7 +273,7 @@ public EnumTest outerEnum(OuterEnum outerEnum) { * Get outerEnum * @return outerEnum **/ - @JsonProperty("outerEnum") + @JsonProperty(value = "outerEnum") @ApiModelProperty(value = "") @Valid public OuterEnum getOuterEnum() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 4be816893906..fb40a511e446 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -50,7 +50,7 @@ public FileSchemaTestClass file(java.io.File file) { * Get file * @return file **/ - @JsonProperty("file") + @JsonProperty(value = "file") @ApiModelProperty(value = "") @Valid public java.io.File getFile() { @@ -78,7 +78,7 @@ public FileSchemaTestClass addFilesItem(java.io.File filesItem) { * Get files * @return files **/ - @JsonProperty("files") + @JsonProperty(value = "files") @ApiModelProperty(value = "") @Valid public List getFiles() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/FormatTest.java index 9817e78712a7..d640a11342c7 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/FormatTest.java @@ -114,7 +114,7 @@ public FormatTest integer(Integer integer) { * maximum: 100 * @return integer **/ - @JsonProperty("integer") + @JsonProperty(value = "integer") @ApiModelProperty(value = "") @Min(10) @Max(100) public Integer getInteger() { @@ -136,7 +136,7 @@ public FormatTest int32(Integer int32) { * maximum: 200 * @return int32 **/ - @JsonProperty("int32") + @JsonProperty(value = "int32") @ApiModelProperty(value = "") @Min(20) @Max(200) public Integer getInt32() { @@ -156,7 +156,7 @@ public FormatTest int64(Long int64) { * Get int64 * @return int64 **/ - @JsonProperty("int64") + @JsonProperty(value = "int64") @ApiModelProperty(value = "") public Long getInt64() { @@ -178,7 +178,7 @@ public FormatTest number(BigDecimal number) { * maximum: 543.2 * @return number **/ - @JsonProperty("number") + @JsonProperty(value = "number") @ApiModelProperty(required = true, value = "") @NotNull @Valid @DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { @@ -200,7 +200,7 @@ public FormatTest _float(Float _float) { * maximum: 987.6 * @return _float **/ - @JsonProperty("float") + @JsonProperty(value = "float") @ApiModelProperty(value = "") @DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { @@ -222,7 +222,7 @@ public FormatTest _double(Double _double) { * maximum: 123.4 * @return _double **/ - @JsonProperty("double") + @JsonProperty(value = "double") @ApiModelProperty(value = "") @DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { @@ -242,7 +242,7 @@ public FormatTest string(String string) { * Get string * @return string **/ - @JsonProperty("string") + @JsonProperty(value = "string") @ApiModelProperty(value = "") @Pattern(regexp="/[a-z]/i") public String getString() { @@ -262,7 +262,7 @@ public FormatTest _byte(byte[] _byte) { * Get _byte * @return _byte **/ - @JsonProperty("byte") + @JsonProperty(value = "byte") @ApiModelProperty(required = true, value = "") @NotNull public byte[] getByte() { @@ -282,7 +282,7 @@ public FormatTest binary(File binary) { * Get binary * @return binary **/ - @JsonProperty("binary") + @JsonProperty(value = "binary") @ApiModelProperty(value = "") public File getBinary() { @@ -302,7 +302,7 @@ public FormatTest date(Date date) { * Get date * @return date **/ - @JsonProperty("date") + @JsonProperty(value = "date") @ApiModelProperty(required = true, value = "") @NotNull public Date getDate() { @@ -322,7 +322,7 @@ public FormatTest dateTime(Date dateTime) { * Get dateTime * @return dateTime **/ - @JsonProperty("dateTime") + @JsonProperty(value = "dateTime") @ApiModelProperty(value = "") public Date getDateTime() { @@ -342,7 +342,7 @@ public FormatTest uuid(UUID uuid) { * Get uuid * @return uuid **/ - @JsonProperty("uuid") + @JsonProperty(value = "uuid") @ApiModelProperty(example = "72f98069-206d-4f12-9f12-3d1e525a8e84", value = "") public UUID getUuid() { @@ -362,7 +362,7 @@ public FormatTest password(String password) { * Get password * @return password **/ - @JsonProperty("password") + @JsonProperty(value = "password") @ApiModelProperty(required = true, value = "") @NotNull @Size(min=10,max=64) public String getPassword() { @@ -382,7 +382,7 @@ public FormatTest bigDecimal(BigDecimal bigDecimal) { * Get bigDecimal * @return bigDecimal **/ - @JsonProperty("BigDecimal") + @JsonProperty(value = "BigDecimal") @ApiModelProperty(value = "") @Valid public BigDecimal getBigDecimal() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index 4f72442fd947..1b5042f61f59 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -48,7 +48,7 @@ public HasOnlyReadOnly bar(String bar) { * Get bar * @return bar **/ - @JsonProperty("bar") + @JsonProperty(value = "bar", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getBar() { @@ -68,7 +68,7 @@ public HasOnlyReadOnly foo(String foo) { * Get foo * @return foo **/ - @JsonProperty("foo") + @JsonProperty(value = "foo", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getFoo() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/MapTest.java index 4db676efea2d..12516e0afba2 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/MapTest.java @@ -101,7 +101,7 @@ public MapTest putMapMapOfStringItem(String key, Map mapMapOfStr * Get mapMapOfString * @return mapMapOfString **/ - @JsonProperty("map_map_of_string") + @JsonProperty(value = "map_map_of_string") @ApiModelProperty(value = "") @Valid public Map> getMapMapOfString() { @@ -129,7 +129,7 @@ public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) * Get mapOfEnumString * @return mapOfEnumString **/ - @JsonProperty("map_of_enum_string") + @JsonProperty(value = "map_of_enum_string") @ApiModelProperty(value = "") public Map getMapOfEnumString() { @@ -157,7 +157,7 @@ public MapTest putDirectMapItem(String key, Boolean directMapItem) { * Get directMap * @return directMap **/ - @JsonProperty("direct_map") + @JsonProperty(value = "direct_map") @ApiModelProperty(value = "") public Map getDirectMap() { @@ -185,7 +185,7 @@ public MapTest putIndirectMapItem(String key, Boolean indirectMapItem) { * Get indirectMap * @return indirectMap **/ - @JsonProperty("indirect_map") + @JsonProperty(value = "indirect_map") @ApiModelProperty(value = "") public Map getIndirectMap() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index 0ba358c6b5c2..eb4fcd577811 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -59,7 +59,7 @@ public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { * Get uuid * @return uuid **/ - @JsonProperty("uuid") + @JsonProperty(value = "uuid") @ApiModelProperty(value = "") public UUID getUuid() { @@ -79,7 +79,7 @@ public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { * Get dateTime * @return dateTime **/ - @JsonProperty("dateTime") + @JsonProperty(value = "dateTime") @ApiModelProperty(value = "") public Date getDateTime() { @@ -107,7 +107,7 @@ public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal * Get map * @return map **/ - @JsonProperty("map") + @JsonProperty(value = "map") @ApiModelProperty(value = "") @Valid public Map getMap() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Model200Response.java index 2df0caa9725d..1a3e698983e5 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Model200Response.java @@ -49,7 +49,7 @@ public Model200Response name(Integer name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public Integer getName() { @@ -69,7 +69,7 @@ public Model200Response propertyClass(String propertyClass) { * Get propertyClass * @return propertyClass **/ - @JsonProperty("class") + @JsonProperty(value = "class") @ApiModelProperty(value = "") public String getPropertyClass() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelApiResponse.java index b0d01665ef6a..1552245d1dc8 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -53,7 +53,7 @@ public ModelApiResponse code(Integer code) { * Get code * @return code **/ - @JsonProperty("code") + @JsonProperty(value = "code") @ApiModelProperty(value = "") public Integer getCode() { @@ -73,7 +73,7 @@ public ModelApiResponse type(String type) { * Get type * @return type **/ - @JsonProperty("type") + @JsonProperty(value = "type") @ApiModelProperty(value = "") public String getType() { @@ -93,7 +93,7 @@ public ModelApiResponse message(String message) { * Get message * @return message **/ - @JsonProperty("message") + @JsonProperty(value = "message") @ApiModelProperty(value = "") public String getMessage() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelReturn.java index 41a1c059f7ef..c9f4504d3f0e 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelReturn.java @@ -44,7 +44,7 @@ public ModelReturn _return(Integer _return) { * Get _return * @return _return **/ - @JsonProperty("return") + @JsonProperty(value = "return") @ApiModelProperty(value = "") public Integer getReturn() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Name.java index a7a189571897..cdcef856cd21 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Name.java @@ -59,7 +59,7 @@ public Name name(Integer name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(required = true, value = "") @NotNull public Integer getName() { @@ -79,7 +79,7 @@ public Name snakeCase(Integer snakeCase) { * Get snakeCase * @return snakeCase **/ - @JsonProperty("snake_case") + @JsonProperty(value = "snake_case", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public Integer getSnakeCase() { @@ -99,7 +99,7 @@ public Name property(String property) { * Get property * @return property **/ - @JsonProperty("property") + @JsonProperty(value = "property") @ApiModelProperty(value = "") public String getProperty() { @@ -119,7 +119,7 @@ public Name _123number(Integer _123number) { * Get _123number * @return _123number **/ - @JsonProperty("123Number") + @JsonProperty(value = "123Number", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public Integer get123number() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/NumberOnly.java index 188899dc4460..3ec25c75ae59 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/NumberOnly.java @@ -44,7 +44,7 @@ public NumberOnly justNumber(BigDecimal justNumber) { * Get justNumber * @return justNumber **/ - @JsonProperty("JustNumber") + @JsonProperty(value = "JustNumber") @ApiModelProperty(value = "") @Valid public BigDecimal getJustNumber() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Order.java index 7ce0000199f9..b97b051ebc80 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Order.java @@ -103,7 +103,7 @@ public Order id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -123,7 +123,7 @@ public Order petId(Long petId) { * Get petId * @return petId **/ - @JsonProperty("petId") + @JsonProperty(value = "petId") @ApiModelProperty(value = "") public Long getPetId() { @@ -143,7 +143,7 @@ public Order quantity(Integer quantity) { * Get quantity * @return quantity **/ - @JsonProperty("quantity") + @JsonProperty(value = "quantity") @ApiModelProperty(value = "") public Integer getQuantity() { @@ -163,7 +163,7 @@ public Order shipDate(Date shipDate) { * Get shipDate * @return shipDate **/ - @JsonProperty("shipDate") + @JsonProperty(value = "shipDate") @ApiModelProperty(value = "") public Date getShipDate() { @@ -183,7 +183,7 @@ public Order status(StatusEnum status) { * Order Status * @return status **/ - @JsonProperty("status") + @JsonProperty(value = "status") @ApiModelProperty(value = "Order Status") public StatusEnum getStatus() { @@ -203,7 +203,7 @@ public Order complete(Boolean complete) { * Get complete * @return complete **/ - @JsonProperty("complete") + @JsonProperty(value = "complete") @ApiModelProperty(value = "") public Boolean getComplete() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/OuterComposite.java index 43b69002d036..577504e1bef2 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/OuterComposite.java @@ -54,7 +54,7 @@ public OuterComposite myNumber(BigDecimal myNumber) { * Get myNumber * @return myNumber **/ - @JsonProperty("my_number") + @JsonProperty(value = "my_number") @ApiModelProperty(value = "") @Valid public BigDecimal getMyNumber() { @@ -74,7 +74,7 @@ public OuterComposite myString(String myString) { * Get myString * @return myString **/ - @JsonProperty("my_string") + @JsonProperty(value = "my_string") @ApiModelProperty(value = "") public String getMyString() { @@ -94,7 +94,7 @@ public OuterComposite myBoolean(Boolean myBoolean) { * Get myBoolean * @return myBoolean **/ - @JsonProperty("my_boolean") + @JsonProperty(value = "my_boolean") @ApiModelProperty(value = "") public Boolean getMyBoolean() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Pet.java index adcdbf24a57d..4ed108d787e9 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Pet.java @@ -108,7 +108,7 @@ public Pet id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -128,7 +128,7 @@ public Pet category(Category category) { * Get category * @return category **/ - @JsonProperty("category") + @JsonProperty(value = "category") @ApiModelProperty(value = "") @Valid public Category getCategory() { @@ -148,7 +148,7 @@ public Pet name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(example = "doggie", required = true, value = "") @NotNull public String getName() { @@ -173,7 +173,7 @@ public Pet addPhotoUrlsItem(String photoUrlsItem) { * Get photoUrls * @return photoUrls **/ - @JsonProperty("photoUrls") + @JsonProperty(value = "photoUrls") @ApiModelProperty(required = true, value = "") @NotNull public Set getPhotoUrls() { @@ -201,7 +201,7 @@ public Pet addTagsItem(Tag tagsItem) { * Get tags * @return tags **/ - @JsonProperty("tags") + @JsonProperty(value = "tags") @ApiModelProperty(value = "") @Valid public List getTags() { @@ -221,7 +221,7 @@ public Pet status(StatusEnum status) { * pet status in the store * @return status **/ - @JsonProperty("status") + @JsonProperty(value = "status") @ApiModelProperty(value = "pet status in the store") public StatusEnum getStatus() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index e2e5ea910e68..05c01064ff67 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -48,7 +48,7 @@ public ReadOnlyFirst bar(String bar) { * Get bar * @return bar **/ - @JsonProperty("bar") + @JsonProperty(value = "bar", access = JsonProperty.Access.READ_ONLY) @ApiModelProperty(value = "") public String getBar() { @@ -68,7 +68,7 @@ public ReadOnlyFirst baz(String baz) { * Get baz * @return baz **/ - @JsonProperty("baz") + @JsonProperty(value = "baz") @ApiModelProperty(value = "") public String getBaz() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/SpecialModelName.java index 48ed44ecf621..1fbc58e301e6 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -43,7 +43,7 @@ public class SpecialModelName { * Get $specialPropertyName * @return $specialPropertyName **/ - @JsonProperty("$special[property.name]") + @JsonProperty(value = "$special[property.name]") @ApiModelProperty(value = "") public Long get$SpecialPropertyName() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Tag.java index 80d098d57c16..5ac82ca92382 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Tag.java @@ -48,7 +48,7 @@ public Tag id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -68,7 +68,7 @@ public Tag name(String name) { * Get name * @return name **/ - @JsonProperty("name") + @JsonProperty(value = "name") @ApiModelProperty(value = "") public String getName() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/TypeHolderDefault.java index 52830413a08c..a8450d0e61d5 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/TypeHolderDefault.java @@ -66,7 +66,7 @@ public TypeHolderDefault stringItem(String stringItem) { * Get stringItem * @return stringItem **/ - @JsonProperty("string_item") + @JsonProperty(value = "string_item") @ApiModelProperty(required = true, value = "") @NotNull public String getStringItem() { @@ -86,7 +86,7 @@ public TypeHolderDefault numberItem(BigDecimal numberItem) { * Get numberItem * @return numberItem **/ - @JsonProperty("number_item") + @JsonProperty(value = "number_item") @ApiModelProperty(required = true, value = "") @NotNull @Valid public BigDecimal getNumberItem() { @@ -106,7 +106,7 @@ public TypeHolderDefault integerItem(Integer integerItem) { * Get integerItem * @return integerItem **/ - @JsonProperty("integer_item") + @JsonProperty(value = "integer_item") @ApiModelProperty(required = true, value = "") @NotNull public Integer getIntegerItem() { @@ -126,7 +126,7 @@ public TypeHolderDefault boolItem(Boolean boolItem) { * Get boolItem * @return boolItem **/ - @JsonProperty("bool_item") + @JsonProperty(value = "bool_item") @ApiModelProperty(required = true, value = "") @NotNull public Boolean getBoolItem() { @@ -151,7 +151,7 @@ public TypeHolderDefault addArrayItemItem(Integer arrayItemItem) { * Get arrayItem * @return arrayItem **/ - @JsonProperty("array_item") + @JsonProperty(value = "array_item") @ApiModelProperty(required = true, value = "") @NotNull public List getArrayItem() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/TypeHolderExample.java index 8e57cc93cef4..026943cb64e3 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/TypeHolderExample.java @@ -71,7 +71,7 @@ public TypeHolderExample stringItem(String stringItem) { * Get stringItem * @return stringItem **/ - @JsonProperty("string_item") + @JsonProperty(value = "string_item") @ApiModelProperty(example = "what", required = true, value = "") @NotNull public String getStringItem() { @@ -91,7 +91,7 @@ public TypeHolderExample numberItem(BigDecimal numberItem) { * Get numberItem * @return numberItem **/ - @JsonProperty("number_item") + @JsonProperty(value = "number_item") @ApiModelProperty(example = "1.234", required = true, value = "") @NotNull @Valid public BigDecimal getNumberItem() { @@ -111,7 +111,7 @@ public TypeHolderExample floatItem(Float floatItem) { * Get floatItem * @return floatItem **/ - @JsonProperty("float_item") + @JsonProperty(value = "float_item") @ApiModelProperty(example = "1.234", required = true, value = "") @NotNull public Float getFloatItem() { @@ -131,7 +131,7 @@ public TypeHolderExample integerItem(Integer integerItem) { * Get integerItem * @return integerItem **/ - @JsonProperty("integer_item") + @JsonProperty(value = "integer_item") @ApiModelProperty(example = "-2", required = true, value = "") @NotNull public Integer getIntegerItem() { @@ -151,7 +151,7 @@ public TypeHolderExample boolItem(Boolean boolItem) { * Get boolItem * @return boolItem **/ - @JsonProperty("bool_item") + @JsonProperty(value = "bool_item") @ApiModelProperty(example = "true", required = true, value = "") @NotNull public Boolean getBoolItem() { @@ -176,7 +176,7 @@ public TypeHolderExample addArrayItemItem(Integer arrayItemItem) { * Get arrayItem * @return arrayItem **/ - @JsonProperty("array_item") + @JsonProperty(value = "array_item") @ApiModelProperty(example = "[0, 1, 2, 3]", required = true, value = "") @NotNull public List getArrayItem() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/User.java index 1e702dd070d5..37ab5453c3d2 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/User.java @@ -78,7 +78,7 @@ public User id(Long id) { * Get id * @return id **/ - @JsonProperty("id") + @JsonProperty(value = "id") @ApiModelProperty(value = "") public Long getId() { @@ -98,7 +98,7 @@ public User username(String username) { * Get username * @return username **/ - @JsonProperty("username") + @JsonProperty(value = "username") @ApiModelProperty(value = "") public String getUsername() { @@ -118,7 +118,7 @@ public User firstName(String firstName) { * Get firstName * @return firstName **/ - @JsonProperty("firstName") + @JsonProperty(value = "firstName") @ApiModelProperty(value = "") public String getFirstName() { @@ -138,7 +138,7 @@ public User lastName(String lastName) { * Get lastName * @return lastName **/ - @JsonProperty("lastName") + @JsonProperty(value = "lastName") @ApiModelProperty(value = "") public String getLastName() { @@ -158,7 +158,7 @@ public User email(String email) { * Get email * @return email **/ - @JsonProperty("email") + @JsonProperty(value = "email") @ApiModelProperty(value = "") public String getEmail() { @@ -178,7 +178,7 @@ public User password(String password) { * Get password * @return password **/ - @JsonProperty("password") + @JsonProperty(value = "password") @ApiModelProperty(value = "") public String getPassword() { @@ -198,7 +198,7 @@ public User phone(String phone) { * Get phone * @return phone **/ - @JsonProperty("phone") + @JsonProperty(value = "phone") @ApiModelProperty(value = "") public String getPhone() { @@ -218,7 +218,7 @@ public User userStatus(Integer userStatus) { * User Status * @return userStatus **/ - @JsonProperty("userStatus") + @JsonProperty(value = "userStatus") @ApiModelProperty(value = "User Status") public Integer getUserStatus() { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/XmlItem.java index 8c61e3e4cc0e..46c2de9ca268 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/XmlItem.java @@ -186,7 +186,7 @@ public XmlItem attributeString(String attributeString) { * Get attributeString * @return attributeString **/ - @JsonProperty("attribute_string") + @JsonProperty(value = "attribute_string") @ApiModelProperty(example = "string", value = "") public String getAttributeString() { @@ -206,7 +206,7 @@ public XmlItem attributeNumber(BigDecimal attributeNumber) { * Get attributeNumber * @return attributeNumber **/ - @JsonProperty("attribute_number") + @JsonProperty(value = "attribute_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getAttributeNumber() { @@ -226,7 +226,7 @@ public XmlItem attributeInteger(Integer attributeInteger) { * Get attributeInteger * @return attributeInteger **/ - @JsonProperty("attribute_integer") + @JsonProperty(value = "attribute_integer") @ApiModelProperty(example = "-2", value = "") public Integer getAttributeInteger() { @@ -246,7 +246,7 @@ public XmlItem attributeBoolean(Boolean attributeBoolean) { * Get attributeBoolean * @return attributeBoolean **/ - @JsonProperty("attribute_boolean") + @JsonProperty(value = "attribute_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getAttributeBoolean() { @@ -274,7 +274,7 @@ public XmlItem addWrappedArrayItem(Integer wrappedArrayItem) { * Get wrappedArray * @return wrappedArray **/ - @JsonProperty("wrapped_array") + @JsonProperty(value = "wrapped_array") @ApiModelProperty(value = "") public List getWrappedArray() { @@ -294,7 +294,7 @@ public XmlItem nameString(String nameString) { * Get nameString * @return nameString **/ - @JsonProperty("name_string") + @JsonProperty(value = "name_string") @ApiModelProperty(example = "string", value = "") public String getNameString() { @@ -314,7 +314,7 @@ public XmlItem nameNumber(BigDecimal nameNumber) { * Get nameNumber * @return nameNumber **/ - @JsonProperty("name_number") + @JsonProperty(value = "name_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getNameNumber() { @@ -334,7 +334,7 @@ public XmlItem nameInteger(Integer nameInteger) { * Get nameInteger * @return nameInteger **/ - @JsonProperty("name_integer") + @JsonProperty(value = "name_integer") @ApiModelProperty(example = "-2", value = "") public Integer getNameInteger() { @@ -354,7 +354,7 @@ public XmlItem nameBoolean(Boolean nameBoolean) { * Get nameBoolean * @return nameBoolean **/ - @JsonProperty("name_boolean") + @JsonProperty(value = "name_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getNameBoolean() { @@ -382,7 +382,7 @@ public XmlItem addNameArrayItem(Integer nameArrayItem) { * Get nameArray * @return nameArray **/ - @JsonProperty("name_array") + @JsonProperty(value = "name_array") @ApiModelProperty(value = "") public List getNameArray() { @@ -410,7 +410,7 @@ public XmlItem addNameWrappedArrayItem(Integer nameWrappedArrayItem) { * Get nameWrappedArray * @return nameWrappedArray **/ - @JsonProperty("name_wrapped_array") + @JsonProperty(value = "name_wrapped_array") @ApiModelProperty(value = "") public List getNameWrappedArray() { @@ -430,7 +430,7 @@ public XmlItem prefixString(String prefixString) { * Get prefixString * @return prefixString **/ - @JsonProperty("prefix_string") + @JsonProperty(value = "prefix_string") @ApiModelProperty(example = "string", value = "") public String getPrefixString() { @@ -450,7 +450,7 @@ public XmlItem prefixNumber(BigDecimal prefixNumber) { * Get prefixNumber * @return prefixNumber **/ - @JsonProperty("prefix_number") + @JsonProperty(value = "prefix_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getPrefixNumber() { @@ -470,7 +470,7 @@ public XmlItem prefixInteger(Integer prefixInteger) { * Get prefixInteger * @return prefixInteger **/ - @JsonProperty("prefix_integer") + @JsonProperty(value = "prefix_integer") @ApiModelProperty(example = "-2", value = "") public Integer getPrefixInteger() { @@ -490,7 +490,7 @@ public XmlItem prefixBoolean(Boolean prefixBoolean) { * Get prefixBoolean * @return prefixBoolean **/ - @JsonProperty("prefix_boolean") + @JsonProperty(value = "prefix_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getPrefixBoolean() { @@ -518,7 +518,7 @@ public XmlItem addPrefixArrayItem(Integer prefixArrayItem) { * Get prefixArray * @return prefixArray **/ - @JsonProperty("prefix_array") + @JsonProperty(value = "prefix_array") @ApiModelProperty(value = "") public List getPrefixArray() { @@ -546,7 +546,7 @@ public XmlItem addPrefixWrappedArrayItem(Integer prefixWrappedArrayItem) { * Get prefixWrappedArray * @return prefixWrappedArray **/ - @JsonProperty("prefix_wrapped_array") + @JsonProperty(value = "prefix_wrapped_array") @ApiModelProperty(value = "") public List getPrefixWrappedArray() { @@ -566,7 +566,7 @@ public XmlItem namespaceString(String namespaceString) { * Get namespaceString * @return namespaceString **/ - @JsonProperty("namespace_string") + @JsonProperty(value = "namespace_string") @ApiModelProperty(example = "string", value = "") public String getNamespaceString() { @@ -586,7 +586,7 @@ public XmlItem namespaceNumber(BigDecimal namespaceNumber) { * Get namespaceNumber * @return namespaceNumber **/ - @JsonProperty("namespace_number") + @JsonProperty(value = "namespace_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getNamespaceNumber() { @@ -606,7 +606,7 @@ public XmlItem namespaceInteger(Integer namespaceInteger) { * Get namespaceInteger * @return namespaceInteger **/ - @JsonProperty("namespace_integer") + @JsonProperty(value = "namespace_integer") @ApiModelProperty(example = "-2", value = "") public Integer getNamespaceInteger() { @@ -626,7 +626,7 @@ public XmlItem namespaceBoolean(Boolean namespaceBoolean) { * Get namespaceBoolean * @return namespaceBoolean **/ - @JsonProperty("namespace_boolean") + @JsonProperty(value = "namespace_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getNamespaceBoolean() { @@ -654,7 +654,7 @@ public XmlItem addNamespaceArrayItem(Integer namespaceArrayItem) { * Get namespaceArray * @return namespaceArray **/ - @JsonProperty("namespace_array") + @JsonProperty(value = "namespace_array") @ApiModelProperty(value = "") public List getNamespaceArray() { @@ -682,7 +682,7 @@ public XmlItem addNamespaceWrappedArrayItem(Integer namespaceWrappedArrayItem) { * Get namespaceWrappedArray * @return namespaceWrappedArray **/ - @JsonProperty("namespace_wrapped_array") + @JsonProperty(value = "namespace_wrapped_array") @ApiModelProperty(value = "") public List getNamespaceWrappedArray() { @@ -702,7 +702,7 @@ public XmlItem prefixNsString(String prefixNsString) { * Get prefixNsString * @return prefixNsString **/ - @JsonProperty("prefix_ns_string") + @JsonProperty(value = "prefix_ns_string") @ApiModelProperty(example = "string", value = "") public String getPrefixNsString() { @@ -722,7 +722,7 @@ public XmlItem prefixNsNumber(BigDecimal prefixNsNumber) { * Get prefixNsNumber * @return prefixNsNumber **/ - @JsonProperty("prefix_ns_number") + @JsonProperty(value = "prefix_ns_number") @ApiModelProperty(example = "1.234", value = "") @Valid public BigDecimal getPrefixNsNumber() { @@ -742,7 +742,7 @@ public XmlItem prefixNsInteger(Integer prefixNsInteger) { * Get prefixNsInteger * @return prefixNsInteger **/ - @JsonProperty("prefix_ns_integer") + @JsonProperty(value = "prefix_ns_integer") @ApiModelProperty(example = "-2", value = "") public Integer getPrefixNsInteger() { @@ -762,7 +762,7 @@ public XmlItem prefixNsBoolean(Boolean prefixNsBoolean) { * Get prefixNsBoolean * @return prefixNsBoolean **/ - @JsonProperty("prefix_ns_boolean") + @JsonProperty(value = "prefix_ns_boolean") @ApiModelProperty(example = "true", value = "") public Boolean getPrefixNsBoolean() { @@ -790,7 +790,7 @@ public XmlItem addPrefixNsArrayItem(Integer prefixNsArrayItem) { * Get prefixNsArray * @return prefixNsArray **/ - @JsonProperty("prefix_ns_array") + @JsonProperty(value = "prefix_ns_array") @ApiModelProperty(value = "") public List getPrefixNsArray() { @@ -818,7 +818,7 @@ public XmlItem addPrefixNsWrappedArrayItem(Integer prefixNsWrappedArrayItem) { * Get prefixNsWrappedArray * @return prefixNsWrappedArray **/ - @JsonProperty("prefix_ns_wrapped_array") + @JsonProperty(value = "prefix_ns_wrapped_array") @ApiModelProperty(value = "") public List getPrefixNsWrappedArray() { diff --git a/samples/server/petstore/kotlin-server/ktor/.openapi-generator/VERSION b/samples/server/petstore/kotlin-server/ktor/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/kotlin-server/ktor/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-server/ktor/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-server/ktor/README.md b/samples/server/petstore/kotlin-server/ktor/README.md index 7cb90e7f8536..0312e13cdf7c 100644 --- a/samples/server/petstore/kotlin-server/ktor/README.md +++ b/samples/server/petstore/kotlin-server/ktor/README.md @@ -2,12 +2,12 @@ This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. -Generated by OpenAPI Generator 5.1.1-SNAPSHOT. +Generated by OpenAPI Generator 5.2.0-SNAPSHOT. ## Requires -* Kotlin 1.3.21 -* Gradle 4.9 +* Kotlin 1.4.31 +* Gradle 6.8.2 ## Build diff --git a/samples/server/petstore/kotlin-server/ktor/build.gradle b/samples/server/petstore/kotlin-server/ktor/build.gradle index 25536d4e5316..c69f129160f5 100644 --- a/samples/server/petstore/kotlin-server/ktor/build.gradle +++ b/samples/server/petstore/kotlin-server/ktor/build.gradle @@ -2,13 +2,13 @@ group 'org.openapitools' version '1.0.0' wrapper { - gradleVersion = '4.9' + gradleVersion = '6.8.2' distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.3.21' - ext.ktor_version = '1.1.3' + ext.kotlin_version = '1.4.31' + ext.ktor_version = '1.5.2' ext.shadow_version = '2.0.3' repositories { @@ -29,7 +29,7 @@ apply plugin: 'application' mainClassName = "io.ktor.server.netty.DevelopmentEngine" -// Initialization order with shadow 2.0.1 and Gradle 4.3 is weird. +// Initialization order with shadow 2.0.1 and Gradle 6.8.2 is weird. // See https://github.com/johnrengelman/shadow/issues/336#issuecomment-355402508 apply plugin: 'com.github.johnrengelman.shadow' @@ -59,6 +59,7 @@ dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" compile "io.ktor:ktor-server-netty:$ktor_version" compile "io.ktor:ktor-metrics:$ktor_version" + compile "io.ktor:ktor-auth:$ktor_version" compile "io.ktor:ktor-locations:$ktor_version" compile "io.ktor:ktor-gson:$ktor_version" compile "io.ktor:ktor-client-core:$ktor_version" diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/AppMain.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/AppMain.kt index 2b0cd5cdb5fd..54658d6ba5df 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/AppMain.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/AppMain.kt @@ -18,12 +18,11 @@ import io.ktor.gson.GsonConverter import io.ktor.http.ContentType import io.ktor.locations.KtorExperimentalLocationsAPI import io.ktor.locations.Locations -import io.ktor.metrics.Metrics import io.ktor.routing.Routing import java.util.concurrent.TimeUnit -import io.ktor.util.KtorExperimentalAPI import io.ktor.auth.Authentication import io.ktor.auth.oauth +import io.ktor.metrics.dropwizard.DropwizardMetrics import org.openapitools.server.infrastructure.ApiKeyCredential import org.openapitools.server.infrastructure.ApiPrincipal import org.openapitools.server.infrastructure.apiKeyAuth @@ -32,23 +31,21 @@ import org.openapitools.server.apis.StoreApi import org.openapitools.server.apis.UserApi -@KtorExperimentalAPI internal val settings = HoconApplicationConfig(ConfigFactory.defaultApplication(HTTP::class.java.classLoader)) object HTTP { val client = HttpClient(Apache) } -@KtorExperimentalAPI @KtorExperimentalLocationsAPI fun Application.main() { install(DefaultHeaders) - install(Metrics) { + install(DropwizardMetrics) { val reporter = Slf4jReporter.forRegistry(registry) - .outputTo(log) - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .build() + .outputTo(log) + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .build() reporter.start(10, TimeUnit.SECONDS) } install(ContentNegotiation) { @@ -72,8 +69,8 @@ fun Application.main() { client = HttpClient(Apache) providerLookup = { ApplicationAuthProviders["petstore_auth"] } urlProvider = { _ -> - // TODO: define a callback url here. - "/" + // TODO: define a callback url here. + "/" } } } @@ -84,8 +81,7 @@ fun Application.main() { } - environment.monitor.subscribe(ApplicationStopping) - { + environment.monitor.subscribe(ApplicationStopping) { HTTP.client.close() } } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Configuration.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Configuration.kt index c16a32ef70f0..8483e64319d0 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Configuration.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Configuration.kt @@ -8,11 +8,7 @@ import io.ktor.features.deflate import io.ktor.features.gzip import io.ktor.features.minimumSize import io.ktor.http.HttpMethod -import io.ktor.util.KtorExperimentalAPI -import java.time.Duration -import java.util.concurrent.Executors - -import org.openapitools.server.settings +import java.util.concurrent.TimeUnit /** @@ -25,7 +21,7 @@ import org.openapitools.server.settings */ internal fun ApplicationHstsConfiguration(): HSTS.Configuration.() -> Unit { return { - maxAge = Duration.ofDays(365) + maxAgeInSeconds = TimeUnit.DAYS.toSeconds(365) includeSubDomains = true preload = false @@ -55,7 +51,6 @@ internal fun ApplicationCompressionConfiguration(): Compression.Configuration.() } // Defines authentication mechanisms used throughout the application. -@KtorExperimentalAPI val ApplicationAuthProviders: Map = listOf( OAuthServerSettings.OAuth2ServerSettings( name = "petstore_auth", @@ -77,6 +72,3 @@ val ApplicationAuthProviders: Map = listOf) + @Location("/pet/findByStatus") class findPetsByStatus(val status: kotlin.collections.List) /** * Finds Pets by tags @@ -38,7 +47,7 @@ object Paths { * @param tags Tags to filter by */ @KtorExperimentalLocationsAPI - @Location("/pet/findByTags") class findPetsByTags(val tags: kotlin.Array) + @Location("/pet/findByTags") class findPetsByTags(val tags: kotlin.collections.List) /** * Find pet by ID @@ -48,6 +57,34 @@ object Paths { @KtorExperimentalLocationsAPI @Location("/pet/{petId}") class getPetById(val petId: kotlin.Long) + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + @KtorExperimentalLocationsAPI + @Location("/pet") class updatePet(val body: Pet) + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + */ + @KtorExperimentalLocationsAPI + @Location("/pet/{petId}") class updatePetWithForm(val petId: kotlin.Long, val name: kotlin.String? = null, val status: kotlin.String? = null) + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + */ + @KtorExperimentalLocationsAPI + @Location("/pet/{petId}/uploadImage") class uploadFile(val petId: kotlin.Long, val additionalMetadata: kotlin.String? = null, val file: java.io.File? = null) + /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -71,6 +108,38 @@ object Paths { @KtorExperimentalLocationsAPI @Location("/store/order/{orderId}") class getOrderById(val orderId: kotlin.Long) + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + @KtorExperimentalLocationsAPI + @Location("/store/order") class placeOrder(val body: Order) + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + @KtorExperimentalLocationsAPI + @Location("/user") class createUser(val body: User) + + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + @KtorExperimentalLocationsAPI + @Location("/user/createWithArray") class createUsersWithArrayInput(val body: kotlin.collections.List) + + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + @KtorExperimentalLocationsAPI + @Location("/user/createWithList") class createUsersWithListInput(val body: kotlin.collections.List) + /** * Delete user * This can only be done by the logged in user. @@ -103,4 +172,13 @@ object Paths { @KtorExperimentalLocationsAPI @Location("/user/logout") class logoutUser() + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + @KtorExperimentalLocationsAPI + @Location("/user/{username}") class updateUser(val username: kotlin.String, val body: User) + } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/PetApi.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/PetApi.kt index 3ac3578638d5..9226541eb34e 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/PetApi.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/PetApi.kt @@ -20,17 +20,18 @@ import io.ktor.auth.OAuthAccessTokenResponse import io.ktor.auth.OAuthServerSettings import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode -import io.ktor.locations.KtorExperimentalLocationsAPI -import io.ktor.locations.delete -import io.ktor.locations.get import io.ktor.response.respond import io.ktor.response.respondText import io.ktor.routing.Route -import io.ktor.routing.post -import io.ktor.routing.put -import io.ktor.routing.route - import org.openapitools.server.Paths +import io.ktor.locations.KtorExperimentalLocationsAPI +import io.ktor.locations.delete +import io.ktor.locations.get +import io.ktor.locations.post +import io.ktor.locations.put +import io.ktor.locations.options +import io.ktor.locations.head + import org.openapitools.server.infrastructure.ApiPrincipal @@ -41,40 +42,27 @@ import org.openapitools.server.models.Pet fun Route.PetApi() { val gson = Gson() val empty = mutableMapOf() - - route("/pet") { - authenticate("petstore_auth") { - post { - val principal = call.authentication.principal() - - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - call.respond(HttpStatusCode.NotImplemented) - } - } - } + authenticate("petstore_auth") { + post { + val principal = call.authentication.principal()!! + + call.respond(HttpStatusCode.NotImplemented) + } } - - delete { _: Paths.deletePet -> - val principal = call.authentication.principal() + authenticate("petstore_auth") { + delete { + val principal = call.authentication.principal()!! - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - call.respond(HttpStatusCode.NotImplemented) - } + call.respond(HttpStatusCode.NotImplemented) + } } - - get { _: Paths.findPetsByStatus -> - val principal = call.authentication.principal() + authenticate("petstore_auth") { + get { + val principal = call.authentication.principal()!! - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - val exampleContentType = "application/json" + val exampleContentType = "application/json" val exampleContentString = """{ "photoUrls" : [ "photoUrls", "photoUrls" ], "name" : "doggie", @@ -93,22 +81,19 @@ fun Route.PetApi() { "status" : "available" }""" - when(exampleContentType) { + when (exampleContentType) { "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } - } + } } - - get { _: Paths.findPetsByTags -> - val principal = call.authentication.principal() + authenticate("petstore_auth") { + get { + val principal = call.authentication.principal()!! - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - val exampleContentType = "application/json" + val exampleContentType = "application/json" val exampleContentString = """{ "photoUrls" : [ "photoUrls", "photoUrls" ], "name" : "doggie", @@ -127,22 +112,19 @@ fun Route.PetApi() { "status" : "available" }""" - when(exampleContentType) { + when (exampleContentType) { "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } - } + } } - - get { _: Paths.getPetById -> - val principal = call.authentication.principal() + authenticate("api_key") { + get { + val principal = call.authentication.principal()!! - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - val exampleContentType = "application/json" + val exampleContentType = "application/json" val exampleContentString = """{ "photoUrls" : [ "photoUrls", "photoUrls" ], "name" : "doggie", @@ -161,68 +143,47 @@ fun Route.PetApi() { "status" : "available" }""" - when(exampleContentType) { + when (exampleContentType) { "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } - } } - - - route("/pet") { - authenticate("petstore_auth") { - put { - val principal = call.authentication.principal() - - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - call.respond(HttpStatusCode.NotImplemented) - } - } - } } - - route("/pet/{petId}") { - authenticate("petstore_auth") { - post { - val principal = call.authentication.principal() - - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - call.respond(HttpStatusCode.NotImplemented) - } - } - } + authenticate("petstore_auth") { + put { + val principal = call.authentication.principal()!! + + call.respond(HttpStatusCode.NotImplemented) + } } + authenticate("petstore_auth") { + post { + val principal = call.authentication.principal()!! + + call.respond(HttpStatusCode.NotImplemented) + } + } - route("/pet/{petId}/uploadImage") { - authenticate("petstore_auth") { - post { - val principal = call.authentication.principal() + authenticate("petstore_auth") { + post { + val principal = call.authentication.principal()!! + + val exampleContentType = "application/json" + val exampleContentString = """{ + "code" : 0, + "type" : "type", + "message" : "message" + }""" - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - val exampleContentType = "application/json" - val exampleContentString = """{ - "code" : 0, - "type" : "type", - "message" : "message" - }""" - - when(exampleContentType) { - "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) - "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) - else -> call.respondText(exampleContentString) - } - } - } + when (exampleContentType) { + "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) + "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) + else -> call.respondText(exampleContentString) } } + } } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt index 17b2c526bd9c..2e5f4ab8b96c 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt @@ -20,17 +20,18 @@ import io.ktor.auth.OAuthAccessTokenResponse import io.ktor.auth.OAuthServerSettings import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode -import io.ktor.locations.KtorExperimentalLocationsAPI -import io.ktor.locations.delete -import io.ktor.locations.get import io.ktor.response.respond import io.ktor.response.respondText import io.ktor.routing.Route -import io.ktor.routing.post -import io.ktor.routing.put -import io.ktor.routing.route - import org.openapitools.server.Paths +import io.ktor.locations.KtorExperimentalLocationsAPI +import io.ktor.locations.delete +import io.ktor.locations.get +import io.ktor.locations.post +import io.ktor.locations.put +import io.ktor.locations.options +import io.ktor.locations.head + import org.openapitools.server.infrastructure.ApiPrincipal @@ -40,24 +41,19 @@ import org.openapitools.server.models.Order fun Route.StoreApi() { val gson = Gson() val empty = mutableMapOf() - - delete { _: Paths.deleteOrder -> + delete { call.respond(HttpStatusCode.NotImplemented) } - - get { _: Paths.getInventory -> - val principal = call.authentication.principal() + authenticate("api_key") { + get { + val principal = call.authentication.principal()!! - if (principal == null) { - call.respond(HttpStatusCode.Unauthorized) - } else { - call.respond(HttpStatusCode.NotImplemented) - } + call.respond(HttpStatusCode.NotImplemented) + } } - - get { _: Paths.getOrderById -> + get { val exampleContentType = "application/json" val exampleContentString = """{ "petId" : 6, @@ -68,31 +64,28 @@ fun Route.StoreApi() { "status" : "placed" }""" - when(exampleContentType) { + when (exampleContentType) { "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } } - - route("/store/order") { - post { - val exampleContentType = "application/json" - val exampleContentString = """{ - "petId" : 6, - "quantity" : 1, - "id" : 0, - "shipDate" : "2000-01-23T04:56:07.000+00:00", - "complete" : false, - "status" : "placed" - }""" - - when(exampleContentType) { - "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) - "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) - else -> call.respondText(exampleContentString) - } + post { + val exampleContentType = "application/json" + val exampleContentString = """{ + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" + }""" + + when (exampleContentType) { + "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) + "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) + else -> call.respondText(exampleContentString) } } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/UserApi.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/UserApi.kt index 7fc0b78fa995..e248d75ae0cc 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/UserApi.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/UserApi.kt @@ -20,17 +20,18 @@ import io.ktor.auth.OAuthAccessTokenResponse import io.ktor.auth.OAuthServerSettings import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode -import io.ktor.locations.KtorExperimentalLocationsAPI -import io.ktor.locations.delete -import io.ktor.locations.get import io.ktor.response.respond import io.ktor.response.respondText import io.ktor.routing.Route -import io.ktor.routing.post -import io.ktor.routing.put -import io.ktor.routing.route - import org.openapitools.server.Paths +import io.ktor.locations.KtorExperimentalLocationsAPI +import io.ktor.locations.delete +import io.ktor.locations.get +import io.ktor.locations.post +import io.ktor.locations.put +import io.ktor.locations.options +import io.ktor.locations.head + import org.openapitools.server.infrastructure.ApiPrincipal @@ -40,34 +41,23 @@ import org.openapitools.server.models.User fun Route.UserApi() { val gson = Gson() val empty = mutableMapOf() - - route("/user") { - post { - call.respond(HttpStatusCode.NotImplemented) - } + post { + call.respond(HttpStatusCode.NotImplemented) } - - route("/user/createWithArray") { - post { - call.respond(HttpStatusCode.NotImplemented) - } + post { + call.respond(HttpStatusCode.NotImplemented) } - - route("/user/createWithList") { - post { - call.respond(HttpStatusCode.NotImplemented) - } + post { + call.respond(HttpStatusCode.NotImplemented) } - - delete { _: Paths.deleteUser -> + delete { call.respond(HttpStatusCode.NotImplemented) } - - get { _: Paths.getUserByName -> + get { val exampleContentType = "application/json" val exampleContentString = """{ "firstName" : "firstName", @@ -80,28 +70,23 @@ fun Route.UserApi() { "username" : "username" }""" - when(exampleContentType) { + when (exampleContentType) { "application/json" -> call.respond(gson.fromJson(exampleContentString, empty::class.java)) "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } } - - get { _: Paths.loginUser -> + get { call.respond(HttpStatusCode.NotImplemented) } - - get { _: Paths.logoutUser -> + get { call.respond(HttpStatusCode.NotImplemented) } - - route("/user/{username}") { - put { - call.respond(HttpStatusCode.NotImplemented) - } + put { + call.respond(HttpStatusCode.NotImplemented) } } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/infrastructure/ApiKeyAuth.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/infrastructure/ApiKeyAuth.kt index 8de972967ef3..de09ba8b6b62 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/infrastructure/ApiKeyAuth.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/infrastructure/ApiKeyAuth.kt @@ -1,85 +1,105 @@ package org.openapitools.server.infrastructure -import io.ktor.application.ApplicationCall -import io.ktor.application.call -import io.ktor.auth.Authentication -import io.ktor.auth.AuthenticationFailedCause -import io.ktor.auth.AuthenticationPipeline -import io.ktor.auth.AuthenticationProvider -import io.ktor.auth.Credential -import io.ktor.auth.Principal -import io.ktor.auth.UnauthorizedResponse -import io.ktor.http.auth.HeaderValueEncoding -import io.ktor.http.auth.HttpAuthHeader -import io.ktor.request.ApplicationRequest -import io.ktor.response.respond +import io.ktor.application.* +import io.ktor.auth.* +import io.ktor.http.auth.* +import io.ktor.request.* +import io.ktor.response.* enum class ApiKeyLocation(val location: String) { QUERY("query"), HEADER("header") } -data class ApiKeyCredential(val value: String): Credential -data class ApiPrincipal(val apiKeyCredential: ApiKeyCredential?) : Principal - +data class ApiKeyCredential(val value: String) : Credential +data class ApiPrincipal(val apiKeyCredential: ApiKeyCredential?) : Principal /** * Represents a Api Key authentication provider * @param name is the name of the provider, or `null` for a default provider */ -class ApiKeyAuthenticationProvider(name: String?) : AuthenticationProvider(name) { - internal var authenticationFunction: suspend ApplicationCall.(ApiKeyCredential) -> Principal? = { null } +class ApiKeyAuthenticationProvider(configuration: Configuration) : AuthenticationProvider(configuration) { - var apiKeyName: String = ""; + private val authenticationFunction = configuration.authenticationFunction - var apiKeyLocation: ApiKeyLocation = ApiKeyLocation.QUERY; + private val apiKeyName: String = configuration.apiKeyName - /** - * Sets a validation function that will check given [ApiKeyCredential] instance and return [Principal], - * or null if credential does not correspond to an authenticated principal - */ - fun validate(body: suspend ApplicationCall.(ApiKeyCredential) -> Principal?) { - authenticationFunction = body - } -} + private val apiKeyLocation: ApiKeyLocation = configuration.apiKeyLocation -fun Authentication.Configuration.apiKeyAuth(name: String? = null, configure: ApiKeyAuthenticationProvider.() -> Unit) { - val provider = ApiKeyAuthenticationProvider(name).apply(configure) - val apiKeyName = provider.apiKeyName - val apiKeyLocation = provider.apiKeyLocation - val authenticate = provider.authenticationFunction + internal fun install() { + pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context -> + val credentials = call.request.apiKeyAuthenticationCredentials(apiKeyName, apiKeyLocation) + val principal = credentials?.let { authenticationFunction(call, it) } - provider.pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context -> - val credentials = call.request.apiKeyAuthenticationCredentials(apiKeyName, apiKeyLocation) - val principal = credentials?.let { authenticate(call, it) } + val cause = when { + credentials == null -> AuthenticationFailedCause.NoCredentials + principal == null -> AuthenticationFailedCause.InvalidCredentials + else -> null + } - val cause = when { - credentials == null -> AuthenticationFailedCause.NoCredentials - principal == null -> AuthenticationFailedCause.InvalidCredentials - else -> null - } + if (cause != null) { + context.challenge(apiKeyName, cause) { + call.respond( + UnauthorizedResponse( + HttpAuthHeader.Parameterized( + "API_KEY", + mapOf("key" to apiKeyName), + HeaderValueEncoding.QUOTED_ALWAYS + ) + ) + ) + it.complete() + } + } - if (cause != null) { - context.challenge(apiKeyName, cause) { - // TODO: Verify correct response structure here. - call.respond(UnauthorizedResponse(HttpAuthHeader.Parameterized("API_KEY", mapOf("key" to apiKeyName), HeaderValueEncoding.QUOTED_ALWAYS))) - it.complete() + if (principal != null) { + context.principal(principal) } } + } + + class Configuration internal constructor(name: String?) : AuthenticationProvider.Configuration(name) { + + internal var authenticationFunction: suspend ApplicationCall.(ApiKeyCredential) -> Principal? = { + throw NotImplementedError( + "Api Key auth validate function is not specified. Use apiKeyAuth { validate { ... } } to fix." + ) + } - if (principal != null) { - context.principal(principal) + var apiKeyName: String = "" + + var apiKeyLocation: ApiKeyLocation = ApiKeyLocation.QUERY + + /** + * Sets a validation function that will check given [ApiKeyCredential] instance and return [Principal], + * or null if credential does not correspond to an authenticated principal + */ + fun validate(body: suspend ApplicationCall.(ApiKeyCredential) -> Principal?) { + authenticationFunction = body } } } -fun ApplicationRequest.apiKeyAuthenticationCredentials(apiKeyName: String, apiKeyLocation: ApiKeyLocation): ApiKeyCredential? { - val value: String? = when(apiKeyLocation) { +fun Authentication.Configuration.apiKeyAuth( + name: String? = null, + configure: ApiKeyAuthenticationProvider.Configuration.() -> Unit +) { + val configuration = ApiKeyAuthenticationProvider.Configuration(name).apply(configure) + val provider = ApiKeyAuthenticationProvider(configuration) + provider.install() + register(provider) +} + +fun ApplicationRequest.apiKeyAuthenticationCredentials( + apiKeyName: String, + apiKeyLocation: ApiKeyLocation +): ApiKeyCredential? { + val value: String? = when (apiKeyLocation) { ApiKeyLocation.QUERY -> this.queryParameters[apiKeyName] ApiKeyLocation.HEADER -> this.headers[apiKeyName] } - when (value) { - null -> return null - else -> return ApiKeyCredential(value) + return when (value) { + null -> null + else -> ApiKeyCredential(value) } } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/ApiResponse.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/ApiResponse.kt index 457607909909..14f50dbb9ad6 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/ApiResponse.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/ApiResponse.kt @@ -19,7 +19,7 @@ import java.io.Serializable * @param type * @param message */ -data class ApiResponse ( +data class ApiResponse( val code: kotlin.Int? = null, val type: kotlin.String? = null, val message: kotlin.String? = null diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Category.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Category.kt index ee26d4c76e50..9d8571921384 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Category.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Category.kt @@ -18,7 +18,7 @@ import java.io.Serializable * @param id * @param name */ -data class Category ( +data class Category( val id: kotlin.Long? = null, val name: kotlin.String? = null ) : Serializable diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Order.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Order.kt index 7889abe12ee2..5e9e18b0328c 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Order.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Order.kt @@ -22,7 +22,7 @@ import java.io.Serializable * @param status Order Status * @param complete */ -data class Order ( +data class Order( val id: kotlin.Long? = null, val petId: kotlin.Long? = null, val quantity: kotlin.Int? = null, diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Pet.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Pet.kt index 8dc13b7ea6e2..8b98ce0469c5 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Pet.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Pet.kt @@ -24,12 +24,12 @@ import java.io.Serializable * @param tags * @param status pet status in the store */ -data class Pet ( +data class Pet( val name: kotlin.String, - val photoUrls: kotlin.Array, + val photoUrls: kotlin.collections.List, val id: kotlin.Long? = null, val category: Category? = null, - val tags: kotlin.Array? = null, + val tags: kotlin.collections.List? = null, /* pet status in the store */ val status: Pet.Status? = null ) : Serializable diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Tag.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Tag.kt index 49c2887a5039..e9626b25c6d1 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Tag.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/Tag.kt @@ -18,7 +18,7 @@ import java.io.Serializable * @param id * @param name */ -data class Tag ( +data class Tag( val id: kotlin.Long? = null, val name: kotlin.String? = null ) : Serializable diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/User.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/User.kt index dee8de740bde..fdbdb4e1cff4 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/User.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/User.kt @@ -24,7 +24,7 @@ import java.io.Serializable * @param phone * @param userStatus User Status */ -data class User ( +data class User( val id: kotlin.Long? = null, val username: kotlin.String? = null, val firstName: kotlin.String? = null, diff --git a/samples/server/petstore/kotlin-springboot-delegate/.openapi-generator/VERSION b/samples/server/petstore/kotlin-springboot-delegate/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/kotlin-springboot-delegate/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-springboot-delegate/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/PetApi.kt b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/PetApi.kt index 62837ade76f9..2880b39b990d 100644 --- a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/PetApi.kt +++ b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/PetApi.kt @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/StoreApi.kt b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/StoreApi.kt index 15cc95c4d7b9..14a9d0fa525d 100644 --- a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/StoreApi.kt +++ b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/StoreApi.kt @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/UserApi.kt b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/UserApi.kt index 7c42d4ae283e..233a3bb1a5f2 100644 --- a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/UserApi.kt +++ b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/UserApi.kt @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/kotlin-springboot-reactive/.openapi-generator/VERSION b/samples/server/petstore/kotlin-springboot-reactive/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/kotlin-springboot-reactive/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-springboot-reactive/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-springboot/.openapi-generator/VERSION b/samples/server/petstore/kotlin-springboot/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/kotlin-springboot/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-springboot/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/php-laravel/.openapi-generator/VERSION b/samples/server/petstore/php-laravel/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/php-laravel/.openapi-generator/VERSION +++ b/samples/server/petstore/php-laravel/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/php-laravel/lib/app/Http/Controllers/FakeController.php b/samples/server/petstore/php-laravel/lib/app/Http/Controllers/FakeController.php index cb3da629aaa5..a0b1238d92ef 100644 --- a/samples/server/petstore/php-laravel/lib/app/Http/Controllers/FakeController.php +++ b/samples/server/petstore/php-laravel/lib/app/Http/Controllers/FakeController.php @@ -228,6 +228,30 @@ public function testGroupParameters() return response('How about implementing testGroupParameters as a delete method ?'); } + /** + * Operation testBodyWithBinary + * + * . + * + * + * @return Http response + */ + public function testBodyWithBinary() + { + $input = Request::all(); + + //path params validation + + + //not path params validation + if (!isset($input['body'])) { + throw new \InvalidArgumentException('Missing the required parameter $body when calling testBodyWithBinary'); + } + $body = $input['body']; + + + return response('How about implementing testBodyWithBinary as a put method ?'); + } /** * Operation testBodyWithFileSchema * diff --git a/samples/server/petstore/php-laravel/lib/routes/api.php b/samples/server/petstore/php-laravel/lib/routes/api.php index 856cc66810a1..fec2cea4a3c1 100644 --- a/samples/server/petstore/php-laravel/lib/routes/api.php +++ b/samples/server/petstore/php-laravel/lib/routes/api.php @@ -63,10 +63,17 @@ */ Route::delete('/v2/fake', 'FakeController@testGroupParameters'); +/** + * put testBodyWithBinary + * Summary: + * Notes: For this test, the body has to be a binary file. + + */ +Route::put('/v2/fake/body-with-binary', 'FakeController@testBodyWithBinary'); /** * put testBodyWithFileSchema * Summary: - * Notes: For this test, the body for this request much reference a schema named `File`. + * Notes: For this test, the body for this request must reference a schema named `File`. */ Route::put('/v2/fake/body-with-file-schema', 'FakeController@testBodyWithFileSchema'); diff --git a/samples/server/petstore/php-lumen/.openapi-generator/VERSION b/samples/server/petstore/php-lumen/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/php-lumen/.openapi-generator/VERSION +++ b/samples/server/petstore/php-lumen/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/php-lumen/lib/app/Http/Controllers/FakeApi.php b/samples/server/petstore/php-lumen/lib/app/Http/Controllers/FakeApi.php index 86e5ae7356fe..e3b631dd0979 100644 --- a/samples/server/petstore/php-lumen/lib/app/Http/Controllers/FakeApi.php +++ b/samples/server/petstore/php-lumen/lib/app/Http/Controllers/FakeApi.php @@ -224,6 +224,30 @@ public function testGroupParameters() return response('How about implementing testGroupParameters as a delete method ?'); } + /** + * Operation testBodyWithBinary + * + * . + * + * + * @return Http response + */ + public function testBodyWithBinary() + { + $input = Request::all(); + + //path params validation + + + //not path params validation + if (!isset($input['body'])) { + throw new \InvalidArgumentException('Missing the required parameter $body when calling testBodyWithBinary'); + } + $body = $input['body']; + + + return response('How about implementing testBodyWithBinary as a put method ?'); + } /** * Operation testBodyWithFileSchema * diff --git a/samples/server/petstore/php-lumen/lib/routes/web.php b/samples/server/petstore/php-lumen/lib/routes/web.php index f159b8da780b..9831967079fc 100644 --- a/samples/server/petstore/php-lumen/lib/routes/web.php +++ b/samples/server/petstore/php-lumen/lib/routes/web.php @@ -79,10 +79,17 @@ */ $router->delete('/v2/fake', 'FakeApi@testGroupParameters'); +/** + * put testBodyWithBinary + * Summary: + * Notes: For this test, the body has to be a binary file. + */ +$router->put('/v2/fake/body-with-binary', 'FakeApi@testBodyWithBinary'); + /** * put testBodyWithFileSchema * Summary: - * Notes: For this test, the body for this request much reference a schema named `File`. + * Notes: For this test, the body for this request must reference a schema named `File`. */ $router->put('/v2/fake/body-with-file-schema', 'FakeApi@testBodyWithFileSchema'); diff --git a/samples/server/petstore/php-mezzio-ph-modern/.gitignore b/samples/server/petstore/php-mezzio-ph-modern/.gitignore new file mode 100644 index 000000000000..1ddcdf2a7099 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/.gitignore @@ -0,0 +1,9 @@ +#based on .gitignore generated by https://github.com/zendframework/zend-expressive-skeleton +.idea + +# Composer files +composer.phar +vendor/ + +# Default cache folder +data/cache/ diff --git a/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator-ignore b/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator/FILES b/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator/FILES new file mode 100644 index 000000000000..bc9a68917b63 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator/FILES @@ -0,0 +1,71 @@ +.gitignore +README.md +application/config.yml +application/config/app.yml +application/config/data_transfer.yml +application/config/path_handler.yml +application/container.php +composer.json +public/index.php +src/App/DTO/ApiResponse.php +src/App/DTO/Category.php +src/App/DTO/Collection.php +src/App/DTO/Collection1.php +src/App/DTO/Collection10.php +src/App/DTO/Collection11.php +src/App/DTO/Collection12.php +src/App/DTO/Collection13.php +src/App/DTO/Collection14.php +src/App/DTO/Collection15.php +src/App/DTO/Collection16.php +src/App/DTO/Collection17.php +src/App/DTO/Collection18.php +src/App/DTO/Collection19.php +src/App/DTO/Collection2.php +src/App/DTO/Collection20.php +src/App/DTO/Collection21.php +src/App/DTO/Collection22.php +src/App/DTO/Collection23.php +src/App/DTO/Collection24.php +src/App/DTO/Collection25.php +src/App/DTO/Collection26.php +src/App/DTO/Collection27.php +src/App/DTO/Collection28.php +src/App/DTO/Collection29.php +src/App/DTO/Collection3.php +src/App/DTO/Collection30.php +src/App/DTO/Collection31.php +src/App/DTO/Collection32.php +src/App/DTO/Collection33.php +src/App/DTO/Collection34.php +src/App/DTO/Collection35.php +src/App/DTO/Collection36.php +src/App/DTO/Collection4.php +src/App/DTO/Collection5.php +src/App/DTO/Collection6.php +src/App/DTO/Collection7.php +src/App/DTO/Collection8.php +src/App/DTO/Collection9.php +src/App/DTO/FindPetsByStatusQueryData.php +src/App/DTO/FindPetsByTagsQueryData.php +src/App/DTO/LoginUserQueryData.php +src/App/DTO/Order.php +src/App/DTO/Pet.php +src/App/DTO/Tag.php +src/App/DTO/User.php +src/App/Factory.php +src/App/Handler/Pet.php +src/App/Handler/PetFindByStatus.php +src/App/Handler/PetFindByTags.php +src/App/Handler/PetPetId.php +src/App/Handler/PetPetIdUploadImage.php +src/App/Handler/StoreInventory.php +src/App/Handler/StoreOrder.php +src/App/Handler/StoreOrderOrderId.php +src/App/Handler/User.php +src/App/Handler/UserCreateWithArray.php +src/App/Handler/UserCreateWithList.php +src/App/Handler/UserLogin.php +src/App/Handler/UserLogout.php +src/App/Handler/UserUsername.php +src/App/Middleware/InternalServerError.php diff --git a/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator/VERSION b/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator/VERSION new file mode 100644 index 000000000000..6555596f9311 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/README.md b/samples/server/petstore/php-mezzio-ph-modern/README.md similarity index 93% rename from samples/openapi3/server/petstore/php-mezzio-ph/README.md rename to samples/server/petstore/php-mezzio-ph-modern/README.md index 584fd1568795..fd66369b261a 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/README.md +++ b/samples/server/petstore/php-mezzio-ph-modern/README.md @@ -5,9 +5,9 @@ Generated by the [OpenAPI Generator](https://openapi-generator.tech) project. ## Overview This server stub aims to provide light, yet comprehensive structure for your API project using: -- PHP: >=7.2 -- [Laminas Mezzio](https://docs.mezzio.dev/mezzio/): >=3.2 -- [Path Handler](https://github.com/Articus/PathHandler): >=0.6 +- PHP: >=8.0 +- [Laminas Mezzio](https://docs.mezzio.dev/mezzio/): >=3.3 +- [Path Handler](https://github.com/Articus/PathHandler): >=0.7 ## How to use All you have to do to start development is: diff --git a/samples/server/petstore/php-mezzio-ph-modern/application/config.yml b/samples/server/petstore/php-mezzio-ph-modern/application/config.yml new file mode 100644 index 000000000000..58056552c5bc --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/application/config.yml @@ -0,0 +1,21 @@ +#Empty configuration placeholder, remove when you add any real configuration settings to this file +{} + +#Enable configuration cache +#cache_configuration: true + +#Articus\PathHandler\RouteInjection\Factory: +# #Enable routing table cache +# router: +# cache: +# directory: ./data/cache/PathHandler + +#Enable handler metadata cache +#Articus\PathHandler\MetadataProvider\PhpAttribute: +# cache: +# directory: ./data/cache/PathHandler + +#Enable data transfer metadata cache for DTOs +#Articus\DataTransfer\MetadataProvider\PhpAttribute: +# cache: +# directory: ./data/cache/DataTransfer diff --git a/samples/server/petstore/php-mezzio-ph-modern/application/config/app.yml b/samples/server/petstore/php-mezzio-ph-modern/application/config/app.yml new file mode 100644 index 000000000000..0ffd5e8864cf --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/application/config/app.yml @@ -0,0 +1,22 @@ +dependencies: + invokables: + Laminas\HttpHandlerRunner\Emitter\EmitterInterface: Laminas\HttpHandlerRunner\Emitter\SapiStreamEmitter + factories: + Mezzio\Application: App\Factory + Mezzio\MiddlewareContainer: Mezzio\Container\MiddlewareContainerFactory + Mezzio\MiddlewareFactory: Mezzio\Container\MiddlewareFactoryFactory + Mezzio\Router\RouteCollector: Mezzio\Router\RouteCollectorFactory + + Psr\Http\Message\ServerRequestInterface: Mezzio\Container\ServerRequestFactoryFactory + Psr\Http\Message\StreamInterface: Mezzio\Container\StreamFactoryFactory + Psr\Http\Message\ResponseInterface: Mezzio\Container\ResponseFactoryFactory + + App\Middleware\InternalServerError: Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory + Mezzio\Router\Middleware\RouteMiddleware: Mezzio\Router\Middleware\RouteMiddlewareFactory + Mezzio\Router\Middleware\DispatchMiddleware: Mezzio\Router\Middleware\DispatchMiddlewareFactory + Mezzio\Router\Middleware\MethodNotAllowedMiddleware: Mezzio\Router\Middleware\MethodNotAllowedMiddlewareFactory + Mezzio\Handler\NotFoundHandler: Mezzio\Container\NotFoundHandlerFactory + +Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory: + App\Middleware\InternalServerError: + - Psr\Http\Message\ResponseInterface diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/application/config/data_transfer.yml b/samples/server/petstore/php-mezzio-ph-modern/application/config/data_transfer.yml similarity index 69% rename from samples/openapi3/server/petstore/php-mezzio-ph/application/config/data_transfer.yml rename to samples/server/petstore/php-mezzio-ph-modern/application/config/data_transfer.yml index c5174147c236..7bdd139bb9ff 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/application/config/data_transfer.yml +++ b/samples/server/petstore/php-mezzio-ph-modern/application/config/data_transfer.yml @@ -1,13 +1,13 @@ dependencies: factories: Articus\DataTransfer\Service: Articus\DataTransfer\Factory - Articus\DataTransfer\MetadataProvider\Annotation: Articus\DataTransfer\MetadataProvider\Factory\Annotation + Articus\DataTransfer\MetadataProvider\PhpAttribute: Articus\DataTransfer\MetadataProvider\Factory\PhpAttribute Articus\DataTransfer\Strategy\PluginManager: Articus\DataTransfer\Strategy\Factory\PluginManager Articus\DataTransfer\Validator\PluginManager: Articus\DataTransfer\Validator\Factory\PluginManager Laminas\Validator\ValidatorPluginManager: Laminas\Validator\ValidatorPluginManagerFactory aliases: - Articus\DataTransfer\ClassMetadataProviderInterface: Articus\DataTransfer\MetadataProvider\Annotation - Articus\DataTransfer\FieldMetadataProviderInterface: Articus\DataTransfer\MetadataProvider\Annotation + Articus\DataTransfer\ClassMetadataProviderInterface: Articus\DataTransfer\MetadataProvider\PhpAttribute + Articus\DataTransfer\FieldMetadataProviderInterface: Articus\DataTransfer\MetadataProvider\PhpAttribute Articus\DataTransfer\Strategy\PluginManager: invokables: @@ -16,6 +16,10 @@ Articus\DataTransfer\Strategy\PluginManager: factories: Date: OpenAPIGenerator\Common\Strategy\Factory\MutableDate DateTime: OpenAPIGenerator\Common\Strategy\Factory\MutableDateTime + ObjectList: OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectList + ObjectMap: OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectMap + ScalarList: OpenAPIGenerator\Common\Strategy\Factory\ScalarList + ScalarMap: OpenAPIGenerator\Common\Strategy\Factory\ScalarMap Articus\DataTransfer\Validator\PluginManager: invokables: @@ -24,3 +28,7 @@ Articus\DataTransfer\Validator\PluginManager: QueryStringScalarArray: OpenAPIGenerator\Common\Validator\QueryStringScalarArray abstract_factories: - Articus\DataTransfer\Validator\Factory\Laminas + +validators: + invokables: + Count: Laminas\Validator\IsCountable diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/application/config/path_handler.yml b/samples/server/petstore/php-mezzio-ph-modern/application/config/path_handler.yml similarity index 53% rename from samples/openapi3/server/petstore/php-mezzio-ph/application/config/path_handler.yml rename to samples/server/petstore/php-mezzio-ph-modern/application/config/path_handler.yml index 25995b20d6f6..eb46b1891a37 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/application/config/path_handler.yml +++ b/samples/server/petstore/php-mezzio-ph-modern/application/config/path_handler.yml @@ -1,8 +1,13 @@ dependencies: factories: - Mezzio\Router\RouterInterface: Articus\PathHandler\RouteInjection\Factory + Mezzio\Router\RouterInterface: Articus\PathHandler\RouteInjectionFactory + Articus\PathHandler\MetadataProviderInterface: Articus\PathHandler\MetadataProvider\Factory\PhpAttribute + Articus\PathHandler\Handler\PluginManager: Articus\PathHandler\Handler\Factory\PluginManager + Articus\PathHandler\Consumer\PluginManager: Articus\PathHandler\Consumer\Factory\PluginManager + Articus\PathHandler\Attribute\PluginManager: Articus\PathHandler\Attribute\Factory\PluginManager + Articus\PathHandler\Producer\PluginManager: Articus\PathHandler\Producer\Factory\PluginManager -Articus\PathHandler\RouteInjection\Factory: +Articus\PathHandler\RouteInjectionFactory: paths: '/v2': - App\Handler\Pet @@ -19,18 +24,22 @@ Articus\PathHandler\RouteInjection\Factory: - App\Handler\UserLogin - App\Handler\UserLogout - App\Handler\UserUsername - handlers: - abstract_factories: - - Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory -# consumers: -# factories: -# invokables: -# attributes: -# factories: -# invokables: -# producers: -# factories: -# invokables: + +Articus\PathHandler\Handler\PluginManager: + abstract_factories: + - Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory + +#Articus\PathHandler\Consumer\PluginManager: +# factories: +# invokables: + +#Articus\PathHandler\Attribute\PluginManager: +# factories: +# invokables: + +#Articus\PathHandler\Producer\PluginManager: +# factories: +# invokables: Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory: App\Handler\Pet: [] diff --git a/samples/server/petstore/php-mezzio-ph-modern/application/container.php b/samples/server/petstore/php-mezzio-ph-modern/application/container.php new file mode 100644 index 000000000000..9c54fafcfec7 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/application/container.php @@ -0,0 +1,43 @@ +setService('config', $config); +$container->setAlias('Config', 'config'); + +return $container; diff --git a/samples/server/petstore/php-mezzio-ph-modern/composer.json b/samples/server/petstore/php-mezzio-ph-modern/composer.json new file mode 100644 index 000000000000..7f03f079e4af --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/composer.json @@ -0,0 +1,26 @@ +{ + "name": "git_user_id/git_repo_id", + "description": "", + "license": "unlicense", + "version": "1.0.0", + "type": "project", + "require": { + "php": "^8.0", + "ext-yaml": "^2.2", + "mezzio/mezzio": "^3.3", + "laminas/laminas-diactoros": "^2.5", + "articus/path-handler": "^0.7", + "articus/data-transfer": "^0.5", + "articus/openapi-generator-common": "^0.2", + "psr/simple-cache": "^1.0", + "laminas/laminas-config": "^3.4", + "laminas/laminas-stdlib": "^3.3", + "laminas/laminas-validator": "^2.14", + "nikic/fast-route": "^1.3" + }, + "autoload": { + "psr-4": { + "": "src/" + } + } +} \ No newline at end of file diff --git a/samples/server/petstore/php-mezzio-ph-modern/public/index.php b/samples/server/petstore/php-mezzio-ph-modern/public/index.php new file mode 100644 index 000000000000..7c3de73df161 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/public/index.php @@ -0,0 +1,11 @@ +get(\Mezzio\Application::class); +$app->run(); diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/ApiResponse.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/ApiResponse.php new file mode 100644 index 000000000000..bfe65906ea50 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/ApiResponse.php @@ -0,0 +1,25 @@ + "int"])] + public int|null $code = null; + + #[DTA\Data(field: "type", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $type = null; + + #[DTA\Data(field: "message", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $message = null; + +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Category.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Category.php new file mode 100644 index 000000000000..e6b28c29028e --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Category.php @@ -0,0 +1,22 @@ + "int"])] + public int|null $id = null; + + #[DTA\Data(field: "name", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + #[DTA\Validator("Regex", ["pattern" => "/^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$/"])] + public string|null $name = null; + +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection.php new file mode 100644 index 000000000000..f0e14da6cd80 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection1.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection1.php new file mode 100644 index 000000000000..c05da2858bd8 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection1.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection1 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection10.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection10.php new file mode 100644 index 000000000000..29e6ccdb3472 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection10.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection10 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection11.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection11.php new file mode 100644 index 000000000000..89b2d0d01f8a --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection11.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection11 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection12.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection12.php new file mode 100644 index 000000000000..e0657b0d467f --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection12.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection12 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection13.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection13.php new file mode 100644 index 000000000000..26f88d9685dd --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection13.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection13 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection14.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection14.php new file mode 100644 index 000000000000..d1e0e11495b3 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection14.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection14 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection15.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection15.php new file mode 100644 index 000000000000..085f17e1e972 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection15.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection15 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection16.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection16.php new file mode 100644 index 000000000000..1b1523c7d09b --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection16.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection16 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection17.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection17.php new file mode 100644 index 000000000000..eb5b0e828f8d --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection17.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection17 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection18.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection18.php new file mode 100644 index 000000000000..dd55bd5840a7 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection18.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection18 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection19.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection19.php new file mode 100644 index 000000000000..45da36c73017 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection19.php @@ -0,0 +1,14 @@ + \App\DTO\Pet::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Pet::class]] +]])] +class Collection19 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection2.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection2.php new file mode 100644 index 000000000000..26176dcc5e59 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection2.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection2 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection20.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection20.php new file mode 100644 index 000000000000..26b16ef104e3 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection20.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection20 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection21.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection21.php new file mode 100644 index 000000000000..9e0c2429bde1 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection21.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection21 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection22.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection22.php new file mode 100644 index 000000000000..6f7a04ff4bd9 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection22.php @@ -0,0 +1,14 @@ + \App\DTO\Pet::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Pet::class]] +]])] +class Collection22 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection23.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection23.php new file mode 100644 index 000000000000..608c9ad50206 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection23.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection23 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection24.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection24.php new file mode 100644 index 000000000000..b876816c2ddb --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection24.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection24 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection25.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection25.php new file mode 100644 index 000000000000..ad3a8102ad3e --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection25.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection25 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection26.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection26.php new file mode 100644 index 000000000000..f8e958fcb402 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection26.php @@ -0,0 +1,14 @@ + \App\DTO\Pet::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Pet::class]] +]])] +class Collection26 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection27.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection27.php new file mode 100644 index 000000000000..b53e9e87a729 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection27.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection27 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection28.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection28.php new file mode 100644 index 000000000000..3b6e05419ef1 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection28.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection28 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection29.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection29.php new file mode 100644 index 000000000000..24a1ee261d86 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection29.php @@ -0,0 +1,14 @@ + \App\DTO\Pet::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Pet::class]] +]])] +class Collection29 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection3.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection3.php new file mode 100644 index 000000000000..1833307cd7e6 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection3.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection3 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection30.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection30.php new file mode 100644 index 000000000000..916229afc92b --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection30.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection30 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection31.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection31.php new file mode 100644 index 000000000000..12b771c1c16a --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection31.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection31 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection32.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection32.php new file mode 100644 index 000000000000..e89cbcd4397a --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection32.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection32 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection33.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection33.php new file mode 100644 index 000000000000..91229b175cfc --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection33.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection33 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection34.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection34.php new file mode 100644 index 000000000000..1670c4ee7e3d --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection34.php @@ -0,0 +1,14 @@ + "int"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "int"]] +]])] +class Collection34 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection35.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection35.php new file mode 100644 index 000000000000..4b1082abc1b1 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection35.php @@ -0,0 +1,14 @@ + \App\DTO\User::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\User::class]] +]])] +class Collection35 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection36.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection36.php new file mode 100644 index 000000000000..38595c2f5d39 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection36.php @@ -0,0 +1,14 @@ + \App\DTO\User::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\User::class]] +]])] +class Collection36 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection4.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection4.php new file mode 100644 index 000000000000..54e2f1a12de5 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection4.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection4 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection5.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection5.php new file mode 100644 index 000000000000..3f32f4513a74 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection5.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection5 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection6.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection6.php new file mode 100644 index 000000000000..79abc43f3398 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection6.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection6 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection7.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection7.php new file mode 100644 index 000000000000..8574d82b3658 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection7.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection7 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection8.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection8.php new file mode 100644 index 000000000000..c264d8076a1f --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection8.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection8 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection9.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection9.php new file mode 100644 index 000000000000..99cc837d6a59 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection9.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection9 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/FindPetsByStatusQueryData.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/FindPetsByStatusQueryData.php new file mode 100644 index 000000000000..178b4949794b --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/FindPetsByStatusQueryData.php @@ -0,0 +1,21 @@ + "string", "format" => "csv"])] + #[DTA\Validator("QueryStringScalarArray", ["type" => "string", "format" => "csv"])] + public array|null $status = null; + +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/FindPetsByTagsQueryData.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/FindPetsByTagsQueryData.php new file mode 100644 index 000000000000..cbf9e1d0c39b --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/FindPetsByTagsQueryData.php @@ -0,0 +1,21 @@ + "string", "format" => "csv"])] + #[DTA\Validator("QueryStringScalarArray", ["type" => "string", "format" => "csv"])] + public array|null $tags = null; + +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/LoginUserQueryData.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/LoginUserQueryData.php new file mode 100644 index 000000000000..2c01e944c918 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/LoginUserQueryData.php @@ -0,0 +1,30 @@ + "string"])] + #[DTA\Validator("QueryStringScalar", ["type" => "string"])] + public string|null $password = null; + + /** + * The user name for login + */ + #[DTA\Data(field: "username")] + #[DTA\Strategy("QueryStringScalar", ["type" => "string"])] + #[DTA\Validator("QueryStringScalar", ["type" => "string"])] + #[DTA\Validator("Regex", ["pattern" => "/^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$/"])] + public string|null $username = null; + +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Order.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Order.php new file mode 100644 index 000000000000..8dd384b4475d --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Order.php @@ -0,0 +1,41 @@ + "int"])] + public int|null $id = null; + + #[DTA\Data(field: "petId", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "int"])] + public int|null $pet_id = null; + + #[DTA\Data(field: "quantity", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "int"])] + public int|null $quantity = null; + + #[DTA\Data(field: "shipDate", nullable: true)] + #[DTA\Strategy("DateTime")] + #[DTA\Validator("Date", ["format" => \DateTime::RFC3339])] + public \DateTime|null $ship_date = null; + + /** + * Order Status + */ + #[DTA\Data(field: "status", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $status = null; + + #[DTA\Data(field: "complete", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "bool"])] + public bool|null $complete = null; + +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Pet.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Pet.php new file mode 100644 index 000000000000..bcd5cdb6e813 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Pet.php @@ -0,0 +1,43 @@ + "int"])] + public int|null $id = null; + + #[DTA\Data(field: "category", nullable: true)] + #[DTA\Strategy("Object", ["type" => \App\DTO\Category::class])] + #[DTA\Validator("TypeCompliant", ["type" => \App\DTO\Category::class])] + public \App\DTO\Category|null $category = null; + + #[DTA\Data(field: "name")] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $name = null; + + #[DTA\Data(field: "photoUrls")] + #[DTA\Strategy("Object", ["type" => \App\DTO\Collection32::class])] + #[DTA\Validator("TypeCompliant", ["type" => \App\DTO\Collection32::class])] + public \App\DTO\Collection32|null $photo_urls = null; + + #[DTA\Data(field: "tags", nullable: true)] + #[DTA\Strategy("Object", ["type" => \App\DTO\Collection33::class])] + #[DTA\Validator("TypeCompliant", ["type" => \App\DTO\Collection33::class])] + public \App\DTO\Collection33|null $tags = null; + + /** + * pet status in the store + */ + #[DTA\Data(field: "status", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $status = null; + +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Tag.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Tag.php new file mode 100644 index 000000000000..5fcc6c116b03 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Tag.php @@ -0,0 +1,21 @@ + "int"])] + public int|null $id = null; + + #[DTA\Data(field: "name", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $name = null; + +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/User.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/User.php new file mode 100644 index 000000000000..c257dfea3192 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/User.php @@ -0,0 +1,48 @@ + "int"])] + public int|null $id = null; + + #[DTA\Data(field: "username", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $username = null; + + #[DTA\Data(field: "firstName", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $first_name = null; + + #[DTA\Data(field: "lastName", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $last_name = null; + + #[DTA\Data(field: "email", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $email = null; + + #[DTA\Data(field: "password", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $password = null; + + #[DTA\Data(field: "phone", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $phone = null; + + /** + * User Status + */ + #[DTA\Data(field: "userStatus", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "int"])] + public int|null $user_status = null; + +} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Factory.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Factory.php similarity index 71% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Factory.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Factory.php index 0757bcfbea74..24eb21b492c0 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Factory.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Factory.php @@ -23,23 +23,13 @@ class Factory implements FactoryInterface { public function __invoke(ContainerInterface $container, $requestedName, array $options = null): Application { - $errorMiddleware = $container->get(Middleware\InternalServerError::class); - if (!($errorMiddleware instanceof Middleware\InternalServerError)) { - throw new \LogicException(\sprintf( - 'Invalid error middleware: expecting %s, not %s.', - Middleware\InternalServerError::class, - \is_object($errorMiddleware) ? \get_class($errorMiddleware) : \gettype($errorMiddleware) - )); - } + $errorMiddleware = self::getErrorMiddleware($container); $pipeline = new MiddlewarePipe(); $runner = new RequestHandlerRunner( $pipeline, $container->get(EmitterInterface::class), $container->get(ServerRequestInterface::class), - function(\Throwable $error) use ($errorMiddleware) : ResponseInterface - { - return $errorMiddleware->handleError($error); - } + static fn(\Throwable $error): ResponseInterface => $errorMiddleware->handleError($error) ); $application = new Application( $container->get(MiddlewareFactory::class), @@ -55,4 +45,9 @@ function(\Throwable $error) use ($errorMiddleware) : ResponseInterface return $application; } + + protected static function getErrorMiddleware(ContainerInterface $container): Middleware\InternalServerError + { + return $container->get(Middleware\InternalServerError::class); + } } diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/Pet.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/Pet.php new file mode 100644 index 000000000000..625b36f693a3 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/Pet.php @@ -0,0 +1,56 @@ + \App\DTO\Pet::class, "objectAttr" => "bodyData"])] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] + public function addPet(ServerRequestInterface $request): \App\DTO\Pet + { + //TODO implement method + /** @var \App\DTO\Pet $bodyData */ + $bodyData = $request->getAttribute("bodyData"); + throw new PHException\HttpCode(501, "Not implemented"); + } + /** + * Update an existing pet + */ + #[PHA\Put()] + // TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Consumer("application/json", PHConsumer\Json::class)] + // TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Consumer("application/xml", PHConsumer\Json::class)] + #[PHA\Attribute(PHAttribute\Transfer::class, ["type" => \App\DTO\Pet::class, "objectAttr" => "bodyData"])] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] + public function updatePet(ServerRequestInterface $request): \App\DTO\Pet + { + //TODO implement method + /** @var \App\DTO\Pet $bodyData */ + $bodyData = $request->getAttribute("bodyData"); + throw new PHException\HttpCode(501, "Not implemented"); + } +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetFindByStatus.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetFindByStatus.php new file mode 100644 index 000000000000..53d217f9969a --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetFindByStatus.php @@ -0,0 +1,36 @@ + \App\DTO\FindPetsByStatusQueryData::class, + "objectAttr" => "queryData", + "source" => PHAttribute\Transfer::SOURCE_GET + ])] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] + public function findPetsByStatus(ServerRequestInterface $request): \App\DTO\Collection19 + { + //TODO implement method + /** @var \App\DTO\FindPetsByStatusQueryData $queryData */ + $queryData = $request->getAttribute("queryData"); + throw new PHException\HttpCode(501, "Not implemented"); + } +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetFindByTags.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetFindByTags.php new file mode 100644 index 000000000000..a40122909bcb --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetFindByTags.php @@ -0,0 +1,36 @@ + \App\DTO\FindPetsByTagsQueryData::class, + "objectAttr" => "queryData", + "source" => PHAttribute\Transfer::SOURCE_GET + ])] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] + public function findPetsByTags(ServerRequestInterface $request): \App\DTO\Collection26 + { + //TODO implement method + /** @var \App\DTO\FindPetsByTagsQueryData $queryData */ + $queryData = $request->getAttribute("queryData"); + throw new PHException\HttpCode(501, "Not implemented"); + } +} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetPetId.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetPetId.php similarity index 55% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetPetId.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetPetId.php index 625bbf5832c3..8da421be6782 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetPetId.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetPetId.php @@ -3,25 +3,20 @@ namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/pet/{petId}") - */ +#[PHA\Route("/pet/{petId}")] class PetPetId { /** * Deletes a pet - * @PHA\Delete() - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Delete()] public function deletePet(ServerRequestInterface $request) { //TODO implement method @@ -29,17 +24,12 @@ public function deletePet(ServerRequestInterface $request) } /** * Find pet by ID - * @PHA\Get() - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/xml") - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/json") - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented - * - * @return \App\DTO\Pet */ + #[PHA\Get()] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] public function getPetById(ServerRequestInterface $request): \App\DTO\Pet { //TODO implement method @@ -47,11 +37,8 @@ public function getPetById(ServerRequestInterface $request): \App\DTO\Pet } /** * Updates a pet in the store with form data - * @PHA\Post() - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Post()] public function updatePetWithForm(ServerRequestInterface $request) { //TODO implement method diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetPetIdUploadImage.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetPetIdUploadImage.php similarity index 58% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetPetIdUploadImage.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetPetIdUploadImage.php index 67cc0784caac..886a35c1e325 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetPetIdUploadImage.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetPetIdUploadImage.php @@ -3,29 +3,22 @@ namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/pet/{petId}/uploadImage") - */ +#[PHA\Route("/pet/{petId}/uploadImage")] class PetPetIdUploadImage { /** * uploads an image - * @PHA\Post() - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/json") - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented - * - * @return \App\DTO\ApiResponse */ + #[PHA\Post()] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] public function uploadFile(ServerRequestInterface $request): \App\DTO\ApiResponse { //TODO implement method diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreInventory.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreInventory.php similarity index 54% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreInventory.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreInventory.php index 6d6d3ceb9464..bc35720421c2 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreInventory.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreInventory.php @@ -3,31 +3,23 @@ namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/store/inventory") - */ +#[PHA\Route("/store/inventory")] class StoreInventory { /** * Returns pet inventories by status - * @PHA\Get() - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/json") - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented - * - * TODO check if generated return container type is valid - * @return map[string,int] */ - public function getInventory(ServerRequestInterface $request): array + #[PHA\Get()] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] + public function getInventory(ServerRequestInterface $request): \App\DTO\Collection34 { //TODO implement method throw new PHException\HttpCode(501, "Not implemented"); diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreOrder.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreOrder.php new file mode 100644 index 000000000000..9399d0e4d3b6 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreOrder.php @@ -0,0 +1,34 @@ + \App\DTO\Order::class, "objectAttr" => "bodyData"])] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] + public function placeOrder(ServerRequestInterface $request): \App\DTO\Order + { + //TODO implement method + /** @var \App\DTO\Order $bodyData */ + $bodyData = $request->getAttribute("bodyData"); + throw new PHException\HttpCode(501, "Not implemented"); + } +} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreOrderOrderId.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreOrderOrderId.php similarity index 54% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreOrderOrderId.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreOrderOrderId.php index 31c53e597eb3..ae8313b20ea1 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreOrderOrderId.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreOrderOrderId.php @@ -3,25 +3,20 @@ namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/store/order/{orderId}") - */ +#[PHA\Route("/store/order/{orderId}")] class StoreOrderOrderId { /** * Delete purchase order by ID - * @PHA\Delete() - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Delete()] public function deleteOrder(ServerRequestInterface $request) { //TODO implement method @@ -29,17 +24,12 @@ public function deleteOrder(ServerRequestInterface $request) } /** * Find purchase order by ID - * @PHA\Get() - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/xml") - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/json") - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented - * - * @return \App\DTO\Order */ + #[PHA\Get()] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] public function getOrderById(ServerRequestInterface $request): \App\DTO\Order { //TODO implement method diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/User.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/User.php similarity index 57% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/User.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/User.php index 5a48f2ec0728..8ad9221e2636 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/User.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/User.php @@ -3,28 +3,23 @@ namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/user") - */ +#[PHA\Route("/user")] class User { /** * Create user - * @PHA\Post() - * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="application/json") - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":\App\DTO\User::class,"objectAttr":"bodyData"}) - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Post()] + // TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Consumer("application/json", PHConsumer\Json::class)] + #[PHA\Attribute(PHAttribute\Transfer::class, ["type" => \App\DTO\User::class, "objectAttr" => "bodyData"])] public function createUser(ServerRequestInterface $request) { //TODO implement method diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithArray.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserCreateWithArray.php similarity index 52% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithArray.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserCreateWithArray.php index a8a39215baba..304f85782c5b 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithArray.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserCreateWithArray.php @@ -3,33 +3,27 @@ namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/user/createWithArray") - */ +#[PHA\Route("/user/createWithArray")] class UserCreateWithArray { /** * Creates list of users with given input array - * @PHA\Post() - * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="application/json") - * TODO check if attribute is valid and can handle your container type - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":"\App\DTO\User[]","objectAttr":"bodyData"}) - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Post()] + // TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Consumer("application/json", PHConsumer\Json::class)] + #[PHA\Attribute(PHAttribute\Transfer::class, ["type" => \App\DTO\Collection36::class, "objectAttr" => "bodyData"])] public function createUsersWithArrayInput(ServerRequestInterface $request) { //TODO implement method - /** @var \App\DTO\User[] $bodyData */ + /** @var \App\DTO\Collection36 $bodyData */ $bodyData = $request->getAttribute("bodyData"); throw new PHException\HttpCode(501, "Not implemented"); } diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithList.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserCreateWithList.php similarity index 52% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithList.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserCreateWithList.php index b34cca7045f2..1d415fcee237 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithList.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserCreateWithList.php @@ -3,33 +3,27 @@ namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/user/createWithList") - */ +#[PHA\Route("/user/createWithList")] class UserCreateWithList { /** * Creates list of users with given input array - * @PHA\Post() - * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="application/json") - * TODO check if attribute is valid and can handle your container type - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":"\App\DTO\User[]","objectAttr":"bodyData"}) - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Post()] + // TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Consumer("application/json", PHConsumer\Json::class)] + #[PHA\Attribute(PHAttribute\Transfer::class, ["type" => \App\DTO\Collection36::class, "objectAttr" => "bodyData"])] public function createUsersWithListInput(ServerRequestInterface $request) { //TODO implement method - /** @var \App\DTO\User[] $bodyData */ + /** @var \App\DTO\Collection36 $bodyData */ $bodyData = $request->getAttribute("bodyData"); throw new PHException\HttpCode(501, "Not implemented"); } diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserLogin.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserLogin.php new file mode 100644 index 000000000000..38a502537f71 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserLogin.php @@ -0,0 +1,36 @@ + \App\DTO\LoginUserQueryData::class, + "objectAttr" => "queryData", + "source" => PHAttribute\Transfer::SOURCE_GET + ])] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] + public function loginUser(ServerRequestInterface $request): string + { + //TODO implement method + /** @var \App\DTO\LoginUserQueryData $queryData */ + $queryData = $request->getAttribute("queryData"); + throw new PHException\HttpCode(501, "Not implemented"); + } +} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserLogout.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserLogout.php similarity index 70% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserLogout.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserLogout.php index 4c0d8b1bb06e..7cb7b9a8a2eb 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserLogout.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserLogout.php @@ -3,25 +3,20 @@ namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/user/logout") - */ +#[PHA\Route("/user/logout")] class UserLogout { /** * Logs out current logged in user session - * @PHA\Get() - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Get()] public function logoutUser(ServerRequestInterface $request) { //TODO implement method diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserUsername.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserUsername.php similarity index 51% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserUsername.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserUsername.php index ce3de9849696..68be5f4fc1a2 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserUsername.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserUsername.php @@ -3,25 +3,20 @@ namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/user/{username}") - */ +#[PHA\Route("/user/{username}")] class UserUsername { /** * Delete user - * @PHA\Delete() - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Delete()] public function deleteUser(ServerRequestInterface $request) { //TODO implement method @@ -29,17 +24,12 @@ public function deleteUser(ServerRequestInterface $request) } /** * Get user by user name - * @PHA\Get() - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/xml") - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/json") - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented - * - * @return \App\DTO\User */ + #[PHA\Get()] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] public function getUserByName(ServerRequestInterface $request): \App\DTO\User { //TODO implement method @@ -47,14 +37,11 @@ public function getUserByName(ServerRequestInterface $request): \App\DTO\User } /** * Updated user - * @PHA\Put() - * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="application/json") - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":\App\DTO\User::class,"objectAttr":"bodyData"}) - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Put()] + // TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Consumer("application/json", PHConsumer\Json::class)] + #[PHA\Attribute(PHAttribute\Transfer::class, ["type" => \App\DTO\User::class, "objectAttr" => "bodyData"])] public function updateUser(ServerRequestInterface $request) { //TODO implement method diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Middleware/InternalServerError.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Middleware/InternalServerError.php similarity index 82% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Middleware/InternalServerError.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Middleware/InternalServerError.php index f0354421e004..bc6d5969e2af 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Middleware/InternalServerError.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Middleware/InternalServerError.php @@ -11,17 +11,8 @@ class InternalServerError implements MiddlewareInterface { - /** - * @var callable - */ - protected $responseGenerator; - - /** - * @param callable $responseGenerator - */ - public function __construct(callable $responseGenerator) + public function __construct(protected \Closure $responseGenerator) { - $this->responseGenerator = $responseGenerator; } /** diff --git a/samples/server/petstore/php-mezzio-ph/.openapi-generator/FILES b/samples/server/petstore/php-mezzio-ph/.openapi-generator/FILES index fc8224fecb8e..bc9a68917b63 100644 --- a/samples/server/petstore/php-mezzio-ph/.openapi-generator/FILES +++ b/samples/server/petstore/php-mezzio-ph/.openapi-generator/FILES @@ -9,6 +9,43 @@ composer.json public/index.php src/App/DTO/ApiResponse.php src/App/DTO/Category.php +src/App/DTO/Collection.php +src/App/DTO/Collection1.php +src/App/DTO/Collection10.php +src/App/DTO/Collection11.php +src/App/DTO/Collection12.php +src/App/DTO/Collection13.php +src/App/DTO/Collection14.php +src/App/DTO/Collection15.php +src/App/DTO/Collection16.php +src/App/DTO/Collection17.php +src/App/DTO/Collection18.php +src/App/DTO/Collection19.php +src/App/DTO/Collection2.php +src/App/DTO/Collection20.php +src/App/DTO/Collection21.php +src/App/DTO/Collection22.php +src/App/DTO/Collection23.php +src/App/DTO/Collection24.php +src/App/DTO/Collection25.php +src/App/DTO/Collection26.php +src/App/DTO/Collection27.php +src/App/DTO/Collection28.php +src/App/DTO/Collection29.php +src/App/DTO/Collection3.php +src/App/DTO/Collection30.php +src/App/DTO/Collection31.php +src/App/DTO/Collection32.php +src/App/DTO/Collection33.php +src/App/DTO/Collection34.php +src/App/DTO/Collection35.php +src/App/DTO/Collection36.php +src/App/DTO/Collection4.php +src/App/DTO/Collection5.php +src/App/DTO/Collection6.php +src/App/DTO/Collection7.php +src/App/DTO/Collection8.php +src/App/DTO/Collection9.php src/App/DTO/FindPetsByStatusQueryData.php src/App/DTO/FindPetsByTagsQueryData.php src/App/DTO/LoginUserQueryData.php diff --git a/samples/server/petstore/php-mezzio-ph/.openapi-generator/VERSION b/samples/server/petstore/php-mezzio-ph/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/php-mezzio-ph/.openapi-generator/VERSION +++ b/samples/server/petstore/php-mezzio-ph/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/php-mezzio-ph/README.md b/samples/server/petstore/php-mezzio-ph/README.md index 584fd1568795..a80470059016 100644 --- a/samples/server/petstore/php-mezzio-ph/README.md +++ b/samples/server/petstore/php-mezzio-ph/README.md @@ -5,9 +5,9 @@ Generated by the [OpenAPI Generator](https://openapi-generator.tech) project. ## Overview This server stub aims to provide light, yet comprehensive structure for your API project using: -- PHP: >=7.2 +- PHP: >=7.3 - [Laminas Mezzio](https://docs.mezzio.dev/mezzio/): >=3.2 -- [Path Handler](https://github.com/Articus/PathHandler): >=0.6 +- [Path Handler](https://github.com/Articus/PathHandler): >=0.7 ## How to use All you have to do to start development is: diff --git a/samples/server/petstore/php-mezzio-ph/application/config.yml b/samples/server/petstore/php-mezzio-ph/application/config.yml index 1f106812353f..71371becf217 100644 --- a/samples/server/petstore/php-mezzio-ph/application/config.yml +++ b/samples/server/petstore/php-mezzio-ph/application/config.yml @@ -9,10 +9,11 @@ # router: # cache: # directory: ./data/cache/PathHandler -# #Enable handler metadata cache -# metadata: -# cache: -# directory: ./data/cache/PathHandler + +#Enable handler metadata cache +#Articus\PathHandler\MetadataProvider\Annotation: +# cache: +# directory: ./data/cache/PathHandler #Enable data transfer metadata cache for DTOs #Articus\DataTransfer\MetadataProvider\Annotation: diff --git a/samples/server/petstore/php-mezzio-ph/application/config/data_transfer.yml b/samples/server/petstore/php-mezzio-ph/application/config/data_transfer.yml index c5174147c236..548c898fb9c8 100644 --- a/samples/server/petstore/php-mezzio-ph/application/config/data_transfer.yml +++ b/samples/server/petstore/php-mezzio-ph/application/config/data_transfer.yml @@ -16,6 +16,10 @@ Articus\DataTransfer\Strategy\PluginManager: factories: Date: OpenAPIGenerator\Common\Strategy\Factory\MutableDate DateTime: OpenAPIGenerator\Common\Strategy\Factory\MutableDateTime + ObjectList: OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectList + ObjectMap: OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectMap + ScalarList: OpenAPIGenerator\Common\Strategy\Factory\ScalarList + ScalarMap: OpenAPIGenerator\Common\Strategy\Factory\ScalarMap Articus\DataTransfer\Validator\PluginManager: invokables: @@ -24,3 +28,7 @@ Articus\DataTransfer\Validator\PluginManager: QueryStringScalarArray: OpenAPIGenerator\Common\Validator\QueryStringScalarArray abstract_factories: - Articus\DataTransfer\Validator\Factory\Laminas + +validators: + invokables: + Count: Laminas\Validator\IsCountable diff --git a/samples/server/petstore/php-mezzio-ph/application/config/path_handler.yml b/samples/server/petstore/php-mezzio-ph/application/config/path_handler.yml index 25995b20d6f6..174f6fc3d269 100644 --- a/samples/server/petstore/php-mezzio-ph/application/config/path_handler.yml +++ b/samples/server/petstore/php-mezzio-ph/application/config/path_handler.yml @@ -1,8 +1,13 @@ dependencies: factories: - Mezzio\Router\RouterInterface: Articus\PathHandler\RouteInjection\Factory + Mezzio\Router\RouterInterface: Articus\PathHandler\RouteInjectionFactory + Articus\PathHandler\MetadataProviderInterface: Articus\PathHandler\MetadataProvider\Factory\Annotation + Articus\PathHandler\Handler\PluginManager: Articus\PathHandler\Handler\Factory\PluginManager + Articus\PathHandler\Consumer\PluginManager: Articus\PathHandler\Consumer\Factory\PluginManager + Articus\PathHandler\Attribute\PluginManager: Articus\PathHandler\Attribute\Factory\PluginManager + Articus\PathHandler\Producer\PluginManager: Articus\PathHandler\Producer\Factory\PluginManager -Articus\PathHandler\RouteInjection\Factory: +Articus\PathHandler\RouteInjectionFactory: paths: '/v2': - App\Handler\Pet @@ -19,18 +24,22 @@ Articus\PathHandler\RouteInjection\Factory: - App\Handler\UserLogin - App\Handler\UserLogout - App\Handler\UserUsername - handlers: - abstract_factories: - - Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory -# consumers: -# factories: -# invokables: -# attributes: -# factories: -# invokables: -# producers: -# factories: -# invokables: + +Articus\PathHandler\Handler\PluginManager: + abstract_factories: + - Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory + +#Articus\PathHandler\Consumer\PluginManager: +# factories: +# invokables: + +#Articus\PathHandler\Attribute\PluginManager: +# factories: +# invokables: + +#Articus\PathHandler\Producer\PluginManager: +# factories: +# invokables: Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory: App\Handler\Pet: [] diff --git a/samples/server/petstore/php-mezzio-ph/composer.json b/samples/server/petstore/php-mezzio-ph/composer.json index 54f8e97226c6..c98cf9983029 100644 --- a/samples/server/petstore/php-mezzio-ph/composer.json +++ b/samples/server/petstore/php-mezzio-ph/composer.json @@ -5,13 +5,13 @@ "version": "1.0.0", "type": "project", "require": { - "php": "^7.2", + "php": "^7.3 || ^8.0", "ext-yaml": "^2.0", "mezzio/mezzio": "^3.2", "laminas/laminas-diactoros": "^2.1", - "articus/path-handler": "^0.6", - "articus/data-transfer": "^0.4", - "articus/openapi-generator-common": "^0.1", + "articus/path-handler": "^0.7", + "articus/data-transfer": "^0.5", + "articus/openapi-generator-common": "^0.2", "doctrine/annotations": "^1.10", "psr/simple-cache": "^1.0", "laminas/laminas-config": "^3.4", diff --git a/samples/server/petstore/php-mezzio-ph/src/App/DTO/ApiResponse.php b/samples/server/petstore/php-mezzio-ph/src/App/DTO/ApiResponse.php index a08cb2c92757..0161f75b2b29 100644 --- a/samples/server/petstore/php-mezzio-ph/src/App/DTO/ApiResponse.php +++ b/samples/server/petstore/php-mezzio-ph/src/App/DTO/ApiResponse.php @@ -16,16 +16,19 @@ class ApiResponse * @var int|null */ public $code; + /** * @DTA\Data(field="type", nullable=true) * @DTA\Validator(name="Scalar", options={"type":"string"}) * @var string|null */ public $type; + /** * @DTA\Data(field="message", nullable=true) * @DTA\Validator(name="Scalar", options={"type":"string"}) * @var string|null */ public $message; + } diff --git a/samples/server/petstore/php-mezzio-ph/src/App/DTO/Category.php b/samples/server/petstore/php-mezzio-ph/src/App/DTO/Category.php index 7b65c273d408..41a221be1cf7 100644 --- a/samples/server/petstore/php-mezzio-ph/src/App/DTO/Category.php +++ b/samples/server/petstore/php-mezzio-ph/src/App/DTO/Category.php @@ -16,6 +16,7 @@ class Category * @var int|null */ public $id; + /** * @DTA\Data(field="name", nullable=true) * @DTA\Validator(name="Scalar", options={"type":"string"}) @@ -23,4 +24,5 @@ class Category * @var string|null */ public $name; + } diff --git a/samples/server/petstore/php-mezzio-ph/src/App/DTO/Collection.php b/samples/server/petstore/php-mezzio-ph/src/App/DTO/Collection.php new file mode 100644 index 000000000000..0e478eb4bd8e --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph/src/App/DTO/Collection.php @@ -0,0 +1,16 @@ +get(Middleware\InternalServerError::class); - if (!($errorMiddleware instanceof Middleware\InternalServerError)) { - throw new \LogicException(\sprintf( - 'Invalid error middleware: expecting %s, not %s.', - Middleware\InternalServerError::class, - \is_object($errorMiddleware) ? \get_class($errorMiddleware) : \gettype($errorMiddleware) - )); - } + $errorMiddleware = self::getErrorMiddleware($container); $pipeline = new MiddlewarePipe(); $runner = new RequestHandlerRunner( $pipeline, $container->get(EmitterInterface::class), $container->get(ServerRequestInterface::class), - function(\Throwable $error) use ($errorMiddleware) : ResponseInterface + static function(\Throwable $error) use ($errorMiddleware) : ResponseInterface { return $errorMiddleware->handleError($error); } @@ -55,4 +48,9 @@ function(\Throwable $error) use ($errorMiddleware) : ResponseInterface return $application; } + + protected static function getErrorMiddleware(ContainerInterface $container): Middleware\InternalServerError + { + return $container->get(Middleware\InternalServerError::class); + } } diff --git a/samples/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByStatus.php b/samples/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByStatus.php index c1c1ce754007..917f9f767a36 100644 --- a/samples/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByStatus.php +++ b/samples/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByStatus.php @@ -31,10 +31,9 @@ class PetFindByStatus * * @throws PHException\HttpCode 501 if the method is not implemented * - * TODO check if generated return container type is valid - * @return \App\DTO\Pet[] + * @return \App\DTO\Collection19 */ - public function findPetsByStatus(ServerRequestInterface $request): array + public function findPetsByStatus(ServerRequestInterface $request): \App\DTO\Collection19 { //TODO implement method /** @var \App\DTO\FindPetsByStatusQueryData $queryData */ diff --git a/samples/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByTags.php b/samples/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByTags.php index b722a310efb0..b74484da909c 100644 --- a/samples/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByTags.php +++ b/samples/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByTags.php @@ -31,10 +31,9 @@ class PetFindByTags * * @throws PHException\HttpCode 501 if the method is not implemented * - * TODO check if generated return container type is valid - * @return \App\DTO\Pet[] + * @return \App\DTO\Collection26 */ - public function findPetsByTags(ServerRequestInterface $request): array + public function findPetsByTags(ServerRequestInterface $request): \App\DTO\Collection26 { //TODO implement method /** @var \App\DTO\FindPetsByTagsQueryData $queryData */ diff --git a/samples/server/petstore/php-mezzio-ph/src/App/Handler/StoreInventory.php b/samples/server/petstore/php-mezzio-ph/src/App/Handler/StoreInventory.php index c1ca1be83d16..c9150110c440 100644 --- a/samples/server/petstore/php-mezzio-ph/src/App/Handler/StoreInventory.php +++ b/samples/server/petstore/php-mezzio-ph/src/App/Handler/StoreInventory.php @@ -24,10 +24,9 @@ class StoreInventory * * @throws PHException\HttpCode 501 if the method is not implemented * - * TODO check if generated return container type is valid - * @return array + * @return \App\DTO\Collection34 */ - public function getInventory(ServerRequestInterface $request): array + public function getInventory(ServerRequestInterface $request): \App\DTO\Collection34 { //TODO implement method throw new PHException\HttpCode(501, "Not implemented"); diff --git a/samples/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithArray.php b/samples/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithArray.php index a8a39215baba..8df1e8b18fd7 100644 --- a/samples/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithArray.php +++ b/samples/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithArray.php @@ -20,8 +20,7 @@ class UserCreateWithArray * @PHA\Post() * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="application/json") - * TODO check if attribute is valid and can handle your container type - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":"\App\DTO\User[]","objectAttr":"bodyData"}) + * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":\App\DTO\Collection36::class,"objectAttr":"bodyData"}) * @param ServerRequestInterface $request * * @throws PHException\HttpCode 501 if the method is not implemented @@ -29,7 +28,7 @@ class UserCreateWithArray public function createUsersWithArrayInput(ServerRequestInterface $request) { //TODO implement method - /** @var \App\DTO\User[] $bodyData */ + /** @var \App\DTO\Collection36 $bodyData */ $bodyData = $request->getAttribute("bodyData"); throw new PHException\HttpCode(501, "Not implemented"); } diff --git a/samples/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithList.php b/samples/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithList.php index b34cca7045f2..dae1cc0f2643 100644 --- a/samples/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithList.php +++ b/samples/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithList.php @@ -20,8 +20,7 @@ class UserCreateWithList * @PHA\Post() * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="application/json") - * TODO check if attribute is valid and can handle your container type - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":"\App\DTO\User[]","objectAttr":"bodyData"}) + * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":\App\DTO\Collection36::class,"objectAttr":"bodyData"}) * @param ServerRequestInterface $request * * @throws PHException\HttpCode 501 if the method is not implemented @@ -29,7 +28,7 @@ class UserCreateWithList public function createUsersWithListInput(ServerRequestInterface $request) { //TODO implement method - /** @var \App\DTO\User[] $bodyData */ + /** @var \App\DTO\Collection36 $bodyData */ $bodyData = $request->getAttribute("bodyData"); throw new PHException\HttpCode(501, "Not implemented"); } diff --git a/samples/server/petstore/php-slim4/.openapi-generator/VERSION b/samples/server/petstore/php-slim4/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/php-slim4/.openapi-generator/VERSION +++ b/samples/server/petstore/php-slim4/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/.openapi-generator/VERSION b/samples/server/petstore/php-symfony/SymfonyBundle-php/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/.openapi-generator/VERSION +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/PetApiInterface.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/PetApiInterface.php index 0cf1ef82a85d..4958426e7c8f 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/PetApiInterface.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/PetApiInterface.php @@ -52,6 +52,15 @@ interface PetApiInterface */ public function setpetstore_auth($value); + /** + * Sets authentication method petstore_auth + * + * @param string $value Value of the petstore_auth authentication method. + * + * @return void + */ + public function setpetstore_auth($value); + /** * Sets authentication method api_key * @@ -66,14 +75,14 @@ public function setapi_key($value); * * Add a new pet to the store * - * @param OpenAPI\Server\Model\Pet $body Pet object that needs to be added to the store (required) + * @param OpenAPI\Server\Model\Pet $pet Pet object that needs to be added to the store (required) * @param integer $responseCode The HTTP response code to return * @param array $responseHeaders Additional HTTP headers to return with the response () * - * @return void + * @return OpenAPI\Server\Model\Pet * */ - public function addPet(Pet $body, &$responseCode, array &$responseHeaders); + public function addPet(Pet $pet, &$responseCode, array &$responseHeaders); /** * Operation deletePet @@ -137,14 +146,14 @@ public function getPetById($petId, &$responseCode, array &$responseHeaders); * * Update an existing pet * - * @param OpenAPI\Server\Model\Pet $body Pet object that needs to be added to the store (required) + * @param OpenAPI\Server\Model\Pet $pet Pet object that needs to be added to the store (required) * @param integer $responseCode The HTTP response code to return * @param array $responseHeaders Additional HTTP headers to return with the response () * - * @return void + * @return OpenAPI\Server\Model\Pet * */ - public function updatePet(Pet $body, &$responseCode, array &$responseHeaders); + public function updatePet(Pet $pet, &$responseCode, array &$responseHeaders); /** * Operation updatePetWithForm diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/StoreApiInterface.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/StoreApiInterface.php index 3a7790362ab1..cf9093ecf13c 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/StoreApiInterface.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/StoreApiInterface.php @@ -97,12 +97,12 @@ public function getOrderById($orderId, &$responseCode, array &$responseHeaders); * * Place an order for a pet * - * @param OpenAPI\Server\Model\Order $body order placed for purchasing the pet (required) + * @param OpenAPI\Server\Model\Order $order order placed for purchasing the pet (required) * @param integer $responseCode The HTTP response code to return * @param array $responseHeaders Additional HTTP headers to return with the response () * * @return OpenAPI\Server\Model\Order * */ - public function placeOrder(Order $body, &$responseCode, array &$responseHeaders); + public function placeOrder(Order $order, &$responseCode, array &$responseHeaders); } diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/UserApiInterface.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/UserApiInterface.php index 960c1b6f8cc9..71a5cfac6699 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/UserApiInterface.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/UserApiInterface.php @@ -42,47 +42,56 @@ interface UserApiInterface { + /** + * Sets authentication method api_key + * + * @param string $value Value of the api_key authentication method. + * + * @return void + */ + public function setapi_key($value); + /** * Operation createUser * * Create user * - * @param OpenAPI\Server\Model\User $body Created user object (required) + * @param OpenAPI\Server\Model\User $user Created user object (required) * @param integer $responseCode The HTTP response code to return * @param array $responseHeaders Additional HTTP headers to return with the response () * * @return void * */ - public function createUser(User $body, &$responseCode, array &$responseHeaders); + public function createUser(User $user, &$responseCode, array &$responseHeaders); /** * Operation createUsersWithArrayInput * * Creates list of users with given input array * - * @param OpenAPI\Server\Model\User[] $body List of user object (required) + * @param OpenAPI\Server\Model\User[] $user List of user object (required) * @param integer $responseCode The HTTP response code to return * @param array $responseHeaders Additional HTTP headers to return with the response () * * @return void * */ - public function createUsersWithArrayInput(array $body, &$responseCode, array &$responseHeaders); + public function createUsersWithArrayInput(array $user, &$responseCode, array &$responseHeaders); /** * Operation createUsersWithListInput * * Creates list of users with given input array * - * @param OpenAPI\Server\Model\User[] $body List of user object (required) + * @param OpenAPI\Server\Model\User[] $user List of user object (required) * @param integer $responseCode The HTTP response code to return * @param array $responseHeaders Additional HTTP headers to return with the response () * * @return void * */ - public function createUsersWithListInput(array $body, &$responseCode, array &$responseHeaders); + public function createUsersWithListInput(array $user, &$responseCode, array &$responseHeaders); /** * Operation deleteUser @@ -146,12 +155,12 @@ public function logoutUser(&$responseCode, array &$responseHeaders); * Updated user * * @param string $username name that need to be deleted (required) - * @param OpenAPI\Server\Model\User $body Updated user object (required) + * @param OpenAPI\Server\Model\User $user Updated user object (required) * @param integer $responseCode The HTTP response code to return * @param array $responseHeaders Additional HTTP headers to return with the response () * * @return void * */ - public function updateUser($username, User $body, &$responseCode, array &$responseHeaders); + public function updateUser($username, User $user, &$responseCode, array &$responseHeaders); } diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/PetController.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/PetController.php index ca07f62678d6..a20c8b98a2ba 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/PetController.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/PetController.php @@ -67,20 +67,29 @@ public function addPetAction(Request $request) return new Response('', 415); } + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + // Handle authentication // Authentication 'petstore_auth' required // Oauth required $securitypetstore_auth = $request->headers->get('authorization'); // Read out all input parameter values into variables - $body = $request->getContent(); + $pet = $request->getContent(); // Use the default value if no value was provided // Deserialize the input values that needs it try { $inputFormat = $request->getMimeType($request->getContentType()); - $body = $this->deserialize($body, 'OpenAPI\Server\Model\Pet', $inputFormat); + $pet = $this->deserialize($pet, 'OpenAPI\Server\Model\Pet', $inputFormat); } catch (SerializerRuntimeException $exception) { return $this->createBadRequestResponse($exception->getMessage()); } @@ -90,7 +99,7 @@ public function addPetAction(Request $request) $asserts[] = new Assert\NotNull(); $asserts[] = new Assert\Type("OpenAPI\Server\Model\Pet"); $asserts[] = new Assert\Valid(); - $response = $this->validate($body, $asserts); + $response = $this->validate($pet, $asserts); if ($response instanceof Response) { return $response; } @@ -103,26 +112,30 @@ public function addPetAction(Request $request) $handler->setpetstore_auth($securitypetstore_auth); // Make the call to the business logic - $responseCode = 204; + $responseCode = 200; $responseHeaders = []; - $result = $handler->addPet($body, $responseCode, $responseHeaders); + $result = $handler->addPet($pet, $responseCode, $responseHeaders); // Find default response message $message = ''; // Find a more specific message, if available switch ($responseCode) { + case 200: + $message = 'successful operation'; + break; case 405: $message = 'Invalid input'; break; } return new Response( - '', + $result !== null ?$this->serialize($result, $responseFormat):'', $responseCode, array_merge( $responseHeaders, [ + 'Content-Type' => $responseFormat, 'X-OpenAPI-Message' => $message ] ) @@ -498,20 +511,29 @@ public function updatePetAction(Request $request) return new Response('', 415); } + // Figure out what data format to return to the client + $produces = ['application/xml', 'application/json']; + // Figure out what the client accepts + $clientAccepts = $request->headers->has('Accept')?$request->headers->get('Accept'):'*/*'; + $responseFormat = $this->getOutputFormat($clientAccepts, $produces); + if ($responseFormat === null) { + return new Response('', 406); + } + // Handle authentication // Authentication 'petstore_auth' required // Oauth required $securitypetstore_auth = $request->headers->get('authorization'); // Read out all input parameter values into variables - $body = $request->getContent(); + $pet = $request->getContent(); // Use the default value if no value was provided // Deserialize the input values that needs it try { $inputFormat = $request->getMimeType($request->getContentType()); - $body = $this->deserialize($body, 'OpenAPI\Server\Model\Pet', $inputFormat); + $pet = $this->deserialize($pet, 'OpenAPI\Server\Model\Pet', $inputFormat); } catch (SerializerRuntimeException $exception) { return $this->createBadRequestResponse($exception->getMessage()); } @@ -521,7 +543,7 @@ public function updatePetAction(Request $request) $asserts[] = new Assert\NotNull(); $asserts[] = new Assert\Type("OpenAPI\Server\Model\Pet"); $asserts[] = new Assert\Valid(); - $response = $this->validate($body, $asserts); + $response = $this->validate($pet, $asserts); if ($response instanceof Response) { return $response; } @@ -534,15 +556,18 @@ public function updatePetAction(Request $request) $handler->setpetstore_auth($securitypetstore_auth); // Make the call to the business logic - $responseCode = 204; + $responseCode = 200; $responseHeaders = []; - $result = $handler->updatePet($body, $responseCode, $responseHeaders); + $result = $handler->updatePet($pet, $responseCode, $responseHeaders); // Find default response message $message = ''; // Find a more specific message, if available switch ($responseCode) { + case 200: + $message = 'successful operation'; + break; case 400: $message = 'Invalid ID supplied'; break; @@ -555,11 +580,12 @@ public function updatePetAction(Request $request) } return new Response( - '', + $result !== null ?$this->serialize($result, $responseFormat):'', $responseCode, array_merge( $responseHeaders, [ + 'Content-Type' => $responseFormat, 'X-OpenAPI-Message' => $message ] ) diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/StoreController.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/StoreController.php index d6e9e33bb369..b0bc06eafa6a 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/StoreController.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/StoreController.php @@ -283,7 +283,7 @@ public function getOrderByIdAction(Request $request, $orderId) public function placeOrderAction(Request $request) { // Make sure that the client is providing something that we can consume - $consumes = []; + $consumes = ['application/json']; if (!static::isContentTypeAllowed($request, $consumes)) { // We can't consume the content that the client is sending us return new Response('', 415); @@ -301,14 +301,14 @@ public function placeOrderAction(Request $request) // Handle authentication // Read out all input parameter values into variables - $body = $request->getContent(); + $order = $request->getContent(); // Use the default value if no value was provided // Deserialize the input values that needs it try { $inputFormat = $request->getMimeType($request->getContentType()); - $body = $this->deserialize($body, 'OpenAPI\Server\Model\Order', $inputFormat); + $order = $this->deserialize($order, 'OpenAPI\Server\Model\Order', $inputFormat); } catch (SerializerRuntimeException $exception) { return $this->createBadRequestResponse($exception->getMessage()); } @@ -318,7 +318,7 @@ public function placeOrderAction(Request $request) $asserts[] = new Assert\NotNull(); $asserts[] = new Assert\Type("OpenAPI\Server\Model\Order"); $asserts[] = new Assert\Valid(); - $response = $this->validate($body, $asserts); + $response = $this->validate($order, $asserts); if ($response instanceof Response) { return $response; } @@ -331,7 +331,7 @@ public function placeOrderAction(Request $request) // Make the call to the business logic $responseCode = 200; $responseHeaders = []; - $result = $handler->placeOrder($body, $responseCode, $responseHeaders); + $result = $handler->placeOrder($order, $responseCode, $responseHeaders); // Find default response message $message = ''; diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/UserController.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/UserController.php index 52af362ae347..b285ae5c23db 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/UserController.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Controller/UserController.php @@ -60,23 +60,26 @@ class UserController extends Controller public function createUserAction(Request $request) { // Make sure that the client is providing something that we can consume - $consumes = []; + $consumes = ['application/json']; if (!static::isContentTypeAllowed($request, $consumes)) { // We can't consume the content that the client is sending us return new Response('', 415); } // Handle authentication + // Authentication 'api_key' required + // Set key with prefix in header + $securityapi_key = $request->headers->get('api_key'); // Read out all input parameter values into variables - $body = $request->getContent(); + $user = $request->getContent(); // Use the default value if no value was provided // Deserialize the input values that needs it try { $inputFormat = $request->getMimeType($request->getContentType()); - $body = $this->deserialize($body, 'OpenAPI\Server\Model\User', $inputFormat); + $user = $this->deserialize($user, 'OpenAPI\Server\Model\User', $inputFormat); } catch (SerializerRuntimeException $exception) { return $this->createBadRequestResponse($exception->getMessage()); } @@ -86,7 +89,7 @@ public function createUserAction(Request $request) $asserts[] = new Assert\NotNull(); $asserts[] = new Assert\Type("OpenAPI\Server\Model\User"); $asserts[] = new Assert\Valid(); - $response = $this->validate($body, $asserts); + $response = $this->validate($user, $asserts); if ($response instanceof Response) { return $response; } @@ -95,11 +98,13 @@ public function createUserAction(Request $request) try { $handler = $this->getApiHandler(); + // Set authentication method 'api_key' + $handler->setapi_key($securityapi_key); // Make the call to the business logic $responseCode = 204; $responseHeaders = []; - $result = $handler->createUser($body, $responseCode, $responseHeaders); + $result = $handler->createUser($user, $responseCode, $responseHeaders); // Find default response message $message = 'successful operation'; @@ -137,23 +142,26 @@ public function createUserAction(Request $request) public function createUsersWithArrayInputAction(Request $request) { // Make sure that the client is providing something that we can consume - $consumes = []; + $consumes = ['application/json']; if (!static::isContentTypeAllowed($request, $consumes)) { // We can't consume the content that the client is sending us return new Response('', 415); } // Handle authentication + // Authentication 'api_key' required + // Set key with prefix in header + $securityapi_key = $request->headers->get('api_key'); // Read out all input parameter values into variables - $body = $request->getContent(); + $user = $request->getContent(); // Use the default value if no value was provided // Deserialize the input values that needs it try { $inputFormat = $request->getMimeType($request->getContentType()); - $body = $this->deserialize($body, 'array', $inputFormat); + $user = $this->deserialize($user, 'array', $inputFormat); } catch (SerializerRuntimeException $exception) { return $this->createBadRequestResponse($exception->getMessage()); } @@ -165,7 +173,7 @@ public function createUsersWithArrayInputAction(Request $request) new Assert\Type("OpenAPI\Server\Model\User"), ]); $asserts[] = new Assert\Valid(); - $response = $this->validate($body, $asserts); + $response = $this->validate($user, $asserts); if ($response instanceof Response) { return $response; } @@ -174,11 +182,13 @@ public function createUsersWithArrayInputAction(Request $request) try { $handler = $this->getApiHandler(); + // Set authentication method 'api_key' + $handler->setapi_key($securityapi_key); // Make the call to the business logic $responseCode = 204; $responseHeaders = []; - $result = $handler->createUsersWithArrayInput($body, $responseCode, $responseHeaders); + $result = $handler->createUsersWithArrayInput($user, $responseCode, $responseHeaders); // Find default response message $message = 'successful operation'; @@ -216,23 +226,26 @@ public function createUsersWithArrayInputAction(Request $request) public function createUsersWithListInputAction(Request $request) { // Make sure that the client is providing something that we can consume - $consumes = []; + $consumes = ['application/json']; if (!static::isContentTypeAllowed($request, $consumes)) { // We can't consume the content that the client is sending us return new Response('', 415); } // Handle authentication + // Authentication 'api_key' required + // Set key with prefix in header + $securityapi_key = $request->headers->get('api_key'); // Read out all input parameter values into variables - $body = $request->getContent(); + $user = $request->getContent(); // Use the default value if no value was provided // Deserialize the input values that needs it try { $inputFormat = $request->getMimeType($request->getContentType()); - $body = $this->deserialize($body, 'array', $inputFormat); + $user = $this->deserialize($user, 'array', $inputFormat); } catch (SerializerRuntimeException $exception) { return $this->createBadRequestResponse($exception->getMessage()); } @@ -244,7 +257,7 @@ public function createUsersWithListInputAction(Request $request) new Assert\Type("OpenAPI\Server\Model\User"), ]); $asserts[] = new Assert\Valid(); - $response = $this->validate($body, $asserts); + $response = $this->validate($user, $asserts); if ($response instanceof Response) { return $response; } @@ -253,11 +266,13 @@ public function createUsersWithListInputAction(Request $request) try { $handler = $this->getApiHandler(); + // Set authentication method 'api_key' + $handler->setapi_key($securityapi_key); // Make the call to the business logic $responseCode = 204; $responseHeaders = []; - $result = $handler->createUsersWithListInput($body, $responseCode, $responseHeaders); + $result = $handler->createUsersWithListInput($user, $responseCode, $responseHeaders); // Find default response message $message = 'successful operation'; @@ -295,6 +310,9 @@ public function createUsersWithListInputAction(Request $request) public function deleteUserAction(Request $request, $username) { // Handle authentication + // Authentication 'api_key' required + // Set key with prefix in header + $securityapi_key = $request->headers->get('api_key'); // Read out all input parameter values into variables @@ -320,6 +338,8 @@ public function deleteUserAction(Request $request, $username) try { $handler = $this->getApiHandler(); + // Set authentication method 'api_key' + $handler->setapi_key($securityapi_key); // Make the call to the business logic $responseCode = 204; @@ -476,6 +496,7 @@ public function loginUserAction(Request $request) $asserts = []; $asserts[] = new Assert\NotNull(); $asserts[] = new Assert\Type("string"); + $asserts[] = new Assert\Regex("/^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$/"); $response = $this->validate($username, $asserts); if ($response instanceof Response) { return $response; @@ -538,6 +559,9 @@ public function loginUserAction(Request $request) public function logoutUserAction(Request $request) { // Handle authentication + // Authentication 'api_key' required + // Set key with prefix in header + $securityapi_key = $request->headers->get('api_key'); // Read out all input parameter values into variables @@ -549,6 +573,8 @@ public function logoutUserAction(Request $request) try { $handler = $this->getApiHandler(); + // Set authentication method 'api_key' + $handler->setapi_key($securityapi_key); // Make the call to the business logic $responseCode = 204; @@ -591,16 +617,19 @@ public function logoutUserAction(Request $request) public function updateUserAction(Request $request, $username) { // Make sure that the client is providing something that we can consume - $consumes = []; + $consumes = ['application/json']; if (!static::isContentTypeAllowed($request, $consumes)) { // We can't consume the content that the client is sending us return new Response('', 415); } // Handle authentication + // Authentication 'api_key' required + // Set key with prefix in header + $securityapi_key = $request->headers->get('api_key'); // Read out all input parameter values into variables - $body = $request->getContent(); + $user = $request->getContent(); // Use the default value if no value was provided @@ -608,7 +637,7 @@ public function updateUserAction(Request $request, $username) try { $username = $this->deserialize($username, 'string', 'string'); $inputFormat = $request->getMimeType($request->getContentType()); - $body = $this->deserialize($body, 'OpenAPI\Server\Model\User', $inputFormat); + $user = $this->deserialize($user, 'OpenAPI\Server\Model\User', $inputFormat); } catch (SerializerRuntimeException $exception) { return $this->createBadRequestResponse($exception->getMessage()); } @@ -625,7 +654,7 @@ public function updateUserAction(Request $request, $username) $asserts[] = new Assert\NotNull(); $asserts[] = new Assert\Type("OpenAPI\Server\Model\User"); $asserts[] = new Assert\Valid(); - $response = $this->validate($body, $asserts); + $response = $this->validate($user, $asserts); if ($response instanceof Response) { return $response; } @@ -634,11 +663,13 @@ public function updateUserAction(Request $request, $username) try { $handler = $this->getApiHandler(); + // Set authentication method 'api_key' + $handler->setapi_key($securityapi_key); // Make the call to the business logic $responseCode = 204; $responseHeaders = []; - $result = $handler->updateUser($username, $body, $responseCode, $responseHeaders); + $result = $handler->updateUser($username, $user, $responseCode, $responseHeaders); // Find default response message $message = ''; diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Category.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Category.php index 8964e71b66a9..7ee222ced8d6 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Category.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Category.php @@ -56,6 +56,7 @@ class Category * @SerializedName("name") * @Assert\Type("string") * @Type("string") + * @Assert\Regex("/^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$/") */ protected $name; diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/README.md b/samples/server/petstore/php-symfony/SymfonyBundle-php/README.md index 27ebd280cd11..b1aab117e185 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/README.md +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/README.md @@ -93,7 +93,7 @@ class PetApi implements PetApiInterface // An interface is autogenerated /** * Implementation of PetApiInterface#addPet */ - public function addPet(Pet $body) + public function addPet(Pet $pet) { // Implement the operation ... } diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/PetApiInterface.md b/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/PetApiInterface.md index 41b9776c01c7..01bd0ee88ae7 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/PetApiInterface.md +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/PetApiInterface.md @@ -27,7 +27,7 @@ services: ``` ## **addPet** -> addPet($body) +> OpenAPI\Server\Model\Pet addPet($pet) Add a new pet to the store @@ -56,7 +56,7 @@ class PetApi implements PetApiInterface /** * Implementation of PetApiInterface#addPet */ - public function addPet(Pet $body) + public function addPet(Pet $pet) { // Implement the operation ... } @@ -69,11 +69,11 @@ class PetApi implements PetApiInterface Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**OpenAPI\Server\Model\Pet**](../Model/Pet.md)| Pet object that needs to be added to the store | + **pet** | [**OpenAPI\Server\Model\Pet**](../Model/Pet.md)| Pet object that needs to be added to the store | ### Return type -void (empty response body) +[**OpenAPI\Server\Model\Pet**](../Model/Pet.md) ### Authorization @@ -82,7 +82,7 @@ void (empty response body) ### HTTP request headers - **Content-Type**: application/json, application/xml - - **Accept**: Not defined + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) @@ -334,7 +334,7 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) ## **updatePet** -> updatePet($body) +> OpenAPI\Server\Model\Pet updatePet($pet) Update an existing pet @@ -363,7 +363,7 @@ class PetApi implements PetApiInterface /** * Implementation of PetApiInterface#updatePet */ - public function updatePet(Pet $body) + public function updatePet(Pet $pet) { // Implement the operation ... } @@ -376,11 +376,11 @@ class PetApi implements PetApiInterface Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**OpenAPI\Server\Model\Pet**](../Model/Pet.md)| Pet object that needs to be added to the store | + **pet** | [**OpenAPI\Server\Model\Pet**](../Model/Pet.md)| Pet object that needs to be added to the store | ### Return type -void (empty response body) +[**OpenAPI\Server\Model\Pet**](../Model/Pet.md) ### Authorization @@ -389,7 +389,7 @@ void (empty response body) ### HTTP request headers - **Content-Type**: application/json, application/xml - - **Accept**: Not defined + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/StoreApiInterface.md b/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/StoreApiInterface.md index 0a1f4154f6d4..3d3e3b18c3ef 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/StoreApiInterface.md +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/StoreApiInterface.md @@ -190,7 +190,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) ## **placeOrder** -> OpenAPI\Server\Model\Order placeOrder($body) +> OpenAPI\Server\Model\Order placeOrder($order) Place an order for a pet @@ -211,7 +211,7 @@ class StoreApi implements StoreApiInterface /** * Implementation of StoreApiInterface#placeOrder */ - public function placeOrder(Order $body) + public function placeOrder(Order $order) { // Implement the operation ... } @@ -224,7 +224,7 @@ class StoreApi implements StoreApiInterface Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**OpenAPI\Server\Model\Order**](../Model/Order.md)| order placed for purchasing the pet | + **order** | [**OpenAPI\Server\Model\Order**](../Model/Order.md)| order placed for purchasing the pet | ### Return type @@ -236,7 +236,7 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined + - **Content-Type**: application/json - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/UserApiInterface.md b/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/UserApiInterface.md index 571e9dcbf291..c00ce7309a8e 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/UserApiInterface.md +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Resources/docs/Api/UserApiInterface.md @@ -27,7 +27,7 @@ services: ``` ## **createUser** -> createUser($body) +> createUser($user) Create user @@ -45,12 +45,20 @@ use OpenAPI\Server\Api\UserApiInterface; class UserApi implements UserApiInterface { + /** + * Configure API key authorization: api_key + */ + public function setapi_key($apiKey) + { + // Retrieve logged in user from $apiKey ... + } + // ... /** * Implementation of UserApiInterface#createUser */ - public function createUser(User $body) + public function createUser(User $user) { // Implement the operation ... } @@ -63,7 +71,7 @@ class UserApi implements UserApiInterface Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**OpenAPI\Server\Model\User**](../Model/User.md)| Created user object | + **user** | [**OpenAPI\Server\Model\User**](../Model/User.md)| Created user object | ### Return type @@ -71,17 +79,17 @@ void (empty response body) ### Authorization -No authorization required +[api_key](../../README.md#api_key) ### HTTP request headers - - **Content-Type**: Not defined + - **Content-Type**: application/json - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) ## **createUsersWithArrayInput** -> createUsersWithArrayInput($body) +> createUsersWithArrayInput($user) Creates list of users with given input array @@ -97,12 +105,20 @@ use OpenAPI\Server\Api\UserApiInterface; class UserApi implements UserApiInterface { + /** + * Configure API key authorization: api_key + */ + public function setapi_key($apiKey) + { + // Retrieve logged in user from $apiKey ... + } + // ... /** * Implementation of UserApiInterface#createUsersWithArrayInput */ - public function createUsersWithArrayInput(array $body) + public function createUsersWithArrayInput(array $user) { // Implement the operation ... } @@ -115,7 +131,7 @@ class UserApi implements UserApiInterface Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**OpenAPI\Server\Model\User**](../Model/User.md)| List of user object | + **user** | [**OpenAPI\Server\Model\User**](../Model/User.md)| List of user object | ### Return type @@ -123,17 +139,17 @@ void (empty response body) ### Authorization -No authorization required +[api_key](../../README.md#api_key) ### HTTP request headers - - **Content-Type**: Not defined + - **Content-Type**: application/json - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) ## **createUsersWithListInput** -> createUsersWithListInput($body) +> createUsersWithListInput($user) Creates list of users with given input array @@ -149,12 +165,20 @@ use OpenAPI\Server\Api\UserApiInterface; class UserApi implements UserApiInterface { + /** + * Configure API key authorization: api_key + */ + public function setapi_key($apiKey) + { + // Retrieve logged in user from $apiKey ... + } + // ... /** * Implementation of UserApiInterface#createUsersWithListInput */ - public function createUsersWithListInput(array $body) + public function createUsersWithListInput(array $user) { // Implement the operation ... } @@ -167,7 +191,7 @@ class UserApi implements UserApiInterface Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**OpenAPI\Server\Model\User**](../Model/User.md)| List of user object | + **user** | [**OpenAPI\Server\Model\User**](../Model/User.md)| List of user object | ### Return type @@ -175,11 +199,11 @@ void (empty response body) ### Authorization -No authorization required +[api_key](../../README.md#api_key) ### HTTP request headers - - **Content-Type**: Not defined + - **Content-Type**: application/json - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) @@ -203,6 +227,14 @@ use OpenAPI\Server\Api\UserApiInterface; class UserApi implements UserApiInterface { + /** + * Configure API key authorization: api_key + */ + public function setapi_key($apiKey) + { + // Retrieve logged in user from $apiKey ... + } + // ... /** @@ -229,7 +261,7 @@ void (empty response body) ### Authorization -No authorization required +[api_key](../../README.md#api_key) ### HTTP request headers @@ -360,6 +392,14 @@ use OpenAPI\Server\Api\UserApiInterface; class UserApi implements UserApiInterface { + /** + * Configure API key authorization: api_key + */ + public function setapi_key($apiKey) + { + // Retrieve logged in user from $apiKey ... + } + // ... /** @@ -383,7 +423,7 @@ void (empty response body) ### Authorization -No authorization required +[api_key](../../README.md#api_key) ### HTTP request headers @@ -393,7 +433,7 @@ No authorization required [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) ## **updateUser** -> updateUser($username, $body) +> updateUser($username, $user) Updated user @@ -411,12 +451,20 @@ use OpenAPI\Server\Api\UserApiInterface; class UserApi implements UserApiInterface { + /** + * Configure API key authorization: api_key + */ + public function setapi_key($apiKey) + { + // Retrieve logged in user from $apiKey ... + } + // ... /** * Implementation of UserApiInterface#updateUser */ - public function updateUser($username, User $body) + public function updateUser($username, User $user) { // Implement the operation ... } @@ -430,7 +478,7 @@ class UserApi implements UserApiInterface Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **string**| name that need to be deleted | - **body** | [**OpenAPI\Server\Model\User**](../Model/User.md)| Updated user object | + **user** | [**OpenAPI\Server\Model\User**](../Model/User.md)| Updated user object | ### Return type @@ -438,11 +486,11 @@ void (empty response body) ### Authorization -No authorization required +[api_key](../../README.md#api_key) ### HTTP request headers - - **Content-Type**: Not defined + - **Content-Type**: application/json - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) diff --git a/samples/server/petstore/python-aiohttp-srclayout/.openapi-generator/VERSION b/samples/server/petstore/python-aiohttp-srclayout/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/python-aiohttp-srclayout/.openapi-generator/VERSION +++ b/samples/server/petstore/python-aiohttp-srclayout/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/python-aiohttp/.openapi-generator/VERSION b/samples/server/petstore/python-aiohttp/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/python-aiohttp/.openapi-generator/VERSION +++ b/samples/server/petstore/python-aiohttp/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/python-blueplanet/.openapi-generator/VERSION b/samples/server/petstore/python-blueplanet/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/python-blueplanet/.openapi-generator/VERSION +++ b/samples/server/petstore/python-blueplanet/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/python-fastapi/.gitignore b/samples/server/petstore/python-fastapi/.gitignore new file mode 100644 index 000000000000..a81c8ee12195 --- /dev/null +++ b/samples/server/petstore/python-fastapi/.gitignore @@ -0,0 +1,138 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ diff --git a/samples/server/petstore/python-fastapi/.openapi-generator-ignore b/samples/server/petstore/python-fastapi/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/petstore/python-fastapi/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/python-fastapi/.openapi-generator/FILES b/samples/server/petstore/python-fastapi/.openapi-generator/FILES new file mode 100644 index 000000000000..247e0d50f673 --- /dev/null +++ b/samples/server/petstore/python-fastapi/.openapi-generator/FILES @@ -0,0 +1,23 @@ +.gitignore +Dockerfile +README.md +docker-compose.yaml +openapi.yaml +pyproject.toml +requirements.txt +setup.cfg +src/openapi_server/apis/__init__.py +src/openapi_server/apis/pet_api.py +src/openapi_server/apis/store_api.py +src/openapi_server/apis/user_api.py +src/openapi_server/main.py +src/openapi_server/models/__init__.py +src/openapi_server/models/api_response.py +src/openapi_server/models/category.py +src/openapi_server/models/extra_models.py +src/openapi_server/models/order.py +src/openapi_server/models/pet.py +src/openapi_server/models/tag.py +src/openapi_server/models/user.py +src/openapi_server/security_api.py +tests/conftest.py diff --git a/samples/server/petstore/python-fastapi/.openapi-generator/VERSION b/samples/server/petstore/python-fastapi/.openapi-generator/VERSION new file mode 100644 index 000000000000..6555596f9311 --- /dev/null +++ b/samples/server/petstore/python-fastapi/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/python-fastapi/Dockerfile b/samples/server/petstore/python-fastapi/Dockerfile new file mode 100644 index 000000000000..395fed380e6c --- /dev/null +++ b/samples/server/petstore/python-fastapi/Dockerfile @@ -0,0 +1,30 @@ +FROM python:3.6 AS builder + +WORKDIR /usr/src/app + +RUN python3 -m venv /venv +ENV PATH="/venv/bin:$PATH" + +RUN pip install --upgrade pip + +COPY . . +RUN pip install --no-cache-dir . + + +FROM python:3.6 AS test_runner +WORKDIR /tmp +COPY --from=builder /venv /venv +COPY --from=builder /usr/src/app/tests tests +ENV PATH=/venv/bin:$PATH + +# install test dependencies +RUN pip install pytest + +# run tests +RUN pytest tests + + +FROM python:3.6 AS service +WORKDIR /root/app/site-packages +COPY --from=test_runner /venv /venv +ENV PATH=/venv/bin:$PATH diff --git a/samples/server/petstore/python-fastapi/README.md b/samples/server/petstore/python-fastapi/README.md new file mode 100644 index 000000000000..3dacf6e790e6 --- /dev/null +++ b/samples/server/petstore/python-fastapi/README.md @@ -0,0 +1,29 @@ +# OpenAPI generated FastAPI server + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- Build package: org.openapitools.codegen.languages.PythonFastAPIServerCodegen + +## Requirements. + +Python >= 3.6 + +## Installation & Usage + +To run the server, please execute the following from the root directory: + +``` + pip3 install -r requirements.txt + uvicorn main:app --host 0.0.0.0 --port 8080 +``` + +and open your browser at `http://localhost:8080/docs/` to see the docs. + +## Running with Docker + +To run the server on a Docker container, please execute the following from the root directory: + +```bash +docker-compose up --build +``` diff --git a/samples/server/petstore/python-fastapi/docker-compose.yaml b/samples/server/petstore/python-fastapi/docker-compose.yaml new file mode 100644 index 000000000000..638e4e00d347 --- /dev/null +++ b/samples/server/petstore/python-fastapi/docker-compose.yaml @@ -0,0 +1,9 @@ +version: '3.6' +services: + service: + build: + context: . + target: service + ports: + - "8080:8080" + command: uvicorn openapi_server.main:app --host 0.0.0.0 --port 8080 diff --git a/samples/server/petstore/python-fastapi/openapi.yaml b/samples/server/petstore/python-fastapi/openapi.yaml new file mode 100644 index 000000000000..477694ade007 --- /dev/null +++ b/samples/server/petstore/python-fastapi/openapi.yaml @@ -0,0 +1,840 @@ +openapi: 3.0.0 +info: + description: This is a sample server Petstore server. For this sample, you can use + the api key `special-key` to test the authorization filters. + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Petstore + version: 1.0.0 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: +- url: http://petstore.swagger.io/v2 +tags: +- description: Everything about your Pets + name: pet +- description: Access to Petstore orders + name: store +- description: Operations about user + name: user +paths: + /pet: + post: + operationId: addPet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Add a new pet to the store + tags: + - pet + put: + operationId: updatePet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + "405": + description: Validation exception + security: + - petstore_auth: + - write:pets + - read:pets + summary: Update an existing pet + tags: + - pet + /pet/findByStatus: + get: + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - description: Status values that need to be considered for filter + explode: false + in: query + name: status + required: true + schema: + items: + default: available + enum: + - available + - pending + - sold + type: string + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + description: successful operation + "400": + description: Invalid status value + security: + - petstore_auth: + - read:pets + summary: Finds Pets by status + tags: + - pet + /pet/findByTags: + get: + deprecated: true + description: Multiple tags can be provided with comma separated strings. Use + tag1, tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - description: Tags to filter by + explode: false + in: query + name: tags + required: true + schema: + items: + type: string + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + description: successful operation + "400": + description: Invalid tag value + security: + - petstore_auth: + - read:pets + summary: Finds Pets by tags + tags: + - pet + /pet/{petId}: + delete: + operationId: deletePet + parameters: + - explode: false + in: header + name: api_key + required: false + schema: + type: string + style: simple + - description: Pet id to delete + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "400": + description: Invalid pet value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Deletes a pet + tags: + - pet + get: + description: Returns a single pet + operationId: getPetById + parameters: + - description: ID of pet to return + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + security: + - api_key: [] + summary: Find pet by ID + tags: + - pet + post: + operationId: updatePetWithForm + parameters: + - description: ID of pet that needs to be updated + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + $ref: '#/components/requestBodies/inline_object' + content: + application/x-www-form-urlencoded: + schema: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + type: object + responses: + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Updates a pet in the store with form data + tags: + - pet + /pet/{petId}/uploadImage: + post: + operationId: uploadFile + parameters: + - description: ID of pet to update + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + $ref: '#/components/requestBodies/inline_object_1' + content: + multipart/form-data: + schema: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + type: object + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads an image + tags: + - pet + /store/inventory: + get: + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + "200": + content: + application/json: + schema: + additionalProperties: + format: int32 + type: integer + type: object + description: successful operation + security: + - api_key: [] + summary: Returns pet inventories by status + tags: + - store + /store/order: + post: + operationId: placeOrder + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + description: successful operation + "400": + description: Invalid Order + summary: Place an order for a pet + tags: + - store + /store/order/{orderId}: + delete: + description: For valid response try integer IDs with value < 1000. Anything + above 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - description: ID of the order that needs to be deleted + explode: false + in: path + name: orderId + required: true + schema: + type: string + style: simple + responses: + "400": + description: Invalid ID supplied + "404": + description: Order not found + summary: Delete purchase order by ID + tags: + - store + get: + description: For valid response try integer IDs with value <= 5 or > 10. Other + values will generated exceptions + operationId: getOrderById + parameters: + - description: ID of pet that needs to be fetched + explode: false + in: path + name: orderId + required: true + schema: + format: int64 + maximum: 5 + minimum: 1 + type: integer + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Order not found + summary: Find purchase order by ID + tags: + - store + /user: + post: + description: This can only be done by the logged in user. + operationId: createUser + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Create user + tags: + - user + /user/createWithArray: + post: + operationId: createUsersWithArrayInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Creates list of users with given input array + tags: + - user + /user/createWithList: + post: + operationId: createUsersWithListInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Creates list of users with given input array + tags: + - user + /user/login: + get: + operationId: loginUser + parameters: + - description: The user name for login + explode: true + in: query + name: username + required: true + schema: + pattern: ^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$ + type: string + style: form + - description: The password for login in clear text + explode: true + in: query + name: password + required: true + schema: + type: string + style: form + responses: + "200": + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + description: successful operation + headers: + Set-Cookie: + description: Cookie authentication key for use with the `api_key` apiKey + authentication. + explode: false + schema: + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + type: string + style: simple + X-Rate-Limit: + description: calls per hour allowed by the user + explode: false + schema: + format: int32 + type: integer + style: simple + X-Expires-After: + description: date in UTC when toekn expires + explode: false + schema: + format: date-time + type: string + style: simple + "400": + description: Invalid username/password supplied + summary: Logs user into the system + tags: + - user + /user/logout: + get: + operationId: logoutUser + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Logs out current logged in user session + tags: + - user + /user/{username}: + delete: + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - description: The name that needs to be deleted + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + responses: + "400": + description: Invalid username supplied + "404": + description: User not found + security: + - api_key: [] + summary: Delete user + tags: + - user + get: + operationId: getUserByName + parameters: + - description: The name that needs to be fetched. Use user1 for testing. + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + description: successful operation + "400": + description: Invalid username supplied + "404": + description: User not found + summary: Get user by user name + tags: + - user + put: + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - description: name that need to be deleted + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + responses: + "400": + description: Invalid user supplied + "404": + description: User not found + security: + - api_key: [] + summary: Updated user + tags: + - user +components: + requestBodies: + UserArray: + content: + application/json: + schema: + items: + $ref: '#/components/schemas/User' + type: array + description: List of user object + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + inline_object: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/inline_object' + inline_object_1: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/inline_object_1' + schemas: + Order: + description: An order for a pets from the pet store + example: + petId: 6 + quantity: 1 + id: 0 + shipDate: 2000-01-23T04:56:07.000+00:00 + complete: false + status: placed + properties: + id: + format: int64 + title: id + type: integer + petId: + format: int64 + title: petId + type: integer + quantity: + format: int32 + title: quantity + type: integer + shipDate: + format: date-time + title: shipDate + type: string + status: + description: Order Status + enum: + - placed + - approved + - delivered + title: status + type: string + complete: + default: false + title: complete + type: boolean + title: Pet Order + type: object + xml: + name: Order + Category: + description: A category for a pet + example: + name: name + id: 6 + properties: + id: + format: int64 + title: id + type: integer + name: + pattern: ^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$ + title: name + type: string + title: Pet category + type: object + xml: + name: Category + User: + description: A User who is purchasing from the pet store + example: + firstName: firstName + lastName: lastName + password: password + userStatus: 6 + phone: phone + id: 0 + email: email + username: username + properties: + id: + format: int64 + type: integer + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + description: User Status + format: int32 + type: integer + title: a User + type: object + xml: + name: User + Tag: + description: A tag for a pet + example: + name: name + id: 1 + properties: + id: + format: int64 + title: id + type: integer + name: + title: name + type: string + title: Pet Tag + type: object + xml: + name: Tag + Pet: + description: A pet for sale in the pet store + example: + photoUrls: + - photoUrls + - photoUrls + name: doggie + id: 0 + category: + name: name + id: 6 + tags: + - name: name + id: 1 + - name: name + id: 1 + status: available + properties: + id: + format: int64 + title: id + type: integer + category: + $ref: '#/components/schemas/Category' + name: + example: doggie + title: name + type: string + photoUrls: + items: + type: string + title: photoUrls + type: array + xml: + name: photoUrl + wrapped: true + tags: + items: + $ref: '#/components/schemas/Tag' + title: tags + type: array + xml: + name: tag + wrapped: true + status: + description: pet status in the store + enum: + - available + - pending + - sold + title: status + type: string + required: + - name + - photoUrls + title: a Pet + type: object + xml: + name: Pet + ApiResponse: + description: Describes the result of uploading an image resource + example: + code: 0 + type: type + message: message + properties: + code: + format: int32 + title: code + type: integer + type: + title: type + type: string + message: + title: message + type: string + title: An uploaded response + type: object + inline_object: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + type: object + inline_object_1: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + type: object + securitySchemes: + petstore_auth: + flows: + implicit: + authorizationUrl: http://petstore.swagger.io/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + type: oauth2 + api_key: + in: header + name: api_key + type: apiKey diff --git a/samples/server/petstore/python-fastapi/pyproject.toml b/samples/server/petstore/python-fastapi/pyproject.toml new file mode 100644 index 000000000000..c2826df30203 --- /dev/null +++ b/samples/server/petstore/python-fastapi/pyproject.toml @@ -0,0 +1,30 @@ +[build-system] +requires = ["setuptools", "wheel"] +build-backend = "setuptools.build_meta" + +[tool.black] +line-length = 88 +exclude = ''' +( + /( + \.eggs # exclude a few common directories in the + | \.git # root of the project + | \.hg + | \.mypy_cache + | \.tox + | \.venv + | _build + | buck-out + | build + | dist + )/ +) +''' + +[tool.isort] +profile = "black" +skip = [ + '.eggs', '.git', '.hg', '.mypy_cache', '.nox', '.pants.d', '.tox', + '.venv', '_build', 'buck-out', 'build', 'dist', 'node_modules', 'venv', +] +skip_gitignore = true diff --git a/samples/server/petstore/python-fastapi/requirements.txt b/samples/server/petstore/python-fastapi/requirements.txt new file mode 100644 index 000000000000..ce66f96d42c9 --- /dev/null +++ b/samples/server/petstore/python-fastapi/requirements.txt @@ -0,0 +1,36 @@ +aiofiles==0.5.0 +aniso8601==7.0.0 +async-exit-stack==1.0.1 +async-generator==1.10 +certifi==2020.12.5 +chardet==4.0.0 +click==7.1.2 +dnspython==2.1.0 +email-validator==1.1.2 +fastapi==0.65.1 +graphene==2.1.8 +graphql-core==2.3.2 +graphql-relay==2.0.1 +h11==0.12.0 +httptools==0.1.2 +idna==2.10 +itsdangerous==1.1.0 +Jinja2==2.11.3 +MarkupSafe==2.0.1 +orjson==3.5.2 +promise==2.3 +pydantic==1.8.2 +python-dotenv==0.17.1 +python-multipart==0.0.5 +PyYAML==5.4.1 +requests==2.25.1 +Rx==1.6.1 +six==1.16.0 +starlette==0.14.2 +typing-extensions==3.10.0.0 +ujson==4.0.2 +urllib3==1.26.4 +uvicorn==0.13.4 +uvloop==0.14.0 +watchgod==0.7 +websockets==8.1 diff --git a/samples/server/petstore/python-fastapi/setup.cfg b/samples/server/petstore/python-fastapi/setup.cfg new file mode 100644 index 000000000000..bc0f0d452d92 --- /dev/null +++ b/samples/server/petstore/python-fastapi/setup.cfg @@ -0,0 +1,23 @@ +[metadata] +name = openapi_server +version = 1.0.0 +description = This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +long_description = file: README.md +keywords = OpenAPI OpenAPI Petstore +python_requires = >= 3.6.* +classifiers = + Operating System :: OS Independent + Programming Language :: Python :: 3 + Programming Language :: Python :: 3.6 + +[options] +install_requires = + fastapi[all] +setup_requires = + setuptools +package_dir= + =src +packages=find_namespace: + +[options.packages.find] +where=src diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/apis/__init__.py b/samples/server/petstore/python-fastapi/src/openapi_server/apis/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/apis/pet_api.py b/samples/server/petstore/python-fastapi/src/openapi_server/apis/pet_api.py new file mode 100644 index 000000000000..d4dfa357c303 --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/apis/pet_api.py @@ -0,0 +1,189 @@ +# coding: utf-8 + +from typing import Dict, List + +from fastapi import ( + APIRouter, + Body, + Cookie, + Depends, + Form, + Header, + Path, + Query, + Response, + Security, + status, +) + +from openapi_server.models.extra_models import TokenModel +from openapi_server.models.api_response import ApiResponse +from openapi_server.models.pet import Pet +from openapi_server.security_api import get_token_petstore_auth, get_token_api_key + +router = APIRouter() + + +@router.post( + "/pet", + responses={ + 200: {"model": Pet, "description": "successful operation"}, + 405: {"description": "Invalid input"}, + }, + tags=["pet"], + summary="Add a new pet to the store", +) +async def add_pet( + pet: Pet = Body(None, description="Pet object that needs to be added to the store") +, + token_petstore_auth: TokenModel = Security( + get_token_petstore_auth, scopes=["write:pets", "read:pets"] + ), +) -> Pet: # noqa: E501 + ... + + +@router.delete( + "/pet/{petId}", + responses={ + 400: {"description": "Invalid pet value"}, + }, + tags=["pet"], + summary="Deletes a pet", +) +async def delete_pet( + petId: int = Path(None, description="Pet id to delete") +, + api_key: str = Header(None, description="") +, + token_petstore_auth: TokenModel = Security( + get_token_petstore_auth, scopes=["write:pets", "read:pets"] + ), +) -> None: # noqa: E501 + ... + + +@router.get( + "/pet/findByStatus", + responses={ + 200: {"model": List[Pet], "description": "successful operation"}, + 400: {"description": "Invalid status value"}, + }, + tags=["pet"], + summary="Finds Pets by status", +) +async def find_pets_by_status( + status: List[str] = Query(None, description="Status values that need to be considered for filter") +, + token_petstore_auth: TokenModel = Security( + get_token_petstore_auth, scopes=["read:pets"] + ), +) -> List[Pet]: # noqa: E501 + """Multiple status values can be provided with comma separated strings""" + ... + + +@router.get( + "/pet/findByTags", + responses={ + 200: {"model": List[Pet], "description": "successful operation"}, + 400: {"description": "Invalid tag value"}, + }, + tags=["pet"], + summary="Finds Pets by tags", +) +async def find_pets_by_tags( + tags: List[str] = Query(None, description="Tags to filter by") +, + token_petstore_auth: TokenModel = Security( + get_token_petstore_auth, scopes=["read:pets"] + ), +) -> List[Pet]: # noqa: E501 + """Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.""" + ... + + +@router.get( + "/pet/{petId}", + responses={ + 200: {"model": Pet, "description": "successful operation"}, + 400: {"description": "Invalid ID supplied"}, + 404: {"description": "Pet not found"}, + }, + tags=["pet"], + summary="Find pet by ID", +) +async def get_pet_by_id( + petId: int = Path(None, description="ID of pet to return") +, + token_api_key: TokenModel = Security( + get_token_api_key + ), +) -> Pet: # noqa: E501 + """Returns a single pet""" + ... + + +@router.put( + "/pet", + responses={ + 200: {"model": Pet, "description": "successful operation"}, + 400: {"description": "Invalid ID supplied"}, + 404: {"description": "Pet not found"}, + 405: {"description": "Validation exception"}, + }, + tags=["pet"], + summary="Update an existing pet", +) +async def update_pet( + pet: Pet = Body(None, description="Pet object that needs to be added to the store") +, + token_petstore_auth: TokenModel = Security( + get_token_petstore_auth, scopes=["write:pets", "read:pets"] + ), +) -> Pet: # noqa: E501 + ... + + +@router.post( + "/pet/{petId}", + responses={ + 405: {"description": "Invalid input"}, + }, + tags=["pet"], + summary="Updates a pet in the store with form data", +) +async def update_pet_with_form( + petId: int = Path(None, description="ID of pet that needs to be updated") +, + name: str = Form(None, description="Updated name of the pet") +, + status: str = Form(None, description="Updated status of the pet") +, + token_petstore_auth: TokenModel = Security( + get_token_petstore_auth, scopes=["write:pets", "read:pets"] + ), +) -> None: # noqa: E501 + ... + + +@router.post( + "/pet/{petId}/uploadImage", + responses={ + 200: {"model": ApiResponse, "description": "successful operation"}, + }, + tags=["pet"], + summary="uploads an image", +) +async def upload_file( + petId: int = Path(None, description="ID of pet to update") +, + additional_metadata: str = Form(None, description="Additional data to pass to server") +, + file: str = Form(None, description="file to upload") +, + token_petstore_auth: TokenModel = Security( + get_token_petstore_auth, scopes=["write:pets", "read:pets"] + ), +) -> ApiResponse: # noqa: E501 + ... diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/apis/store_api.py b/samples/server/petstore/python-fastapi/src/openapi_server/apis/store_api.py new file mode 100644 index 000000000000..dd7a484d3dbd --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/apis/store_api.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +from typing import Dict, List + +from fastapi import ( + APIRouter, + Body, + Cookie, + Depends, + Form, + Header, + Path, + Query, + Response, + Security, + status, +) + +from openapi_server.models.extra_models import TokenModel +from openapi_server.models.order import Order +from openapi_server.security_api import get_token_api_key + +router = APIRouter() + + +@router.delete( + "/store/order/{orderId}", + responses={ + 400: {"description": "Invalid ID supplied"}, + 404: {"description": "Order not found"}, + }, + tags=["store"], + summary="Delete purchase order by ID", +) +async def delete_order( + orderId: str = Path(None, description="ID of the order that needs to be deleted") +, +) -> None: # noqa: E501 + """For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors""" + ... + + +@router.get( + "/store/inventory", + responses={ + 200: {"model": Dict[str, int], "description": "successful operation"}, + }, + tags=["store"], + summary="Returns pet inventories by status", +) +async def get_inventory( + token_api_key: TokenModel = Security( + get_token_api_key + ), +) -> Dict[str, int]: # noqa: E501 + """Returns a map of status codes to quantities""" + ... + + +@router.get( + "/store/order/{orderId}", + responses={ + 200: {"model": Order, "description": "successful operation"}, + 400: {"description": "Invalid ID supplied"}, + 404: {"description": "Order not found"}, + }, + tags=["store"], + summary="Find purchase order by ID", +) +async def get_order_by_id( + orderId: int = Path(None, description="ID of pet that needs to be fetched") +, +) -> Order: # noqa: E501 + """For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions""" + ... + + +@router.post( + "/store/order", + responses={ + 200: {"model": Order, "description": "successful operation"}, + 400: {"description": "Invalid Order"}, + }, + tags=["store"], + summary="Place an order for a pet", +) +async def place_order( + order: Order = Body(None, description="order placed for purchasing the pet") +, +) -> Order: # noqa: E501 + ... diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/apis/user_api.py b/samples/server/petstore/python-fastapi/src/openapi_server/apis/user_api.py new file mode 100644 index 000000000000..d6370178cd9e --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/apis/user_api.py @@ -0,0 +1,171 @@ +# coding: utf-8 + +from typing import Dict, List + +from fastapi import ( + APIRouter, + Body, + Cookie, + Depends, + Form, + Header, + Path, + Query, + Response, + Security, + status, +) + +from openapi_server.models.extra_models import TokenModel +from openapi_server.models.user import User +from openapi_server.security_api import get_token_api_key + +router = APIRouter() + + +@router.post( + "/user", + responses={ + 200: {"description": "successful operation"}, + }, + tags=["user"], + summary="Create user", +) +async def create_user( + user: User = Body(None, description="Created user object") +, + token_api_key: TokenModel = Security( + get_token_api_key + ), +) -> None: # noqa: E501 + """This can only be done by the logged in user.""" + ... + + +@router.post( + "/user/createWithArray", + responses={ + 200: {"description": "successful operation"}, + }, + tags=["user"], + summary="Creates list of users with given input array", +) +async def create_users_with_array_input( + user: List[User] = Body(None, description="List of user object") +, + token_api_key: TokenModel = Security( + get_token_api_key + ), +) -> None: # noqa: E501 + ... + + +@router.post( + "/user/createWithList", + responses={ + 200: {"description": "successful operation"}, + }, + tags=["user"], + summary="Creates list of users with given input array", +) +async def create_users_with_list_input( + user: List[User] = Body(None, description="List of user object") +, + token_api_key: TokenModel = Security( + get_token_api_key + ), +) -> None: # noqa: E501 + ... + + +@router.delete( + "/user/{username}", + responses={ + 400: {"description": "Invalid username supplied"}, + 404: {"description": "User not found"}, + }, + tags=["user"], + summary="Delete user", +) +async def delete_user( + username: str = Path(None, description="The name that needs to be deleted") +, + token_api_key: TokenModel = Security( + get_token_api_key + ), +) -> None: # noqa: E501 + """This can only be done by the logged in user.""" + ... + + +@router.get( + "/user/{username}", + responses={ + 200: {"model": User, "description": "successful operation"}, + 400: {"description": "Invalid username supplied"}, + 404: {"description": "User not found"}, + }, + tags=["user"], + summary="Get user by user name", +) +async def get_user_by_name( + username: str = Path(None, description="The name that needs to be fetched. Use user1 for testing.") +, +) -> User: # noqa: E501 + ... + + +@router.get( + "/user/login", + responses={ + 200: {"model": str, "description": "successful operation"}, + 400: {"description": "Invalid username/password supplied"}, + }, + tags=["user"], + summary="Logs user into the system", +) +async def login_user( + username: str = Query(None, description="The user name for login") +, + password: str = Query(None, description="The password for login in clear text") +, +) -> str: # noqa: E501 + ... + + +@router.get( + "/user/logout", + responses={ + 200: {"description": "successful operation"}, + }, + tags=["user"], + summary="Logs out current logged in user session", +) +async def logout_user( + token_api_key: TokenModel = Security( + get_token_api_key + ), +) -> None: # noqa: E501 + ... + + +@router.put( + "/user/{username}", + responses={ + 400: {"description": "Invalid user supplied"}, + 404: {"description": "User not found"}, + }, + tags=["user"], + summary="Updated user", +) +async def update_user( + username: str = Path(None, description="name that need to be deleted") +, + user: User = Body(None, description="Updated user object") +, + token_api_key: TokenModel = Security( + get_token_api_key + ), +) -> None: # noqa: E501 + """This can only be done by the logged in user.""" + ... diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/main.py b/samples/server/petstore/python-fastapi/src/openapi_server/main.py new file mode 100644 index 000000000000..eec13ca5eba9 --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/main.py @@ -0,0 +1,27 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from fastapi import FastAPI + +from openapi_server.apis.pet_api import router as PetApiRouter +from openapi_server.apis.store_api import router as StoreApiRouter +from openapi_server.apis.user_api import router as UserApiRouter + +app = FastAPI( + title="OpenAPI Petstore", + description="This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.", + version="1.0.0", +) + +app.include_router(PetApiRouter) +app.include_router(StoreApiRouter) +app.include_router(UserApiRouter) diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/__init__.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/api_response.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/api_response.py new file mode 100644 index 000000000000..49926a6a14d8 --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/models/api_response.py @@ -0,0 +1,24 @@ +# coding: utf-8 + +from datetime import date, datetime + +from typing import Dict, List, Optional + +from pydantic import BaseModel, EmailStr, validator + + +class ApiResponse(BaseModel): + """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + + Do not edit the class manually. + + ApiResponse - a model defined in OpenAPI + + code: The code of this ApiResponse [Optional]. + type: The type of this ApiResponse [Optional]. + message: The message of this ApiResponse [Optional]. + """ + + code: Optional[int] = None + type: Optional[str] = None + message: Optional[str] = None diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/category.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/category.py new file mode 100644 index 000000000000..cba9aece542b --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/models/category.py @@ -0,0 +1,22 @@ +# coding: utf-8 + +from datetime import date, datetime + +from typing import Dict, List, Optional + +from pydantic import BaseModel, EmailStr, validator + + +class Category(BaseModel): + """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + + Do not edit the class manually. + + Category - a model defined in OpenAPI + + id: The id of this Category [Optional]. + name: The name of this Category [Optional]. + """ + + id: Optional[int] = None + name: Optional[str] = None diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/extra_models.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/extra_models.py new file mode 100644 index 000000000000..a3a283fb842b --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/models/extra_models.py @@ -0,0 +1,8 @@ +# coding: utf-8 + +from pydantic import BaseModel + +class TokenModel(BaseModel): + """Defines a token model.""" + + sub: str diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/order.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/order.py new file mode 100644 index 000000000000..b129842ad2ca --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/models/order.py @@ -0,0 +1,30 @@ +# coding: utf-8 + +from datetime import date, datetime + +from typing import Dict, List, Optional + +from pydantic import BaseModel, EmailStr, validator + + +class Order(BaseModel): + """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + + Do not edit the class manually. + + Order - a model defined in OpenAPI + + id: The id of this Order [Optional]. + pet_id: The pet_id of this Order [Optional]. + quantity: The quantity of this Order [Optional]. + ship_date: The ship_date of this Order [Optional]. + status: The status of this Order [Optional]. + complete: The complete of this Order [Optional]. + """ + + id: Optional[int] = None + pet_id: Optional[int] = None + quantity: Optional[int] = None + ship_date: Optional[datetime] = None + status: Optional[str] = None + complete: Optional[bool] = None diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/pet.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/pet.py new file mode 100644 index 000000000000..c4e8c3fa4bfe --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/models/pet.py @@ -0,0 +1,32 @@ +# coding: utf-8 + +from datetime import date, datetime + +from typing import Dict, List, Optional + +from pydantic import BaseModel, EmailStr, validator +from openapi_server.models.category import Category +from openapi_server.models.tag import Tag + + +class Pet(BaseModel): + """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + + Do not edit the class manually. + + Pet - a model defined in OpenAPI + + id: The id of this Pet [Optional]. + category: The category of this Pet [Optional]. + name: The name of this Pet. + photo_urls: The photo_urls of this Pet. + tags: The tags of this Pet [Optional]. + status: The status of this Pet [Optional]. + """ + + id: Optional[int] = None + category: Optional[Category] = None + name: str + photo_urls: List[str] + tags: Optional[List[Tag]] = None + status: Optional[str] = None diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/tag.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/tag.py new file mode 100644 index 000000000000..6c2ab695415c --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/models/tag.py @@ -0,0 +1,22 @@ +# coding: utf-8 + +from datetime import date, datetime + +from typing import Dict, List, Optional + +from pydantic import BaseModel, EmailStr, validator + + +class Tag(BaseModel): + """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + + Do not edit the class manually. + + Tag - a model defined in OpenAPI + + id: The id of this Tag [Optional]. + name: The name of this Tag [Optional]. + """ + + id: Optional[int] = None + name: Optional[str] = None diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/user.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/user.py new file mode 100644 index 000000000000..dd173677ce9f --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/models/user.py @@ -0,0 +1,34 @@ +# coding: utf-8 + +from datetime import date, datetime + +from typing import Dict, List, Optional + +from pydantic import BaseModel, EmailStr, validator + + +class User(BaseModel): + """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + + Do not edit the class manually. + + User - a model defined in OpenAPI + + id: The id of this User [Optional]. + username: The username of this User [Optional]. + first_name: The first_name of this User [Optional]. + last_name: The last_name of this User [Optional]. + email: The email of this User [Optional]. + password: The password of this User [Optional]. + phone: The phone of this User [Optional]. + user_status: The user_status of this User [Optional]. + """ + + id: Optional[int] = None + username: Optional[str] = None + first_name: Optional[str] = None + last_name: Optional[str] = None + email: Optional[str] = None + password: Optional[str] = None + phone: Optional[str] = None + user_status: Optional[int] = None diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/security_api.py b/samples/server/petstore/python-fastapi/src/openapi_server/security_api.py new file mode 100644 index 000000000000..1c2f51e30a52 --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/security_api.py @@ -0,0 +1,83 @@ +# coding: utf-8 + +from typing import List + +from fastapi import APIRouter, Depends, Response, Security, status +from fastapi.openapi.models import OAuthFlowImplicit, OAuthFlows +from fastapi.security import ( + HTTPAuthorizationCredentials, + HTTPBasic, + HTTPBasicCredentials, + HTTPBearer, + OAuth2, + OAuth2AuthorizationCodeBearer, + OAuth2PasswordBearer, + SecurityScopes, +) +from fastapi.security.api_key import APIKey, APIKeyCookie, APIKeyHeader, APIKeyQuery + +from openapi_server.models.extra_models import TokenModel + + +def get_token_api_key( + token_api_key_header: str = Security( + APIKeyHeader(name="api_key", auto_error=False) + ), +) -> TokenModel: + """ + Check and retrieve authentication information from api_key. + + :param token_api_key_header API key provided by Authorization[api_key] header + + + :type token_api_key_header: str + :return: Information attached to provided api_key or None if api_key is invalid or does not allow access to called API + :rtype: TokenModel | None + """ + + ... + +oauth2_implicit = OAuth2( + flows=OAuthFlows( + implicit=OAuthFlowImplicit( + authorizationUrl="http://petstore.swagger.io/api/oauth/dialog", + scopes={ + "write:pets": "modify pets in your account", + "read:pets": "read your pets", + } + ) + ) +) + + +def get_token_petstore_auth( + security_scopes: SecurityScopes, token: str = Depends(oauth2_implicit) +) -> TokenModel: + """ + Validate and decode token. + + :param token Token provided by Authorization header + :type token: str + :return: Decoded token information or None if token is invalid + :rtype: TokenModel | None + """ + + ... + + +def validate_scope_petstore_auth( + required_scopes: SecurityScopes, token_scopes: List[str] +) -> bool: + """ + Validate required scopes are included in token scope + + :param required_scopes Required scope to access called API + :type required_scopes: List[str] + :param token_scopes Scope present in token + :type token_scopes: List[str] + :return: True if access to called API is allowed + :rtype: bool + """ + + return False + diff --git a/samples/server/petstore/python-fastapi/tests/conftest.py b/samples/server/petstore/python-fastapi/tests/conftest.py new file mode 100644 index 000000000000..0f1845c60412 --- /dev/null +++ b/samples/server/petstore/python-fastapi/tests/conftest.py @@ -0,0 +1,20 @@ +import contextlib +from typing import Any + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from openapi_server.main import app as application + + +@pytest.fixture +def app() -> FastAPI: + application.dependency_overrides = {} + + return application + + +@pytest.fixture +def client(app) -> TestClient: + return TestClient(app) diff --git a/samples/server/petstore/python-fastapi/tests/test_pet_api.py b/samples/server/petstore/python-fastapi/tests/test_pet_api.py new file mode 100644 index 000000000000..5124a86bc915 --- /dev/null +++ b/samples/server/petstore/python-fastapi/tests/test_pet_api.py @@ -0,0 +1,165 @@ +# coding: utf-8 + +from fastapi.testclient import TestClient + +import json +import pytest + +from openapi_server.models.api_response import ApiResponse +from openapi_server.models.pet import Pet + + +def test_add_pet(client: TestClient): + """Test case for add_pet + + Add a new pet to the store + """ + pet = {"photo_urls":["photoUrls","photoUrls"],"name":"doggie","id":0,"category":{"name":"name","id":6},"tags":[{"name":"name","id":1},{"name":"name","id":1}],"status":"available"} + headers = { + 'Authorization': 'Bearer special-key', + } + response = client.request( + 'POST', + '/pet', + headers=headers, + json=pet, + ) + + assert response.status_code == 200 + + +def test_delete_pet(client: TestClient): + """Test case for delete_pet + + Deletes a pet + """ + headers = { + 'api_key': 'api_key_example', + 'Authorization': 'Bearer special-key', + } + response = client.request( + 'DELETE', + '/pet/{petId}'.format(petId=56), + headers=headers, + ) + + assert response.status_code == 200 + + +def test_find_pets_by_status(client: TestClient): + """Test case for find_pets_by_status + + Finds Pets by status + """ + params = [("status", ['status_example'])] + headers = { + 'Authorization': 'Bearer special-key', + } + response = client.request( + 'GET', + '/pet/findByStatus', + headers=headers, + params=params, + ) + + assert response.status_code == 200 + + +def test_find_pets_by_tags(client: TestClient): + """Test case for find_pets_by_tags + + Finds Pets by tags + """ + params = [("tags", ['tags_example'])] + headers = { + 'Authorization': 'Bearer special-key', + } + response = client.request( + 'GET', + '/pet/findByTags', + headers=headers, + params=params, + ) + + assert response.status_code == 200 + + +def test_get_pet_by_id(client: TestClient): + """Test case for get_pet_by_id + + Find pet by ID + """ + headers = { + 'api_key': 'special-key', + } + response = client.request( + 'GET', + '/pet/{petId}'.format(petId=56), + headers=headers, + ) + + assert response.status_code == 200 + + +def test_update_pet(client: TestClient): + """Test case for update_pet + + Update an existing pet + """ + pet = {"photo_urls":["photoUrls","photoUrls"],"name":"doggie","id":0,"category":{"name":"name","id":6},"tags":[{"name":"name","id":1},{"name":"name","id":1}],"status":"available"} + headers = { + 'Authorization': 'Bearer special-key', + } + response = client.request( + 'PUT', + '/pet', + headers=headers, + json=pet, + ) + + assert response.status_code == 200 + + +def test_update_pet_with_form(client: TestClient): + """Test case for update_pet_with_form + + Updates a pet in the store with form data + """ + headers = { + 'Authorization': 'Bearer special-key', + } + data = { + 'name': 'name_example', + 'status': 'status_example' + } + response = client.request( + 'POST', + '/pet/{petId}'.format(petId=56), + headers=headers, + data=data, + ) + + assert response.status_code == 200 + + +def test_upload_file(client: TestClient): + """Test case for upload_file + + uploads an image + """ + headers = { + 'Authorization': 'Bearer special-key', + } + data = { + 'additional_metadata': 'additional_metadata_example', + 'file': '/path/to/file' + } + response = client.request( + 'POST', + '/pet/{petId}/uploadImage'.format(petId=56), + headers=headers, + data=data, + ) + + assert response.status_code == 200 + diff --git a/samples/server/petstore/python-fastapi/tests/test_store_api.py b/samples/server/petstore/python-fastapi/tests/test_store_api.py new file mode 100644 index 000000000000..8cd5effb77ee --- /dev/null +++ b/samples/server/petstore/python-fastapi/tests/test_store_api.py @@ -0,0 +1,76 @@ +# coding: utf-8 + +from fastapi.testclient import TestClient + +import json +import pytest + +from openapi_server.models.order import Order + + +def test_delete_order(client: TestClient): + """Test case for delete_order + + Delete purchase order by ID + """ + headers = { + } + response = client.request( + 'DELETE', + '/store/order/{orderId}'.format(orderId='order_id_example'), + headers=headers, + ) + + assert response.status_code == 200 + + +def test_get_inventory(client: TestClient): + """Test case for get_inventory + + Returns pet inventories by status + """ + headers = { + 'api_key': 'special-key', + } + response = client.request( + 'GET', + '/store/inventory', + headers=headers, + ) + + assert response.status_code == 200 + + +def test_get_order_by_id(client: TestClient): + """Test case for get_order_by_id + + Find purchase order by ID + """ + headers = { + } + response = client.request( + 'GET', + '/store/order/{orderId}'.format(orderId=56), + headers=headers, + ) + + assert response.status_code == 200 + + +def test_place_order(client: TestClient): + """Test case for place_order + + Place an order for a pet + """ + order = {"pet_id":6,"quantity":1,"id":0,"ship_date":"2000-01-23T04:56:07.000+00:00","complete":0,"status":"placed"} + headers = { + } + response = client.request( + 'POST', + '/store/order', + headers=headers, + json=order, + ) + + assert response.status_code == 200 + diff --git a/samples/server/petstore/python-fastapi/tests/test_user_api.py b/samples/server/petstore/python-fastapi/tests/test_user_api.py new file mode 100644 index 000000000000..537696ef9750 --- /dev/null +++ b/samples/server/petstore/python-fastapi/tests/test_user_api.py @@ -0,0 +1,154 @@ +# coding: utf-8 + +from fastapi.testclient import TestClient + +import json +import pytest + +from openapi_server.models.user import User + + +def test_create_user(client: TestClient): + """Test case for create_user + + Create user + """ + user = {"first_name":"firstName","last_name":"lastName","password":"password","user_status":6,"phone":"phone","id":0,"email":"email","username":"username"} + headers = { + 'api_key': 'special-key', + } + response = client.request( + 'POST', + '/user', + headers=headers, + json=user, + ) + + assert response.status_code == 200 + + +def test_create_users_with_array_input(client: TestClient): + """Test case for create_users_with_array_input + + Creates list of users with given input array + """ + user = [{"first_name":"firstName","last_name":"lastName","password":"password","user_status":6,"phone":"phone","id":0,"email":"email","username":"username"}] + headers = { + 'api_key': 'special-key', + } + response = client.request( + 'POST', + '/user/createWithArray', + headers=headers, + json=user, + ) + + assert response.status_code == 200 + + +def test_create_users_with_list_input(client: TestClient): + """Test case for create_users_with_list_input + + Creates list of users with given input array + """ + user = [{"first_name":"firstName","last_name":"lastName","password":"password","user_status":6,"phone":"phone","id":0,"email":"email","username":"username"}] + headers = { + 'api_key': 'special-key', + } + response = client.request( + 'POST', + '/user/createWithList', + headers=headers, + json=user, + ) + + assert response.status_code == 200 + + +def test_delete_user(client: TestClient): + """Test case for delete_user + + Delete user + """ + headers = { + 'api_key': 'special-key', + } + response = client.request( + 'DELETE', + '/user/{username}'.format(username='username_example'), + headers=headers, + ) + + assert response.status_code == 200 + + +def test_get_user_by_name(client: TestClient): + """Test case for get_user_by_name + + Get user by user name + """ + headers = { + } + response = client.request( + 'GET', + '/user/{username}'.format(username='username_example'), + headers=headers, + ) + + assert response.status_code == 200 + + +def test_login_user(client: TestClient): + """Test case for login_user + + Logs user into the system + """ + params = [("username", 'username_example'), + ("password", 'password_example')] + headers = { + } + response = client.request( + 'GET', + '/user/login', + headers=headers, + params=params, + ) + + assert response.status_code == 200 + + +def test_logout_user(client: TestClient): + """Test case for logout_user + + Logs out current logged in user session + """ + headers = { + 'api_key': 'special-key', + } + response = client.request( + 'GET', + '/user/logout', + headers=headers, + ) + + assert response.status_code == 200 + + +def test_update_user(client: TestClient): + """Test case for update_user + + Updated user + """ + user = {"first_name":"firstName","last_name":"lastName","password":"password","user_status":6,"phone":"phone","id":0,"email":"email","username":"username"} + headers = { + 'api_key': 'special-key', + } + response = client.request( + 'PUT', + '/user/{username}'.format(username='username_example'), + headers=headers, + json=user, + ) + + assert response.status_code == 200 + diff --git a/samples/server/petstore/python-flask/.openapi-generator/VERSION b/samples/server/petstore/python-flask/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/python-flask/.openapi-generator/VERSION +++ b/samples/server/petstore/python-flask/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/python-flask/requirements.txt b/samples/server/petstore/python-flask/requirements.txt index 72ed547c4429..70e1f0c55402 100644 --- a/samples/server/petstore/python-flask/requirements.txt +++ b/samples/server/petstore/python-flask/requirements.txt @@ -8,3 +8,4 @@ werkzeug == 0.16.1; python_version=="3.5" or python_version=="3.4" swagger-ui-bundle >= 0.0.2 python_dateutil >= 2.6.0 setuptools >= 21.0.0 +Flask == 1.1.2 diff --git a/samples/server/petstore/ruby-sinatra/.openapi-generator/FILES b/samples/server/petstore/ruby-sinatra/.openapi-generator/FILES new file mode 100644 index 000000000000..573dd33a9b2b --- /dev/null +++ b/samples/server/petstore/ruby-sinatra/.openapi-generator/FILES @@ -0,0 +1,10 @@ +Dockerfile +Gemfile +README.md +api/pet_api.rb +api/store_api.rb +api/user_api.rb +config.ru +lib/openapiing.rb +my_app.rb +openapi.yaml diff --git a/samples/server/petstore/ruby-sinatra/.openapi-generator/VERSION b/samples/server/petstore/ruby-sinatra/.openapi-generator/VERSION index d168f1d8bdaa..d509cc92aa80 100644 --- a/samples/server/petstore/ruby-sinatra/.openapi-generator/VERSION +++ b/samples/server/petstore/ruby-sinatra/.openapi-generator/VERSION @@ -1 +1 @@ -4.2.1-SNAPSHOT \ No newline at end of file +5.1.1-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/ruby-sinatra/Dockerfile b/samples/server/petstore/ruby-sinatra/Dockerfile new file mode 100644 index 000000000000..41be83d48ece --- /dev/null +++ b/samples/server/petstore/ruby-sinatra/Dockerfile @@ -0,0 +1,32 @@ +## Build libraries +FROM ruby:3.0-alpine as rubydev + +## for thin or falcon +#RUN apk --no-cache add make g++ libc-dev +## for puma +#RUN apk --no-cache add make gcc libc-dev + +ADD . /app +WORKDIR /app + +RUN bundle config set path lib +RUN bundle install + +## Build Runtime image +FROM ruby:3.0-alpine + +RUN apk --no-cache add tzdata ## ca-certificates + +COPY --from=rubydev /app /app +WORKDIR /app + +ENV SINATRA_HOST 0.0.0.0 +ENV SINATRA_PORT 8080 +EXPOSE $SINATRA_PORT + +RUN addgroup sinatra +RUN adduser -S -G sinatra sinatra +USER sinatra +RUN bundle config set path lib + +CMD bundle exec rackup --host $SINATRA_HOST -p $SINATRA_PORT diff --git a/samples/server/petstore/ruby-sinatra/Gemfile b/samples/server/petstore/ruby-sinatra/Gemfile index be9c3168ea6f..90d7b0e3bcdc 100644 --- a/samples/server/petstore/ruby-sinatra/Gemfile +++ b/samples/server/petstore/ruby-sinatra/Gemfile @@ -1,4 +1,5 @@ source 'https://rubygems.org' +gem "webrick" gem "sinatra" -gem "sinatra-cross_origin" \ No newline at end of file +gem "sinatra-cross_origin" diff --git a/samples/server/petstore/ruby-sinatra/README.md b/samples/server/petstore/ruby-sinatra/README.md index bf132cb042a2..aecb705a1946 100644 --- a/samples/server/petstore/ruby-sinatra/README.md +++ b/samples/server/petstore/ruby-sinatra/README.md @@ -1,4 +1,4 @@ -# Swagger for Sinatra +# OpenAPI for Sinatra ## Overview This is a project to provide Swagger support inside the [Sinatra](http://www.sinatrarb.com/) framework. You can find @@ -6,24 +6,60 @@ out more about both the spec and the framework at http://swagger.io. For more i Wordnik's APIs, please visit http://developer.wordnik.com. ## Prerequisites -You need to install ruby 1.9.3 and the following gems: +As of ruby 3.0.0, the webrick web server library was removed. +You need to install a rack-supported web server, such as webrick and thin. + +The default Gemfile is as follows. +Update the name of the web server as your prefer. ``` -sinatra -sinatra-cross_origin +source 'https://rubygems.org' + +gem "webrick" +gem "sinatra" +gem "sinatra-cross_origin" ``` ## Getting started -This sample was generated with the [OpenAPI Generator](https://github.com/openapitools/openapi-generator) project. +To generate a ruby-sinatra server for petstore.yaml, please run the following: + +``` +openapi-generator-cli generate \ + -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml \ + -g ruby-sinatra -o code +``` + +To run the generated server, please run the following: + +``` +cd code/ +bundle config set path lib +bundle install +bundle exec rackup -p 8080 +``` + +You can access the application by the following URL: + +``` +http://localhost:8080/v2/store/inventory +``` + +## Docker +If you want to use a web server other than webrick, you need to edit the generated Dockerfile to prepare the compiler and the make command. Please check the comment of the Dockerfile. + +To run the code on docker, you can use the Dockerfile as follows: + +### Build the docker image +The "container_name" can be changed for your preferences. ``` -rackup -p 4567 config.ru +docker build . --tag "container_name" ``` -In your [swagger ui](https://github.com/swagger-api/swagger-ui), put in the following URL: +### Run the docker image ``` -http://localhost:4567/resources.json +docker run -it --rm -p 8080:8080 "container_name" ``` Voila! diff --git a/samples/server/petstore/ruby-sinatra/api/pet_api.rb b/samples/server/petstore/ruby-sinatra/api/pet_api.rb index f17047e217b8..c92b77b099c9 100644 --- a/samples/server/petstore/ruby-sinatra/api/pet_api.rb +++ b/samples/server/petstore/ruby-sinatra/api/pet_api.rb @@ -5,7 +5,7 @@ "resourcePath" => "/Pet", "summary" => "Add a new pet to the store", "nickname" => "add_pet", - "responseClass" => "void", + "responseClass" => "Pet", "endpoint" => "/pet", "notes" => "", "parameters" => [ @@ -123,7 +123,7 @@ "resourcePath" => "/Pet", "summary" => "Update an existing pet", "nickname" => "update_pet", - "responseClass" => "void", + "responseClass" => "Pet", "endpoint" => "/pet", "notes" => "", "parameters" => [ diff --git a/samples/server/petstore/ruby-sinatra/openapi.yaml b/samples/server/petstore/ruby-sinatra/openapi.yaml index 2a48cecf82bb..26aaeac34b7d 100644 --- a/samples/server/petstore/ruby-sinatra/openapi.yaml +++ b/samples/server/petstore/ruby-sinatra/openapi.yaml @@ -26,7 +26,16 @@ paths: requestBody: $ref: '#/components/requestBodies/Pet' responses: - 405: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "405": description: Invalid input security: - petstore_auth: @@ -40,11 +49,20 @@ paths: requestBody: $ref: '#/components/requestBodies/Pet' responses: - 400: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "400": description: Invalid ID supplied - 404: + "404": description: Pet not found - 405: + "405": description: Validation exception security: - petstore_auth: @@ -74,7 +92,7 @@ paths: type: array style: form responses: - 200: + "200": content: application/xml: schema: @@ -87,7 +105,7 @@ paths: $ref: '#/components/schemas/Pet' type: array description: successful operation - 400: + "400": description: Invalid status value security: - petstore_auth: @@ -113,7 +131,7 @@ paths: type: array style: form responses: - 200: + "200": content: application/xml: schema: @@ -126,7 +144,7 @@ paths: $ref: '#/components/schemas/Pet' type: array description: successful operation - 400: + "400": description: Invalid tag value security: - petstore_auth: @@ -155,7 +173,7 @@ paths: type: integer style: simple responses: - 400: + "400": description: Invalid pet value security: - petstore_auth: @@ -178,7 +196,7 @@ paths: type: integer style: simple responses: - 200: + "200": content: application/xml: schema: @@ -187,9 +205,9 @@ paths: schema: $ref: '#/components/schemas/Pet' description: successful operation - 400: + "400": description: Invalid ID supplied - 404: + "404": description: Pet not found security: - api_key: [] @@ -222,7 +240,7 @@ paths: type: string type: object responses: - 405: + "405": description: Invalid input security: - petstore_auth: @@ -259,7 +277,7 @@ paths: type: string type: object responses: - 200: + "200": content: application/json: schema: @@ -277,7 +295,7 @@ paths: description: Returns a map of status codes to quantities operationId: getInventory responses: - 200: + "200": content: application/json: schema: @@ -302,7 +320,7 @@ paths: description: order placed for purchasing the pet required: true responses: - 200: + "200": content: application/xml: schema: @@ -311,7 +329,7 @@ paths: schema: $ref: '#/components/schemas/Order' description: successful operation - 400: + "400": description: Invalid Order summary: Place an order for a pet tags: @@ -331,9 +349,9 @@ paths: type: string style: simple responses: - 400: + "400": description: Invalid ID supplied - 404: + "404": description: Order not found summary: Delete purchase order by ID tags: @@ -355,7 +373,7 @@ paths: type: integer style: simple responses: - 200: + "200": content: application/xml: schema: @@ -364,9 +382,9 @@ paths: schema: $ref: '#/components/schemas/Order' description: successful operation - 400: + "400": description: Invalid ID supplied - 404: + "404": description: Order not found summary: Find purchase order by ID tags: @@ -386,7 +404,7 @@ paths: default: description: successful operation security: - - auth_cookie: [] + - api_key: [] summary: Create user tags: - user @@ -399,7 +417,7 @@ paths: default: description: successful operation security: - - auth_cookie: [] + - api_key: [] summary: Creates list of users with given input array tags: - user @@ -412,7 +430,7 @@ paths: default: description: successful operation security: - - auth_cookie: [] + - api_key: [] summary: Creates list of users with given input array tags: - user @@ -438,7 +456,7 @@ paths: type: string style: form responses: - 200: + "200": content: application/xml: schema: @@ -449,8 +467,8 @@ paths: description: successful operation headers: Set-Cookie: - description: Cookie authentication key for use with the `auth_cookie` - apiKey authentication. + description: Cookie authentication key for use with the `api_key` apiKey + authentication. explode: false schema: example: AUTH_KEY=abcde12345; Path=/; HttpOnly @@ -470,7 +488,7 @@ paths: format: date-time type: string style: simple - 400: + "400": description: Invalid username/password supplied summary: Logs user into the system tags: @@ -482,7 +500,7 @@ paths: default: description: successful operation security: - - auth_cookie: [] + - api_key: [] summary: Logs out current logged in user session tags: - user @@ -500,12 +518,12 @@ paths: type: string style: simple responses: - 400: + "400": description: Invalid username supplied - 404: + "404": description: User not found security: - - auth_cookie: [] + - api_key: [] summary: Delete user tags: - user @@ -521,7 +539,7 @@ paths: type: string style: simple responses: - 200: + "200": content: application/xml: schema: @@ -530,9 +548,9 @@ paths: schema: $ref: '#/components/schemas/User' description: successful operation - 400: + "400": description: Invalid username supplied - 404: + "404": description: User not found summary: Get user by user name tags: @@ -557,12 +575,12 @@ paths: description: Updated user object required: true responses: - 400: + "400": description: Invalid user supplied - 404: + "404": description: User not found security: - - auth_cookie: [] + - api_key: [] summary: Updated user tags: - user @@ -802,7 +820,3 @@ components: in: header name: api_key type: apiKey - auth_cookie: - in: cookie - name: AUTH_KEY - type: apiKey diff --git a/samples/server/petstore/ruby-sinatra/swagger.yaml b/samples/server/petstore/ruby-sinatra/swagger.yaml deleted file mode 100644 index bc7c6e9ae1d5..000000000000 --- a/samples/server/petstore/ruby-sinatra/swagger.yaml +++ /dev/null @@ -1,713 +0,0 @@ ---- -swagger: "2.0" -info: - description: "This is a sample server Petstore server. You can find out more about\ - \ Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).\ - \ For this sample, you can use the api key `special-key` to test the authorization\ - \ filters." - version: "1.0.0" - title: "Swagger Petstore" - termsOfService: "http://swagger.io/terms/" - contact: - email: "apiteam@swagger.io" - license: - name: "Apache 2.0" - url: "https://www.apache.org/licenses/LICENSE-2.0.html" -host: "petstore.swagger.io" -basePath: "/v2" -tags: -- name: "pet" - description: "Everything about your Pets" - externalDocs: - description: "Find out more" - url: "http://swagger.io" -- name: "store" - description: "Access to Petstore orders" -- name: "user" - description: "Operations about user" - externalDocs: - description: "Find out more about our store" - url: "http://swagger.io" -schemes: -- "http" -paths: - /pet: - post: - tags: - - "pet" - summary: "Add a new pet to the store" - description: "" - operationId: "addPet" - consumes: - - "application/json" - - "application/xml" - produces: - - "application/xml" - - "application/json" - parameters: - - in: "body" - name: "body" - description: "Pet object that needs to be added to the store" - required: true - schema: - $ref: "#/definitions/Pet" - responses: - 405: - description: "Invalid input" - security: - - petstore_auth: - - "write:pets" - - "read:pets" - put: - tags: - - "pet" - summary: "Update an existing pet" - description: "" - operationId: "updatePet" - consumes: - - "application/json" - - "application/xml" - produces: - - "application/xml" - - "application/json" - parameters: - - in: "body" - name: "body" - description: "Pet object that needs to be added to the store" - required: true - schema: - $ref: "#/definitions/Pet" - responses: - 400: - description: "Invalid ID supplied" - 404: - description: "Pet not found" - 405: - description: "Validation exception" - security: - - petstore_auth: - - "write:pets" - - "read:pets" - /pet/findByStatus: - get: - tags: - - "pet" - summary: "Finds Pets by status" - description: "Multiple status values can be provided with comma separated strings" - operationId: "findPetsByStatus" - produces: - - "application/xml" - - "application/json" - parameters: - - name: "status" - in: "query" - description: "Status values that need to be considered for filter" - required: true - type: "array" - items: - type: "string" - enum: - - "available" - - "pending" - - "sold" - default: "available" - collectionFormat: "csv" - responses: - 200: - description: "successful operation" - schema: - type: "array" - items: - $ref: "#/definitions/Pet" - 400: - description: "Invalid status value" - security: - - petstore_auth: - - "write:pets" - - "read:pets" - /pet/findByTags: - get: - tags: - - "pet" - summary: "Finds Pets by tags" - description: "Multiple tags can be provided with comma separated strings. Use\ - \ tag1, tag2, tag3 for testing." - operationId: "findPetsByTags" - produces: - - "application/xml" - - "application/json" - parameters: - - name: "tags" - in: "query" - description: "Tags to filter by" - required: true - type: "array" - items: - type: "string" - collectionFormat: "csv" - responses: - 200: - description: "successful operation" - schema: - type: "array" - items: - $ref: "#/definitions/Pet" - 400: - description: "Invalid tag value" - security: - - petstore_auth: - - "write:pets" - - "read:pets" - /pet/{petId}: - get: - tags: - - "pet" - summary: "Find pet by ID" - description: "Returns a single pet" - operationId: "getPetById" - produces: - - "application/xml" - - "application/json" - parameters: - - name: "petId" - in: "path" - description: "ID of pet to return" - required: true - type: "integer" - format: "int64" - responses: - 200: - description: "successful operation" - schema: - $ref: "#/definitions/Pet" - 400: - description: "Invalid ID supplied" - 404: - description: "Pet not found" - security: - - api_key: [] - post: - tags: - - "pet" - summary: "Updates a pet in the store with form data" - description: "" - operationId: "updatePetWithForm" - consumes: - - "application/x-www-form-urlencoded" - produces: - - "application/xml" - - "application/json" - parameters: - - name: "petId" - in: "path" - description: "ID of pet that needs to be updated" - required: true - type: "integer" - format: "int64" - - name: "name" - in: "formData" - description: "Updated name of the pet" - required: false - type: "string" - - name: "status" - in: "formData" - description: "Updated status of the pet" - required: false - type: "string" - responses: - 405: - description: "Invalid input" - security: - - petstore_auth: - - "write:pets" - - "read:pets" - delete: - tags: - - "pet" - summary: "Deletes a pet" - description: "" - operationId: "deletePet" - produces: - - "application/xml" - - "application/json" - parameters: - - name: "api_key" - in: "header" - required: false - type: "string" - - name: "petId" - in: "path" - description: "Pet id to delete" - required: true - type: "integer" - format: "int64" - responses: - 400: - description: "Invalid pet value" - security: - - petstore_auth: - - "write:pets" - - "read:pets" - /pet/{petId}/uploadImage: - post: - tags: - - "pet" - summary: "uploads an image" - description: "" - operationId: "uploadFile" - consumes: - - "multipart/form-data" - produces: - - "application/json" - parameters: - - name: "petId" - in: "path" - description: "ID of pet to update" - required: true - type: "integer" - format: "int64" - - name: "additionalMetadata" - in: "formData" - description: "Additional data to pass to server" - required: false - type: "string" - - name: "file" - in: "formData" - description: "file to upload" - required: false - type: "file" - responses: - 200: - description: "successful operation" - schema: - $ref: "#/definitions/ApiResponse" - security: - - petstore_auth: - - "write:pets" - - "read:pets" - /store/inventory: - get: - tags: - - "store" - summary: "Returns pet inventories by status" - description: "Returns a map of status codes to quantities" - operationId: "getInventory" - produces: - - "application/json" - parameters: [] - responses: - 200: - description: "successful operation" - schema: - type: "object" - additionalProperties: - type: "integer" - format: "int32" - security: - - api_key: [] - /store/order: - post: - tags: - - "store" - summary: "Place an order for a pet" - description: "" - operationId: "placeOrder" - produces: - - "application/xml" - - "application/json" - parameters: - - in: "body" - name: "body" - description: "order placed for purchasing the pet" - required: true - schema: - $ref: "#/definitions/Order" - responses: - 200: - description: "successful operation" - schema: - $ref: "#/definitions/Order" - 400: - description: "Invalid Order" - /store/order/{orderId}: - get: - tags: - - "store" - summary: "Find purchase order by ID" - description: "For valid response try integer IDs with value <= 5 or > 10. Other\ - \ values will generated exceptions" - operationId: "getOrderById" - produces: - - "application/xml" - - "application/json" - parameters: - - name: "orderId" - in: "path" - description: "ID of pet that needs to be fetched" - required: true - type: "integer" - maximum: 5 - minimum: 1 - format: "int64" - responses: - 200: - description: "successful operation" - schema: - $ref: "#/definitions/Order" - 400: - description: "Invalid ID supplied" - 404: - description: "Order not found" - delete: - tags: - - "store" - summary: "Delete purchase order by ID" - description: "For valid response try integer IDs with value < 1000. Anything\ - \ above 1000 or nonintegers will generate API errors" - operationId: "deleteOrder" - produces: - - "application/xml" - - "application/json" - parameters: - - name: "orderId" - in: "path" - description: "ID of the order that needs to be deleted" - required: true - type: "string" - responses: - 400: - description: "Invalid ID supplied" - 404: - description: "Order not found" - /user: - post: - tags: - - "user" - summary: "Create user" - description: "This can only be done by the logged in user." - operationId: "createUser" - produces: - - "application/xml" - - "application/json" - parameters: - - in: "body" - name: "body" - description: "Created user object" - required: true - schema: - $ref: "#/definitions/User" - responses: - default: - description: "successful operation" - /user/createWithArray: - post: - tags: - - "user" - summary: "Creates list of users with given input array" - description: "" - operationId: "createUsersWithArrayInput" - produces: - - "application/xml" - - "application/json" - parameters: - - in: "body" - name: "body" - description: "List of user object" - required: true - schema: - type: "array" - items: - $ref: "#/definitions/User" - responses: - default: - description: "successful operation" - /user/createWithList: - post: - tags: - - "user" - summary: "Creates list of users with given input array" - description: "" - operationId: "createUsersWithListInput" - produces: - - "application/xml" - - "application/json" - parameters: - - in: "body" - name: "body" - description: "List of user object" - required: true - schema: - type: "array" - items: - $ref: "#/definitions/User" - responses: - default: - description: "successful operation" - /user/login: - get: - tags: - - "user" - summary: "Logs user into the system" - description: "" - operationId: "loginUser" - produces: - - "application/xml" - - "application/json" - parameters: - - name: "username" - in: "query" - description: "The user name for login" - required: true - type: "string" - - name: "password" - in: "query" - description: "The password for login in clear text" - required: true - type: "string" - responses: - 200: - description: "successful operation" - schema: - type: "string" - headers: - X-Rate-Limit: - type: "integer" - format: "int32" - description: "calls per hour allowed by the user" - X-Expires-After: - type: "string" - format: "date-time" - description: "date in UTC when toekn expires" - 400: - description: "Invalid username/password supplied" - /user/logout: - get: - tags: - - "user" - summary: "Logs out current logged in user session" - description: "" - operationId: "logoutUser" - produces: - - "application/xml" - - "application/json" - parameters: [] - responses: - default: - description: "successful operation" - /user/{username}: - get: - tags: - - "user" - summary: "Get user by user name" - description: "" - operationId: "getUserByName" - produces: - - "application/xml" - - "application/json" - parameters: - - name: "username" - in: "path" - description: "The name that needs to be fetched. Use user1 for testing. " - required: true - type: "string" - responses: - 200: - description: "successful operation" - schema: - $ref: "#/definitions/User" - 400: - description: "Invalid username supplied" - 404: - description: "User not found" - put: - tags: - - "user" - summary: "Updated user" - description: "This can only be done by the logged in user." - operationId: "updateUser" - produces: - - "application/xml" - - "application/json" - parameters: - - name: "username" - in: "path" - description: "name that need to be deleted" - required: true - type: "string" - - in: "body" - name: "body" - description: "Updated user object" - required: true - schema: - $ref: "#/definitions/User" - responses: - 400: - description: "Invalid user supplied" - 404: - description: "User not found" - delete: - tags: - - "user" - summary: "Delete user" - description: "This can only be done by the logged in user." - operationId: "deleteUser" - produces: - - "application/xml" - - "application/json" - parameters: - - name: "username" - in: "path" - description: "The name that needs to be deleted" - required: true - type: "string" - responses: - 400: - description: "Invalid username supplied" - 404: - description: "User not found" -securityDefinitions: - petstore_auth: - type: "oauth2" - authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" - flow: "implicit" - scopes: - write:pets: "modify pets in your account" - read:pets: "read your pets" - api_key: - type: "apiKey" - name: "api_key" - in: "header" -definitions: - Order: - type: "object" - properties: - id: - type: "integer" - format: "int64" - petId: - type: "integer" - format: "int64" - quantity: - type: "integer" - format: "int32" - shipDate: - type: "string" - format: "date-time" - status: - type: "string" - description: "Order Status" - enum: - - "placed" - - "approved" - - "delivered" - complete: - type: "boolean" - default: false - title: "Pet Order" - description: "An order for a pets from the pet store" - xml: - name: "Order" - Category: - type: "object" - properties: - id: - type: "integer" - format: "int64" - name: - type: "string" - title: "Pet category" - description: "A category for a pet" - xml: - name: "Category" - User: - type: "object" - properties: - id: - type: "integer" - format: "int64" - username: - type: "string" - firstName: - type: "string" - lastName: - type: "string" - email: - type: "string" - password: - type: "string" - phone: - type: "string" - userStatus: - type: "integer" - format: "int32" - description: "User Status" - title: "a User" - description: "A User who is purchasing from the pet store" - xml: - name: "User" - Tag: - type: "object" - properties: - id: - type: "integer" - format: "int64" - name: - type: "string" - title: "Pet Tag" - description: "A tag for a pet" - xml: - name: "Tag" - Pet: - type: "object" - required: - - "name" - - "photoUrls" - properties: - id: - type: "integer" - format: "int64" - category: - $ref: "#/definitions/Category" - name: - type: "string" - example: "doggie" - photoUrls: - type: "array" - xml: - name: "photoUrl" - wrapped: true - items: - type: "string" - tags: - type: "array" - xml: - name: "tag" - wrapped: true - items: - $ref: "#/definitions/Tag" - status: - type: "string" - description: "pet status in the store" - enum: - - "available" - - "pending" - - "sold" - title: "a Pet" - description: "A pet for sale in the pet store" - xml: - name: "Pet" - ApiResponse: - type: "object" - properties: - code: - type: "integer" - format: "int32" - type: - type: "string" - message: - type: "string" - title: "An uploaded response" - description: "Describes the result of uploading an image resource" -externalDocs: - description: "Find out more about Swagger" - url: "http://swagger.io" diff --git a/samples/server/petstore/rust-server/output/multipart-v3/.openapi-generator/VERSION b/samples/server/petstore/rust-server/output/multipart-v3/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/rust-server/output/multipart-v3/.openapi-generator/VERSION +++ b/samples/server/petstore/rust-server/output/multipart-v3/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-server/output/no-example-v3/.openapi-generator/VERSION b/samples/server/petstore/rust-server/output/no-example-v3/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/rust-server/output/no-example-v3/.openapi-generator/VERSION +++ b/samples/server/petstore/rust-server/output/no-example-v3/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator/VERSION b/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator/VERSION +++ b/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-server/output/ops-v3/.openapi-generator/VERSION b/samples/server/petstore/rust-server/output/ops-v3/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/rust-server/output/ops-v3/.openapi-generator/VERSION +++ b/samples/server/petstore/rust-server/output/ops-v3/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/VERSION b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/VERSION +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-server/output/ping-bearer-auth/.openapi-generator/VERSION b/samples/server/petstore/rust-server/output/ping-bearer-auth/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/rust-server/output/ping-bearer-auth/.openapi-generator/VERSION +++ b/samples/server/petstore/rust-server/output/ping-bearer-auth/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-server/output/rust-server-test/.openapi-generator/VERSION b/samples/server/petstore/rust-server/output/rust-server-test/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/.openapi-generator/VERSION +++ b/samples/server/petstore/rust-server/output/rust-server-test/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/scala-akka-http-server/.openapi-generator/FILES b/samples/server/petstore/scala-akka-http-server/.openapi-generator/FILES new file mode 100644 index 000000000000..cfcbab175e5d --- /dev/null +++ b/samples/server/petstore/scala-akka-http-server/.openapi-generator/FILES @@ -0,0 +1,15 @@ +README.md +build.sbt +src/main/scala/org/openapitools/server/AkkaHttpHelper.scala +src/main/scala/org/openapitools/server/Controller.scala +src/main/scala/org/openapitools/server/MultipartDirectives.scala +src/main/scala/org/openapitools/server/StringDirectives.scala +src/main/scala/org/openapitools/server/api/PetApi.scala +src/main/scala/org/openapitools/server/api/StoreApi.scala +src/main/scala/org/openapitools/server/api/UserApi.scala +src/main/scala/org/openapitools/server/model/ApiResponse.scala +src/main/scala/org/openapitools/server/model/Category.scala +src/main/scala/org/openapitools/server/model/Order.scala +src/main/scala/org/openapitools/server/model/Pet.scala +src/main/scala/org/openapitools/server/model/Tag.scala +src/main/scala/org/openapitools/server/model/User.scala diff --git a/samples/server/petstore/scala-akka-http-server/.openapi-generator/VERSION b/samples/server/petstore/scala-akka-http-server/.openapi-generator/VERSION index d99e7162d01f..d509cc92aa80 100644 --- a/samples/server/petstore/scala-akka-http-server/.openapi-generator/VERSION +++ b/samples/server/petstore/scala-akka-http-server/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.1.1-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/scala-akka-http-server/src/main/scala/org/openapitools/server/MultipartDirectives.scala b/samples/server/petstore/scala-akka-http-server/src/main/scala/org/openapitools/server/MultipartDirectives.scala index 79891d7095a8..2ebbd943db2f 100644 --- a/samples/server/petstore/scala-akka-http-server/src/main/scala/org/openapitools/server/MultipartDirectives.scala +++ b/samples/server/petstore/scala-akka-http-server/src/main/scala/org/openapitools/server/MultipartDirectives.scala @@ -1,6 +1,7 @@ package org.openapitools.server import java.io.File +import java.nio.file.Files import akka.annotation.ApiMayChange import akka.http.scaladsl.model.Multipart.FormData @@ -69,7 +70,7 @@ trait MultipartDirectives { object MultipartDirectives extends MultipartDirectives with FileUploadDirectives { val tempFileFromFileInfo: FileInfo => File = { - file: FileInfo => File.createTempFile(file.fileName, ".tmp") + file: FileInfo => Files.createTempFile(file.fileName, ".tmp").toFile() } } diff --git a/samples/server/petstore/spring-mvc-default-value/.openapi-generator/VERSION b/samples/server/petstore/spring-mvc-default-value/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/spring-mvc-default-value/.openapi-generator/VERSION +++ b/samples/server/petstore/spring-mvc-default-value/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc-default-value/src/main/java/org/openapitools/api/TestHeadersApi.java b/samples/server/petstore/spring-mvc-default-value/src/main/java/org/openapitools/api/TestHeadersApi.java index 016fb8657356..2d31a64a04d4 100644 --- a/samples/server/petstore/spring-mvc-default-value/src/main/java/org/openapitools/api/TestHeadersApi.java +++ b/samples/server/petstore/spring-mvc-default-value/src/main/java/org/openapitools/api/TestHeadersApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-default-value/src/main/java/org/openapitools/api/TestQueryParamsApi.java b/samples/server/petstore/spring-mvc-default-value/src/main/java/org/openapitools/api/TestQueryParamsApi.java index 14eeb6403601..a3f907809a00 100644 --- a/samples/server/petstore/spring-mvc-default-value/src/main/java/org/openapitools/api/TestQueryParamsApi.java +++ b/samples/server/petstore/spring-mvc-default-value/src/main/java/org/openapitools/api/TestQueryParamsApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-async/.openapi-generator/VERSION b/samples/server/petstore/spring-mvc-j8-async/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/spring-mvc-j8-async/.openapi-generator/VERSION +++ b/samples/server/petstore/spring-mvc-j8-async/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/AnotherFakeApi.java index 67f680d139b0..8326ab48c02c 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeApi.java index 3b25c6d7d78d..b301ad0b4855 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index d61dfa63e878..3de6e0e21889 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/PetApi.java index 0e5716fc1ad5..f2512f9eac34 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/StoreApi.java index b41f4bddc4bf..03fa53219d90 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/UserApi.java index 60a6ba8a507f..bc349aa67c0f 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-localdatetime/.openapi-generator/VERSION b/samples/server/petstore/spring-mvc-j8-localdatetime/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/spring-mvc-j8-localdatetime/.openapi-generator/VERSION +++ b/samples/server/petstore/spring-mvc-j8-localdatetime/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/AnotherFakeApi.java index 56e1534835b9..62b5e8c1c9ec 100644 --- a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeApi.java index a641e78829df..1d52ff9cf887 100644 --- a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index c17bd7071ef4..ce5242fa1b93 100644 --- a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/PetApi.java index 1f1ff854ce6b..6c50971728c1 100644 --- a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/StoreApi.java index ee1d1a1a1274..a18ef0803417 100644 --- a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/UserApi.java index d8256d4cb8dc..bdd829c2178f 100644 --- a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-no-nullable/.openapi-generator/VERSION b/samples/server/petstore/spring-mvc-no-nullable/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/spring-mvc-no-nullable/.openapi-generator/VERSION +++ b/samples/server/petstore/spring-mvc-no-nullable/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java index 56e1534835b9..62b5e8c1c9ec 100644 --- a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/FakeApi.java index 535060645a5e..9c17aee08e3d 100644 --- a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index c17bd7071ef4..ce5242fa1b93 100644 --- a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/PetApi.java index 1f1ff854ce6b..6c50971728c1 100644 --- a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/StoreApi.java index ee1d1a1a1274..a18ef0803417 100644 --- a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/UserApi.java index d8256d4cb8dc..bdd829c2178f 100644 --- a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-spring-pageable/.openapi-generator/VERSION b/samples/server/petstore/spring-mvc-spring-pageable/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/spring-mvc-spring-pageable/.openapi-generator/VERSION +++ b/samples/server/petstore/spring-mvc-spring-pageable/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java index 56e1534835b9..62b5e8c1c9ec 100644 --- a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java index 0033e1e5940a..b0b57f815bd6 100644 --- a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index c17bd7071ef4..ce5242fa1b93 100644 --- a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/PetApi.java index 3616754568d3..2e67f9eb6099 100644 --- a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java index ee1d1a1a1274..a18ef0803417 100644 --- a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/UserApi.java index d8256d4cb8dc..bdd829c2178f 100644 --- a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc/.openapi-generator/VERSION b/samples/server/petstore/spring-mvc/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/spring-mvc/.openapi-generator/VERSION +++ b/samples/server/petstore/spring-mvc/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/AnotherFakeApi.java index 56e1534835b9..62b5e8c1c9ec 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApi.java index 535060645a5e..9c17aee08e3d 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index c17bd7071ef4..ce5242fa1b93 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/PetApi.java index 1f1ff854ce6b..6c50971728c1 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/StoreApi.java index ee1d1a1a1274..a18ef0803417 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/UserApi.java index d8256d4cb8dc..bdd829c2178f 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/.openapi-generator/VERSION b/samples/server/petstore/springboot-beanvalidation-no-nullable/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java index 388462a95376..dfae7d61930c 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApi.java index 5a70cda84f72..68cec85a19ab 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 5967985c2540..d2215dd0d1be 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApi.java index 334bdc9a82e6..b9655c2c700f 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApi.java index 57b8bddb8816..69c047f7c677 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApi.java index e8f4fc3d844c..972cc8bc4682 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation/.openapi-generator/VERSION b/samples/server/petstore/springboot-beanvalidation/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/springboot-beanvalidation/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-beanvalidation/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApi.java index 56e1534835b9..62b5e8c1c9ec 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java index 535060645a5e..9c17aee08e3d 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index c17bd7071ef4..ce5242fa1b93 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApi.java index 1f1ff854ce6b..6c50971728c1 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApi.java index ee1d1a1a1274..a18ef0803417 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApi.java index d8256d4cb8dc..bdd829c2178f 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate-j8/.openapi-generator/VERSION b/samples/server/petstore/springboot-delegate-j8/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/springboot-delegate-j8/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-delegate-j8/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java index 958a16e9bb92..f4afb63f6185 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApi.java index ce0cdec40152..f085be2317d2 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 1cd4f8903465..572b49ba2a94 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/PetApi.java index b78cdfa71495..b7a84c916cfb 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/StoreApi.java index 57d70d7cd091..05cfb8f5758a 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApi.java index 96528d91dee0..5b3512235937 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate/.openapi-generator/VERSION b/samples/server/petstore/springboot-delegate/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/springboot-delegate/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-delegate/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java index 958a16e9bb92..f4afb63f6185 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java index ce0cdec40152..f085be2317d2 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 1cd4f8903465..572b49ba2a94 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java index b78cdfa71495..b7a84c916cfb 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java index 57d70d7cd091..05cfb8f5758a 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java index 96528d91dee0..5b3512235937 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-implicitHeaders/.openapi-generator/VERSION b/samples/server/petstore/springboot-implicitHeaders/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/springboot-implicitHeaders/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-implicitHeaders/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java index 84692f831dc0..0fa0742fe83a 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java index e30d8084ace4..e985e37bc09e 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index bb04ba91937f..3d7f2e2ea285 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java index d4e93dfa88e0..209a72ff9778 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java index 51ca3cba19e2..94057aa6fc58 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java index e36f0b478666..b60e3580cf6b 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive/.openapi-generator/VERSION b/samples/server/petstore/springboot-reactive/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/springboot-reactive/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-reactive/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java index 43517a22bf80..eea35ce51b89 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java index 22df9d55c342..33228158d4d3 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index f6bd5bc94220..15b48f22a526 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApi.java index 27aa83d6f198..41ed1eeccd35 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApi.java index 5e4c7dd51931..520c688e3fa4 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApi.java index d58ba4dd213b..2f3e0a55c9bd 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/.openapi-generator/VERSION b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java index 388462a95376..dfae7d61930c 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeApi.java index 7bab611bc094..54e73fc876d0 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 5967985c2540..d2215dd0d1be 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/PetApi.java index b6676ee8e79f..dcdb633acf62 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/StoreApi.java index 57b8bddb8816..69c047f7c677 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApi.java index e8f4fc3d844c..972cc8bc4682 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/.openapi-generator/VERSION b/samples/server/petstore/springboot-spring-pageable-delegatePattern/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/AnotherFakeApi.java index 958a16e9bb92..f4afb63f6185 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeApi.java index 0256dd794c24..02a920c8bf8b 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 1cd4f8903465..572b49ba2a94 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/PetApi.java index c493551f7049..0e5bdeffced3 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/StoreApi.java index 57d70d7cd091..05cfb8f5758a 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApi.java index 96528d91dee0..5b3512235937 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/.openapi-generator/VERSION b/samples/server/petstore/springboot-spring-pageable-without-j8/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java index 388462a95376..dfae7d61930c 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeApi.java index 7bab611bc094..54e73fc876d0 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 5967985c2540..d2215dd0d1be 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/PetApi.java index b6676ee8e79f..dcdb633acf62 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/StoreApi.java index 57b8bddb8816..69c047f7c677 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/UserApi.java index e8f4fc3d844c..972cc8bc4682 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable/.openapi-generator/VERSION b/samples/server/petstore/springboot-spring-pageable/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/springboot-spring-pageable/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-spring-pageable/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java index 56e1534835b9..62b5e8c1c9ec 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java index 0033e1e5940a..b0b57f815bd6 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index c17bd7071ef4..ce5242fa1b93 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/PetApi.java index 3616754568d3..2e67f9eb6099 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java index ee1d1a1a1274..a18ef0803417 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/UserApi.java index d8256d4cb8dc..bdd829c2178f 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-useoptional/.openapi-generator/VERSION b/samples/server/petstore/springboot-useoptional/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/springboot-useoptional/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-useoptional/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApi.java index 56e1534835b9..62b5e8c1c9ec 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java index f3315076f434..5360eef212b6 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index c17bd7071ef4..ce5242fa1b93 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApi.java index f4ad20eef3c8..581c9ec1d36f 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApi.java index ee1d1a1a1274..a18ef0803417 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApi.java index d8256d4cb8dc..bdd829c2178f 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-virtualan/.openapi-generator/VERSION b/samples/server/petstore/springboot-virtualan/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/springboot-virtualan/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-virtualan/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-virtualan/pom.xml b/samples/server/petstore/springboot-virtualan/pom.xml index 3dceb8a963e7..8dc39bea12e3 100644 --- a/samples/server/petstore/springboot-virtualan/pom.xml +++ b/samples/server/petstore/springboot-virtualan/pom.xml @@ -75,18 +75,13 @@ io.virtualan virtualan-plugin - 2.1.7 + 2.2.1 org.hsqldb hsqldb - 2.3.2 - - - org.springframework.boot - spring-boot-starter-data-jpa - 1.5.9.RELEASE + 2.5.0 diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/AnotherFakeApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/AnotherFakeApi.java index 31ff3bf73e1a..5ba806e0898f 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApi.java index 7eccddfa1fad..b3dcb0a94008 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApi.java index b7343dafc32a..a963e3199694 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/PetApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/PetApi.java index 6a36a1742d50..a83c6d8326d2 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/PetApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/StoreApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/StoreApi.java index 7d2ffbc696e5..e9cd51627cd0 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/StoreApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/UserApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/UserApi.java index 80d269c1b0c0..d730f7e2ab01 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/UserApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-virtualan/src/main/resources/application.properties b/samples/server/petstore/springboot-virtualan/src/main/resources/application.properties index cf5e33b68698..64073b52f1eb 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/resources/application.properties +++ b/samples/server/petstore/springboot-virtualan/src/main/resources/application.properties @@ -2,7 +2,7 @@ springfox.documentation.swagger.v2.path=/api-docs server.port=80 spring.jackson.date-format=org.openapitools.RFC3339DateFormat spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false -virtual.datasource.driver-class-name=org.hsqldb.jdbcDriver -virtual.datasource.jdbcurl=jdbc:hsqldb:mem:dataSource -virtual.datasource.username=sa -virtual.datasource.password= +virtualan.datasource.driver-class-name=org.hsqldb.jdbcDriver +virtualan.datasource.jdbcurl=jdbc:hsqldb:mem:dataSource +virtualan.datasource.username=sa +virtualan.datasource.password= diff --git a/samples/server/petstore/springboot/.openapi-generator/VERSION b/samples/server/petstore/springboot/.openapi-generator/VERSION index d509cc92aa80..6555596f9311 100644 --- a/samples/server/petstore/springboot/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/AnotherFakeApi.java index 56e1534835b9..62b5e8c1c9ec 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApi.java index 535060645a5e..9c17aee08e3d 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index c17bd7071ef4..ce5242fa1b93 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java index 1f1ff854ce6b..6c50971728c1 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java index ee1d1a1a1274..a18ef0803417 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java index d8256d4cb8dc..bdd829c2178f 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.1.1-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.2.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/shippable.yml b/shippable.yml index 5dc40c6fa41b..009806b31a34 100644 --- a/shippable.yml +++ b/shippable.yml @@ -21,7 +21,6 @@ build: - export PATH=/opt/gradle/gradle-5.6.4/bin:$PATH - gradle -v - java -version - - mvn --no-snapshot-updates --quiet clean install -Dmaven.javadoc.skip=true # ensure all modifications created by 'mature' generators are in the git repo # below move to CircleCI ./bin/utils/ensure-up-to-date # prepare environment for tests @@ -49,12 +48,3 @@ build: - mix --version # test samples defined in pom.xml - mvn --no-snapshot-updates --quiet verify -P samples.shippable -Dmaven.javadoc.skip=true - # test maven plugin - - mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/java-client.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error - - mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/multi-module/pom.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error - - mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/kotlin.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error - - mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/spring.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error - # test gradle plugin - - (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew buildGoSdk) - - (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew openApiGenerate) - diff --git a/website/src/dynamic/users.yml b/website/src/dynamic/users.yml index cbd789930a70..c8ff21541f90 100644 --- a/website/src/dynamic/users.yml +++ b/website/src/dynamic/users.yml @@ -1,3 +1,8 @@ +- + caption: "Aalborg University" + image: "img/companies/aalborg_university.png" + infoLink: "https://www.aau.dk/" + pinned: false - caption: "Adaptant Solutions AG" image: "img/companies/adaptant.png" @@ -413,6 +418,11 @@ image: "img/companies/telstra.svg" infoLink: "https://dev.telstra.com/" pinned: true +- + caption: The University of Aizu + image: "img/companies/uoa.png" + infoLink: "https://www.u-aizu.ac.jp/en/" + pinned: false - caption: "TravelTime platform" image: "img/companies/traveltime.jpg" @@ -448,6 +458,11 @@ image: "img/companies/viadee.jpg" infoLink: "https://www.viadee.de" pinned: false +- + caption: "VMware" + image: "img/companies/vmware.png" + infoLink: "https://www.vmware.com/" + pinned: false - caption: Vonage image: "img/companies/vonage.png" diff --git a/website/static/img/companies/aalborg_university.png b/website/static/img/companies/aalborg_university.png new file mode 100644 index 000000000000..5fcf0511d478 Binary files /dev/null and b/website/static/img/companies/aalborg_university.png differ diff --git a/website/static/img/companies/uoa.png b/website/static/img/companies/uoa.png new file mode 100644 index 000000000000..15edfd0ef3e8 Binary files /dev/null and b/website/static/img/companies/uoa.png differ diff --git a/website/static/img/companies/vmware.png b/website/static/img/companies/vmware.png new file mode 100644 index 000000000000..7e697256a9e1 Binary files /dev/null and b/website/static/img/companies/vmware.png differ